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.

77 lines
2.3 KiB

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