A collection of basic/generally desirable code I use across multiple C++ projects.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.4 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. #pragma once
  2. #ifndef ULE_ALLOC_H
  3. #define ULE_ALLOC_H
  4. #include "config.h"
  5. #include "types.h"
  6. // define a consistent memory allocation interface
  7. // trailing void* is a pointer to some allocator state, if relevant.
  8. // will be unused for malloc/calloc/realloc/free, as the allocator state is internal to the OS.
  9. // overloads should exist which do nothing with the trailing paramter.
  10. typedef void* (*mallocator) (size_t, void*);
  11. typedef void* (*callocator) (size_t, size_t, void*);
  12. typedef void* (*reallocator) (void*, size_t, void*);
  13. typedef void (*freeer) (void*, void*);
  14. typedef void (*clearer) ( void*);
  15. typedef void (*destroyer) ( void*);
  16. // operating system allocator wrappers
  17. extern void* pMalloc(size_t size);
  18. extern void* pMalloc(size_t size, void* allocatorState);
  19. extern void* pCalloc(size_t maxNumOfElements, size_t elementSize);
  20. extern void* pCalloc(size_t maxNumOfElements, size_t elementSize, void* allocatorState);
  21. extern void* pRealloc(void* buffer, size_t newSize);
  22. extern void* pRealloc(void* buffer, size_t newSize, void* allocatorState);
  23. extern void pFree(void* ptr);
  24. extern void pFree(void* ptr, void* allocatorState);
  25. extern void pFree(const void* ptr);
  26. extern void pFree(const void* ptr, void* allocatorState);
  27. struct Allocator {
  28. void* state;
  29. mallocator mallocate;
  30. callocator callocate;
  31. reallocator reallocate;
  32. freeer free; // releases a specific piece of memory
  33. clearer clear; // should release all the memory owned by this allocator at once.
  34. destroyer destroy; // releases all the memory owned by this allocator, and also destroys the allocator.
  35. static Allocator* GetDefault();
  36. Allocator() {
  37. this->state = null;
  38. this->mallocate = pMalloc;
  39. this->callocate = pCalloc;
  40. this->reallocate = pRealloc;
  41. this->free = pFree;
  42. this->clear = null;
  43. this->destroy = null;
  44. }
  45. Allocator(mallocator mallocate, freeer free) {
  46. this->state = null;
  47. this->mallocate = mallocate;
  48. this->callocate = null;
  49. this->reallocate = null;
  50. this->free = free;
  51. this->clear = null;
  52. this->destroy = null;
  53. }
  54. };
  55. struct Arena {
  56. u32 bufferSizeInBytes;
  57. u32 index;
  58. u8* buffer;
  59. static Arena* Init(u32 sizeInBytes = 1024);
  60. void* Alloc(u32 sizeInBytes);
  61. void Clear();
  62. };
  63. #endif