aboutsummaryrefslogtreecommitdiff
path: root/src/uniquekey.h
blob: 93aaf37cc3877b279ef47da06440689345aad73a (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
#pragma once

#include "compat.h"
#include "macros_and_utils.h"

#include <bit>

class UniqueKey
{
    private:

    uintptr_t m_storage;

    public:

    constexpr UniqueKey(uintptr_t val_)
#if LUAJIT_FLAVOR() == 64 // building against LuaJIT headers for 64 bits, light userdata is restricted to 47 significant bits, because LuaJIT uses the other bits for internal optimizations
    : m_storage{ val_ & 0x7fffffffffffull }
#else // LUAJIT_FLAVOR()
    : m_storage{ val_ }
#endif // LUAJIT_FLAVOR()
    {
    }
    constexpr UniqueKey(UniqueKey const& rhs_) = default;
    constexpr bool operator!=(UniqueKey const& rhs_) const
    {
        return m_storage != rhs_.m_storage;
    }
    constexpr bool operator==(UniqueKey const& rhs_) const
    {
        return m_storage == rhs_.m_storage;
    }

    void push(lua_State* const L) const
    {
        lua_pushlightuserdata(L, std::bit_cast<void*>(m_storage));
    }
    bool equals(lua_State* const L, int i) const
    {
        return lua_touserdata(L, i) == std::bit_cast<void*>(m_storage);
    }
    void query_registry(lua_State* const L) const
    {
        push(L);
        lua_rawget(L, LUA_REGISTRYINDEX);
    }
    template <typename OP>
    void set_registry(lua_State* L, OP operation_) const
    {
        // Note we can't check stack consistency because operation is not always a push (could be insert, replace, whatever)
        push(L);                              // ... key
        operation_(L);                        // ... key value
        lua_rawset(L, LUA_REGISTRYINDEX);     // ...
    }
};