aligned_alloc.hpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. Copyright 2014-2015 Glen Joseph Fernandes
  3. (glenjofe@gmail.com)
  4. Distributed under the Boost Software License, Version 1.0.
  5. (http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #ifndef BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP
  8. #define BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP
  9. #include <boost/align/detail/is_alignment.hpp>
  10. #include <boost/align/align.hpp>
  11. #include <boost/align/alignment_of.hpp>
  12. #include <boost/assert.hpp>
  13. #include <cstdlib>
  14. namespace boost {
  15. namespace alignment {
  16. inline void*
  17. aligned_alloc(std::size_t alignment, std::size_t size) BOOST_NOEXCEPT
  18. {
  19. BOOST_ASSERT(detail::is_alignment(alignment));
  20. enum {
  21. N = alignment_of<void*>::value
  22. };
  23. if (alignment < N) {
  24. alignment = N;
  25. }
  26. std::size_t n = size + alignment - N;
  27. void* p = std::malloc(sizeof(void*) + n);
  28. if (p) {
  29. void* r = static_cast<char*>(p) + sizeof(void*);
  30. (void)boost::alignment::align(alignment, size, r, n);
  31. *(static_cast<void**>(r) - 1) = p;
  32. p = r;
  33. }
  34. return p;
  35. }
  36. inline void
  37. aligned_free(void* ptr) BOOST_NOEXCEPT
  38. {
  39. if (ptr) {
  40. std::free(*(static_cast<void**>(ptr) - 1));
  41. }
  42. }
  43. } /* alignment */
  44. } /* boost */
  45. #endif