aboutsummaryrefslogtreecommitdiff
path: root/src/allocator.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/allocator.h')
-rw-r--r--src/allocator.h47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/allocator.h b/src/allocator.h
new file mode 100644
index 0000000..9a9c245
--- /dev/null
+++ b/src/allocator.h
@@ -0,0 +1,47 @@
1#pragma once
2
3// #################################################################################################
4
5// everything we need to provide to lua_newstate()
6class AllocatorDefinition
7{
8 public:
9 // xxh64 of string "kAllocatorVersion_1" generated at https://www.pelock.com/products/hash-calculator
10 static constexpr uintptr_t kAllocatorVersion{ static_cast<uintptr_t>(0xCF9D321B0DFB5715ull) };
11 uintptr_t version{ kAllocatorVersion };
12 lua_Alloc allocF{ nullptr };
13 void* allocUD{ nullptr };
14
15 [[nodiscard]] static void* operator new(size_t size_) noexcept = delete; // can't create one outside of a Lua state
16 [[nodiscard]] static void* operator new(size_t size_, lua_State* L_) noexcept { return lua_newuserdatauv(L_, size_, 0); }
17 // always embedded somewhere else or "in-place constructed" as a full userdata
18 // can't actually delete the operator because the compiler generates stack unwinding code that could call it in case of exception
19 static void operator delete([[maybe_unused]] void* p_, [[maybe_unused]] lua_State* L_) {}
20
21 AllocatorDefinition(uintptr_t const version_, lua_Alloc const allocF_, void* const allocUD_) noexcept
22 : version{ version_ }
23 , allocF{ allocF_ }
24 , allocUD{ allocUD_ }
25 {
26 }
27 AllocatorDefinition() = default;
28 AllocatorDefinition(AllocatorDefinition const& rhs_) = default;
29 AllocatorDefinition(AllocatorDefinition&& rhs_) = default;
30 AllocatorDefinition& operator=(AllocatorDefinition const& rhs_) = default;
31 AllocatorDefinition& operator=(AllocatorDefinition&& rhs_) = default;
32
33 void initFrom(lua_State* L_)
34 {
35 allocF = lua_getallocf(L_, &allocUD);
36 }
37
38 void* alloc(size_t nsize_)
39 {
40 return allocF(allocUD, nullptr, 0, nsize_);
41 }
42
43 void free(void* ptr_, size_t osize_)
44 {
45 std::ignore = allocF(allocUD, ptr_, osize_, 0);
46 }
47};