1 | #include <Common/AlignedBuffer.h> |
2 | |
3 | #include <Common/Exception.h> |
4 | #include <Common/formatReadable.h> |
5 | |
6 | |
7 | namespace DB |
8 | { |
9 | |
10 | namespace ErrorCodes |
11 | { |
12 | extern const int CANNOT_ALLOCATE_MEMORY; |
13 | } |
14 | |
15 | |
16 | void AlignedBuffer::alloc(size_t size, size_t alignment) |
17 | { |
18 | void * new_buf; |
19 | int res = ::posix_memalign(&new_buf, std::max(alignment, sizeof(void*)), size); |
20 | if (0 != res) |
21 | throwFromErrno("Cannot allocate memory (posix_memalign), size: " |
22 | + formatReadableSizeWithBinarySuffix(size) + ", alignment: " + formatReadableSizeWithBinarySuffix(alignment) + "." , |
23 | ErrorCodes::CANNOT_ALLOCATE_MEMORY, res); |
24 | buf = new_buf; |
25 | } |
26 | |
27 | void AlignedBuffer::dealloc() |
28 | { |
29 | if (buf) |
30 | ::free(buf); |
31 | } |
32 | |
33 | void AlignedBuffer::reset(size_t size, size_t alignment) |
34 | { |
35 | dealloc(); |
36 | alloc(size, alignment); |
37 | } |
38 | |
39 | AlignedBuffer::AlignedBuffer(size_t size, size_t alignment) |
40 | { |
41 | alloc(size, alignment); |
42 | } |
43 | |
44 | AlignedBuffer::~AlignedBuffer() |
45 | { |
46 | dealloc(); |
47 | } |
48 | |
49 | } |
50 | |