Skip to content

Commit

Permalink
fix: stack_alloc after sweep ai work
Browse files Browse the repository at this point in the history
  • Loading branch information
chocolacula committed Oct 15, 2023
1 parent 7d7c1d0 commit e9aa1b3
Showing 1 changed file with 26 additions and 55 deletions.
81 changes: 26 additions & 55 deletions library/include/er/stack_alloc.h
Original file line number Diff line number Diff line change
@@ -1,67 +1,38 @@
#include <memory>
#include <new>
#include <algorithm>
#include <memory>

namespace er {

template <typename T, size_t size>
class StackAlloc {
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using const_reference = const T&;
using size_type = size_t;
using difference_type = ptrdiff_t;
}

pointer allocate(size_type n) {
if (sizeof(T) * n > size) {
return static_cast<pointer>(::operator new(n * sizeof(T)));
} else {
return reinterpret_cast<pointer>(_stack);
}
}

void deallocate(pointer p, size_type n) {
if (sizeof(T) * n > size) {
::operator delete(p);
} else {
// do nothing, stack memory is automatically freed
}
}

template <typename U, typename... Args>
void construct(U* p, Args&&... args) {
new(p) U(std::forward<Args>(args)...);
public:
using value_type = T;
using size_type = size_t;
using difference_type = ptrdiff_t;

T* allocate(size_type n) {
if (sizeof(T) * n > size) {
return static_cast<T*>(::operator new(n * sizeof(T)));
}
return reinterpret_cast<T*>(_stack_mem);
}

template <typename U>
void destroy(U* p) {
p->~U();
void deallocate(T* p, size_type n) {
if (sizeof(T) * n > size) {
::operator delete(p);
}

size_type max_size() const noexcept {
return std::max<size_type>(1, size / sizeof(T));
}

pointer address(reference x) const noexcept {
return std::addressof(x);
}

const T* address(const_reference x) const noexcept {
return std::addressof(x);
}

StackAlloc() = default;
StackAlloc(const StackAlloc&) = default;
StackAlloc& operator=(const StackAlloc&) = default;
StackAlloc(StackAlloc&&) = default;
StackAlloc& operator=(StackAlloc&&) = default;
~StackAlloc() = default;

private:
alignas(T) char _stack[size];
// else do nothing, stack memory is automatically freed
}

StackAlloc() = default;
StackAlloc(const StackAlloc&) = default;
StackAlloc& operator=(const StackAlloc&) = default;
StackAlloc(StackAlloc&&) noexcept = default;
StackAlloc& operator=(StackAlloc&&) noexcept = default;
~StackAlloc() = default;

private:
alignas(T) uint8_t _stack_mem[size];
};

} // namespace er

0 comments on commit e9aa1b3

Please sign in to comment.