aligned_malloc.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #ifndef MEMORY_ALIGNED_MALLOC_H_
  2. #define MEMORY_ALIGNED_MALLOC_H_
  3. // The functions declared here
  4. // 1) Allocates block of aligned memory.
  5. // 2) Re-calculates a pointer such that it is aligned to a higher or equal
  6. // address.
  7. // Note: alignment must be a power of two. The alignment is in bytes.
  8. #include <stddef.h>
  9. // Returns a pointer to the first boundry of |alignment| bytes following the
  10. // address of |ptr|.
  11. // Note that there is no guarantee that the memory in question is available.
  12. // |ptr| has no requirements other than it can't be NULL.
  13. void* GetRightAlign(const void* ptr, size_t alignment);
  14. // Allocates memory of |size| bytes aligned on an |alignment| boundry.
  15. // The return value is a pointer to the memory. Note that the memory must
  16. // be de-allocated using AlignedFree.
  17. void* AlignedMalloc(size_t size, size_t alignment);
  18. // De-allocates memory created using the AlignedMalloc() API.
  19. void AlignedFree(void* mem_block);
  20. // Templated versions to facilitate usage of aligned malloc without casting
  21. // to and from void*.
  22. template <typename T>
  23. T* GetRightAlign(const T* ptr, size_t alignment) {
  24. return reinterpret_cast<T*>(
  25. GetRightAlign(reinterpret_cast<const void*>(ptr), alignment));
  26. }
  27. template <typename T>
  28. T* AlignedMalloc(size_t size, size_t alignment) {
  29. return reinterpret_cast<T*>(AlignedMalloc(size, alignment));
  30. }
  31. // Deleter for use with unique_ptr. E.g., use as
  32. // std::unique_ptr<Foo, AlignedFreeDeleter> foo;
  33. struct AlignedFreeDeleter {
  34. inline void operator()(void* ptr) const { AlignedFree(ptr); }
  35. };
  36. #endif // RTC_BASE_MEMORY_ALIGNED_MALLOC_H_