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