🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3 KiB

  1. #include "config.h"
  2. #include "almalloc.h"
  3. #include <cassert>
  4. #include <cstddef>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <memory>
  8. #ifdef HAVE_MALLOC_H
  9. #include <malloc.h>
  10. #endif
  11. void *al_malloc(size_t alignment, size_t size)
  12. {
  13. assert((alignment & (alignment-1)) == 0);
  14. alignment = std::max(alignment, alignof(std::max_align_t));
  15. #if defined(HAVE_POSIX_MEMALIGN)
  16. void *ret{};
  17. if(posix_memalign(&ret, alignment, size) == 0)
  18. return ret;
  19. return nullptr;
  20. #elif defined(HAVE__ALIGNED_MALLOC)
  21. return _aligned_malloc(size, alignment);
  22. #else
  23. size_t total_size{size + alignment-1 + sizeof(void*)};
  24. void *base{std::malloc(total_size)};
  25. if(base != nullptr)
  26. {
  27. void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
  28. total_size -= sizeof(void*);
  29. std::align(alignment, size, aligned_ptr, total_size);
  30. *(static_cast<void**>(aligned_ptr)-1) = base;
  31. base = aligned_ptr;
  32. }
  33. return base;
  34. #endif
  35. }
  36. void *al_calloc(size_t alignment, size_t size)
  37. {
  38. void *ret{al_malloc(alignment, size)};
  39. if(ret) std::memset(ret, 0, size);
  40. return ret;
  41. }
  42. void al_free(void *ptr) noexcept
  43. {
  44. #if defined(HAVE_POSIX_MEMALIGN)
  45. std::free(ptr);
  46. #elif defined(HAVE__ALIGNED_MALLOC)
  47. _aligned_free(ptr);
  48. #else
  49. if(ptr != nullptr)
  50. std::free(*(static_cast<void**>(ptr) - 1));
  51. #endif
  52. }