mempools.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #pragma once
  2. #include "utils.h"
  3. #include <stddef.h>
  4. struct MemoryPool {
  5. void *(*alloc)(struct MemoryPool *pool, size_t size);
  6. void (*free)(struct MemoryPool *pool, void *ptr);
  7. };
  8. #define POOL_ALLOC(p, sz) ((p)->alloc(p, sz))
  9. #define POOL_FREE(p, ptr) ((p)->free(p, ptr))
  10. struct TemporaryPool {
  11. char *storage;
  12. size_t size, cursor;
  13. };
  14. static inline void *tmpGetCursor(const struct TemporaryPool *tmp) {
  15. return tmp->storage + tmp->cursor;
  16. }
  17. static inline size_t tmpGetLeft(const struct TemporaryPool *tmp) {
  18. return tmp->size - tmp->cursor;
  19. }
  20. static inline void *tmpAdvance(struct TemporaryPool *tmp, size_t size) {
  21. if (tmp->size - tmp->cursor < size)
  22. return 0;
  23. void *ret = tmp->storage + tmp->cursor;
  24. tmp->cursor += size;
  25. return ret;
  26. }
  27. static inline void tmpReturn(struct TemporaryPool *tmp, size_t size) {
  28. ASSERT(size <= tmp->cursor);
  29. tmp->cursor -= size;
  30. }
  31. static inline void tmpReturnToPosition(struct TemporaryPool *tmp, void *marker) {
  32. ASSERT((char*)marker >= tmp->storage);
  33. const size_t to_release = tmp->cursor - ((char*)marker - tmp->storage);
  34. tmpReturn(tmp, to_release);
  35. }