Repository navigation
Expand file tree
/
Copy pathIsolateStateBag.h
More file actions
76 lines (62 loc) · 2.33 KB
/
Copy pathIsolateStateBag.h
File metadata and controls
76 lines (62 loc) · 2.33 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#ifndef NATIVESCRIPT_COMMON_ISOLATE_STATE_BAG_H_
#define NATIVESCRIPT_COMMON_ISOLATE_STATE_BAG_H_
#include <array>
#include <cstddef>
namespace nativescript::common {
// One runtime's per-isolate subsystem state: each state type T gets one
// default-constructed instance, created on first use. Nothing is shared
// between runtimes, so there is nothing to lock: runtimes start and tear down
// on their own threads, and each touches only its own bag, from its isolate's
// thread.
//
// The bag stays usable through all of teardown. Close() destroys every state
// and makes the bag refuse to create more; the runtime calls it once, as late
// as it can, while the isolate is still alive, so a state may hold
// v8::Global members.
class IsolateStateBag {
public:
IsolateStateBag() = default;
IsolateStateBag(const IsolateStateBag&) = delete;
IsolateStateBag& operator=(const IsolateStateBag&) = delete;
~IsolateStateBag() { Close(); }
// The instance, created if needed; null once closed. Isolate thread only.
template <typename T>
T* Get() {
Slot& slot = slots_[kSlotIndex<T>];
if (slot.value != nullptr) [[likely]] {
return static_cast<T*>(slot.value);
}
if (closed_) {
return nullptr;
}
slot.value = new T();
slot.destroy = [](void* value) { delete static_cast<T*>(value); };
return static_cast<T*>(slot.value);
}
// The instance if one exists; never creates. A thread other than the
// isolate's may call it while holding the isolate's Locker.
template <typename T>
T* Existing() const {
return static_cast<T*>(slots_[kSlotIndex<T>].value);
}
// Refuses further creation, then destroys every state, highest slot first.
// Idempotent.
void Close();
bool IsClosed() const { return closed_; }
// More state types than this abort at load time; raise it then.
static constexpr size_t kCapacity = 48;
private:
struct Slot {
void* value = nullptr;
void (*destroy)(void*) = nullptr;
};
static size_t ClaimSlotIndex();
// Claimed while the library loads, so a lookup reads a constant instead of
// a function-local static's guard.
template <typename T>
static inline const size_t kSlotIndex = ClaimSlotIndex();
std::array<Slot, kCapacity> slots_{};
bool closed_ = false;
};
} // namespace nativescript::common
#endif // NATIVESCRIPT_COMMON_ISOLATE_STATE_BAG_H_