StackAllocator.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <iostream>
  2. #include "memory/StackAllocator.h"
  3. static constexpr int MAX_BYTES = 50 * 1024 * 1024;
  4. alignas(16) static char data[MAX_BYTES];
  5. static int index = 0;
  6. static int lastIndex = 0;
  7. StackAllocator::Pointer incrementIndex(int inc) {
  8. StackAllocator::Pointer p = {lastIndex, index};
  9. lastIndex = index;
  10. if((inc & 0xF) != 0) {
  11. inc = (inc & ~0xF) + 16;
  12. }
  13. index += inc;
  14. return p;
  15. }
  16. StackAllocator::Pointer StackAllocator::allocate(int bytesPerElement, int& elements) {
  17. int bytes = bytesPerElement * elements;
  18. if(index + bytes <= MAX_BYTES) {
  19. return incrementIndex(bytes);
  20. }
  21. elements = (MAX_BYTES - index) / bytesPerElement;
  22. return incrementIndex(bytesPerElement * elements);
  23. }
  24. void StackAllocator::free(const Pointer& p) {
  25. if(p.pointer > index) {
  26. return;
  27. }
  28. index = p.pointer;
  29. lastIndex = p.lastPointer;
  30. }
  31. int StackAllocator::grow(const Pointer& p, int bytesPerElement, int elements) {
  32. if(p.pointer != lastIndex) {
  33. return 0;
  34. }
  35. int bytes = bytesPerElement * elements;
  36. if(index + bytes <= MAX_BYTES) {
  37. index += bytes;
  38. return elements;
  39. }
  40. elements = (MAX_BYTES - index) / bytesPerElement;
  41. index += bytesPerElement * elements;
  42. return elements;
  43. }
  44. void* StackAllocator::get(const Pointer& p) {
  45. return data + p.pointer;
  46. }