ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
chain.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4
5namespace esphome {
6
12template<typename Next, typename Owner> class ChainLink {
13 public:
14 bool is_owner() const { return reinterpret_cast<uintptr_t>(this->ptr_) & OWNER_TAG; }
16 Next *next() const { return this->is_owner() ? nullptr : this->ptr_; }
18 Owner *owner() const { return reinterpret_cast<Owner *>(reinterpret_cast<char *>(this->ptr_) - OWNER_TAG); }
20 Next **next_slot() {
21 static_assert(alignof(Next) > OWNER_TAG, "a node address must leave the owner tag bit free");
22 return &this->ptr_;
23 }
24 void set_next(Next *next) {
25 static_assert(alignof(Next) > OWNER_TAG, "a node address must leave the owner tag bit free");
26 this->ptr_ = next;
27 }
29 void set_owner(Owner *owner) { this->ptr_ = tagged(owner); }
31 static Next *tagged(Owner *owner) {
32 static_assert(alignof(Owner) > OWNER_TAG, "the owner tag needs a free low bit");
33 char *base = reinterpret_cast<char *>(owner);
34 // The analyzer cannot see that an owner read back through owner() is non-null
35 // NOLINTNEXTLINE(clang-analyzer-core.NullPointerArithm)
36 return reinterpret_cast<Next *>(base + OWNER_TAG);
37 }
39 void set(Next *next, Owner *owner) {
40 if (next != nullptr) {
41 this->set_next(next);
42 } else {
43 this->set_owner(owner);
44 }
45 }
46
47 protected:
48 static constexpr uintptr_t OWNER_TAG = 1;
49 // A pointer, not a uintptr_t, so no integer is ever cast back to a pointer
50 Next *ptr_{nullptr};
51};
52
54template<typename Node, typename Owner> class ChainNode {
55 // Only Node can be built on this base
56 friend Node;
57 ChainNode() = default;
58
59 protected:
61 Node *chain_last_() {
62 Node *node = static_cast<Node *>(this);
63 while (!node->link_.is_owner())
64 node = node->link_.next();
65 return node;
66 }
68 Owner *chain_owner_() { return this->chain_last_()->link_.owner(); }
69
72};
73
74} // namespace esphome
Base for a node of a ChainLink chain: holds the link and finds the chain's owner.
Definition chain.h:54
ChainLink< Node, Owner > link_
The next node, or the owner on the last node.
Definition chain.h:71
Node * chain_last_()
Only for a chain that ends in its owner, never in nullptr.
Definition chain.h:61
Owner * chain_owner_()
Walks to the end of the chain on every call.
Definition chain.h:68