2#ifndef CEL_RUNTIME_DETAIL_RETIREMENT_HPP
3#define CEL_RUNTIME_DETAIL_RETIREMENT_HPP
10namespace cel::detail {
11static_assert(std::atomic<std::size_t>::is_always_lock_free,
12 "runtime ownership requires lock-free reference counts");
13class retirement_queue;
19struct retirement_node {
22 std::atomic<std::size_t> owners{1};
23 retirement_node* next =
nullptr;
24 void (*dispose)(retirement_node&, retirement_queue&)
noexcept;
31 explicit retirement_node(
void (*operation)(retirement_node&, retirement_queue&)
noexcept) :
40class retirement_queue {
44 retirement_node* _pending =
nullptr;
48 retirement_queue() noexcept = default;
50 retirement_queue(const retirement_queue&) = delete;
52 retirement_queue& operator=(const retirement_queue&) = delete;
59 auto* current = _pending;
60 _pending = current->next;
61 current->next =
nullptr;
62 current->dispose(*current, *
this);
71 void release(retirement_node* node)
noexcept {
74 if (node && node->owners.fetch_sub(1, std::memory_order_acq_rel) == 1) {
75 node->next = _pending;
96 retirement_node* _node =
nullptr;
100 retirement_ptr() noexcept = default;
104 explicit retirement_ptr(std::remove_const_t<T>* node) noexcept : _node(node) {}
106 retirement_ptr(
const retirement_ptr& other) noexcept : _node(other._node) {
107 if (_node) _node->owners.fetch_add(1, std::memory_order_relaxed);
110 retirement_ptr(retirement_ptr&& other) noexcept : _node(std::exchange(other._node,
nullptr)) {}
115 retirement_queue queue;
124 retirement_ptr& operator=(
const retirement_ptr& other)
noexcept {
125 retirement_ptr next(other);
134 retirement_ptr& operator=(retirement_ptr&& other)
noexcept {
135 if (
this != &other) {
136 retirement_ptr next(std::move(other));
142 void swap(retirement_ptr& other)
noexcept { std::swap(_node, other._node); }
146 void retire(retirement_queue& queue)
noexcept { queue.release(std::exchange(_node,
nullptr)); }
148 explicit operator bool() const noexcept {
return _node !=
nullptr; }
152 T* get() const noexcept {
return static_cast<T*
>(_node); }
154 friend bool operator==(
const retirement_ptr&,
const retirement_ptr&)
noexcept =
default;
160 T* operator->() const noexcept {