Imported Upstream version 1.57.0
[platform/upstream/boost.git] / boost / align / detail / aligned_alloc.hpp
1 /*
2  (c) 2014 Glen Joseph Fernandes
3  glenjofe at gmail dot com
4
5  Distributed under the Boost Software
6  License, Version 1.0.
7  http://boost.org/LICENSE_1_0.txt
8 */
9 #ifndef BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP
10 #define BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP
11
12 #include <boost/assert.hpp>
13 #include <boost/config.hpp>
14 #include <boost/align/align.hpp>
15 #include <boost/align/alignment_of.hpp>
16 #include <boost/align/detail/is_alignment.hpp>
17 #include <cstdlib>
18
19 namespace boost {
20     namespace alignment {
21         inline void* aligned_alloc(std::size_t alignment,
22             std::size_t size) BOOST_NOEXCEPT
23         {
24             BOOST_ASSERT(detail::is_alignment(alignment));
25             if (alignment < alignment_of<void*>::value) {
26                 alignment = alignment_of<void*>::value;
27             }
28             std::size_t n = size + alignment - 1;
29             void* p1 = 0;
30             void* p2 = std::malloc(n + sizeof p1);
31             if (p2) {
32                 p1 = static_cast<char*>(p2) + sizeof p1;
33                 (void)align(alignment, size, p1, n);
34                 *(static_cast<void**>(p1) - 1) = p2;
35             }
36             return p1;
37         }
38
39         inline void aligned_free(void* ptr)
40             BOOST_NOEXCEPT
41         {
42             if (ptr) {
43                 void* p = *(static_cast<void**>(ptr) - 1);
44                 std::free(p);
45             }
46         }
47     }
48 }
49
50 #endif