Skip to content

Commit aea99c2

Browse files
committed
fix: rework allocator for alignment mode
1 parent e842305 commit aea99c2

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

include/plg/allocator.hpp

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,26 +47,33 @@ namespace plg {
4747

4848
size_type size = n * sizeof(T);
4949
if (std::is_constant_evaluated()) {
50-
return static_cast<T*>(::operator new(size));
50+
if constexpr (alignof(T) > alignof(std::max_align_t)) {
51+
return static_cast<T*>(::operator new(size, std::align_val_t{alignof(T)}));
52+
} else {
53+
return static_cast<T*>(::operator new(size));
54+
}
5155
} else {
5256
return malloc_allocate(size);
5357
}
5458
}
5559

5660
constexpr void deallocate(T* p, [[maybe_unused]] size_type n) {
5761
if (std::is_constant_evaluated()) {
58-
::operator delete(p);
62+
if constexpr (alignof(T) > alignof(std::max_align_t)) {
63+
::operator delete(p, std::align_val_t{alignof(T)});
64+
} else {
65+
::operator delete(p);
66+
}
5967
} else {
60-
std::free(p);
68+
malloc_deallocate(p);
6169
}
6270
}
6371

6472
private:
6573
static T* malloc_allocate(size_type size) {
6674
T* ret;
6775
if constexpr (alignof(T) > alignof(std::max_align_t)) {
68-
size_type aligned_size = (size + (alignof(T) - 1)) & ~(alignof(T) - 1);
69-
ret = static_cast<T*>(aligned_allocate(alignof(T), aligned_size));
76+
ret = static_cast<T*>(aligned_allocate(size));
7077
} else {
7178
ret = static_cast<T*>(std::malloc(size));
7279
}
@@ -76,6 +83,14 @@ namespace plg {
7683
return ret;
7784
}
7885

86+
static void malloc_deallocate(T* ptr) {
87+
if constexpr (alignof(T) > alignof(std::max_align_t)) {
88+
aligned_deallocate(ptr);
89+
} else {
90+
std::free(ptr);
91+
}
92+
}
93+
7994
[[noreturn]] static void throw_bad_array_new_length() {
8095
PLUGIFY_THROW("bad array new length", std::bad_array_new_length);
8196
}
@@ -84,11 +99,20 @@ namespace plg {
8499
PLUGIFY_THROW("bad allocation", std::bad_alloc);
85100
}
86101

87-
static void* aligned_allocate(size_type alignment, size_type size) {
102+
static void* aligned_allocate(size_type size) {
103+
#if PLUGIFY_PLATFORM_WINDOWS
104+
return _aligned_malloc(size, alignof(T));
105+
#else
106+
size_type aligned_size = (size + (alignof(T) - 1)) & ~(alignof(T) - 1);
107+
return std::aligned_alloc(alignof(T), aligned_size);
108+
#endif // PLUGIFY_PLATFORM_WINDOWS
109+
}
110+
111+
static void aligned_deallocate(void* ptr) {
88112
#if PLUGIFY_PLATFORM_WINDOWS
89-
return _aligned_malloc(size, alignment);
113+
_aligned_free(ptr);
90114
#else
91-
return std::aligned_alloc(alignment, size);
115+
std::free(ptr);
92116
#endif // PLUGIFY_PLATFORM_WINDOWS
93117
}
94118
};

0 commit comments

Comments
 (0)