mempools.h 958 B

12345678910111213141516171819202122232425262728293031323334
  1. #pragma once
  2. #include "common.h"
  3. #include <stddef.h>
  4. struct Stack {
  5. char *storage;
  6. size_t size, cursor;
  7. };
  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. }