mempools.h 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #pragma once
  2. #include "common.h"
  3. #include <stddef.h>
  4. typedef struct Stack {
  5. char *storage;
  6. size_t size, cursor;
  7. } Stack;
  8. static inline void *stackGetCursor(const struct Stack *stack) {
  9. return stack->storage + stack->cursor;
  10. }
  11. static inline size_t stackGetFree(const struct Stack *stack) {
  12. return stack->size - stack->cursor;
  13. }
  14. static inline void *stackAlloc(struct Stack *stack, size_t size) {
  15. size = 4 * ((size + 3) / 4); // alignment
  16. if (stack->size - stack->cursor < size)
  17. return 0;
  18. void *ret = stack->storage + stack->cursor;
  19. stack->cursor += size;
  20. return ret;
  21. }
  22. static inline void stackFree(struct Stack *stack, size_t size) {
  23. ASSERT(size <= stack->cursor);
  24. stack->cursor -= size;
  25. }
  26. static inline void stackFreeUpToPosition(struct Stack *stack, void *marker) {
  27. ASSERT((char*)marker >= stack->storage);
  28. const size_t marker_pos = ((char*)marker - stack->storage);
  29. ASSERT(marker_pos <= stack->cursor);
  30. stackFree(stack, stack->cursor - marker_pos);
  31. }
  32. struct Memories {
  33. struct Stack *temp;
  34. struct Stack *persistent;
  35. };