memory.h 986 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #pragma once
  2. #ifndef CACHE_LINE_SIZE
  3. #define CACHE_LINE_SIZE 64
  4. #endif
  5. #define CONCAT(a, b) a##b
  6. #define LABEL(a) CONCAT(UniqueName_, a)
  7. #define UNIQUE_NAME LABEL(__LINE__)
  8. #define CACHE_LINE_PADDING char UNIQUE_NAME[CACHE_LINE_SIZE];
  9. static inline void* MallocAligned(size_t size, size_t alignment) {
  10. void** ptr = (void**)malloc(size + alignment + sizeof(size_t*));
  11. if (!ptr) {
  12. return nullptr;
  13. }
  14. size_t mask = ~(alignment - 1);
  15. intptr_t roundedDown = intptr_t(ptr) & mask;
  16. void** alignedPtr = (void**)(roundedDown + alignment);
  17. alignedPtr[-1] = ptr;
  18. return alignedPtr;
  19. }
  20. static inline void FreeAligned(void* ptr) {
  21. if (!ptr) {
  22. return;
  23. }
  24. void** typedPtr = (void**)ptr;
  25. void* originalPtr = typedPtr[-1];
  26. free(originalPtr);
  27. }
  28. static inline void* MallocCacheAligned(size_t size) {
  29. return MallocAligned(size, CACHE_LINE_SIZE);
  30. }
  31. static inline void FreeCacheAligned(void* ptr) {
  32. return FreeAligned(ptr);
  33. }