Phasor 2.2.0
Stack VM based Programming Language
Loading...
Searching...
No Matches
handle.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <unordered_map>
4#include <cstdint>
5
6namespace HandleSystem
7{
8using HandleId = uint32_t;
9
11{
12 static HandleId id = 1;
13 return id;
14}
15
16template <typename T> struct Table
17{
18 static std::unordered_map<HandleId, T> &idToHandle()
19 {
20 static std::unordered_map<HandleId, T> map;
21 return map;
22 }
23
24 static std::unordered_map<T, HandleId> &handleToId()
25 {
26 static std::unordered_map<T, HandleId> map;
27 return map;
28 }
29};
30
31template <typename T> inline HandleId store(T handle)
32{
33 if (!handle)
34 return 0;
35
36 auto &h2i = Table<T>::handleToId();
37 auto &i2h = Table<T>::idToHandle();
38
39 auto it = h2i.find(handle);
40 if (it != h2i.end())
41 return it->second;
42
43 HandleId id = nextId()++;
44 h2i[handle] = id;
45 i2h[id] = handle;
46 return id;
47}
48
49template <typename T> inline T resolve(HandleId id)
50{
51 if (id == 0)
52 return T{};
53
54 auto &i2h = Table<T>::idToHandle();
55 auto it = i2h.find(id);
56 if (it == i2h.end())
57 return T{};
58
59 return it->second;
60}
61
62template <typename T> inline void remove(HandleId id)
63{
64 auto &i2h = Table<T>::idToHandle();
65 auto &h2i = Table<T>::handleToId();
66
67 auto it = i2h.find(id);
68 if (it == i2h.end())
69 return;
70
71 h2i.erase(it->second);
72 i2h.erase(it);
73}
74} // namespace HandleSystem
HandleId store(T handle)
Definition handle.hpp:31
T resolve(HandleId id)
Definition handle.hpp:49
void remove(HandleId id)
Definition handle.hpp:62
uint32_t HandleId
Definition handle.hpp:8
HandleId & nextId()
Definition handle.hpp:10
static std::unordered_map< HandleId, T > & idToHandle()
Definition handle.hpp:18
static std::unordered_map< T, HandleId > & handleToId()
Definition handle.hpp:24