Skip to main content

cranpose_foundation/modifier/
chain_node_ref.rs

1//! Read-only handles on the positions of a [`ModifierNodeChain`], and the
2//! iterator over them.
3
4use super::{ModifierNode, ModifierNodeChain, NodeCapabilities, NodePath, PlainElement, PlainFns};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7enum TraversalDirection {
8    Forward,
9    Backward,
10}
11
12/// Iterator walking a modifier chain by indexing into its order.
13pub struct ModifierChainIter<'a> {
14    chain: &'a ModifierNodeChain,
15    cursor: usize,
16    remaining: usize,
17    direction: TraversalDirection,
18}
19
20impl<'a> ModifierChainIter<'a> {
21    pub(super) fn forward(chain: &'a ModifierNodeChain) -> Self {
22        Self {
23            chain,
24            cursor: 0,
25            remaining: chain.order_len(),
26            direction: TraversalDirection::Forward,
27        }
28    }
29
30    pub(super) fn backward(chain: &'a ModifierNodeChain) -> Self {
31        let len = chain.order_len();
32        Self {
33            chain,
34            cursor: len.wrapping_sub(1),
35            remaining: len,
36            direction: TraversalDirection::Backward,
37        }
38    }
39}
40
41impl<'a> Iterator for ModifierChainIter<'a> {
42    type Item = ModifierChainNodeRef<'a>;
43
44    #[inline]
45    fn next(&mut self) -> Option<Self::Item> {
46        if self.remaining == 0 {
47            return None;
48        }
49        let node_ref = self.chain.node_ref(ChainPosition::Node(self.cursor));
50        self.remaining -= 1;
51        match self.direction {
52            TraversalDirection::Forward => self.cursor += 1,
53            TraversalDirection::Backward => self.cursor = self.cursor.wrapping_sub(1),
54        }
55        Some(node_ref)
56    }
57
58    #[inline]
59    fn size_hint(&self) -> (usize, Option<usize>) {
60        (self.remaining, Some(self.remaining))
61    }
62}
63
64impl ExactSizeIterator for ModifierChainIter<'_> {}
65impl std::iter::FusedIterator for ModifierChainIter<'_> {}
66
67/// A cheap read-only handle on one position of a [`ModifierNodeChain`]: a node or the head or tail
68/// marker. Obtain it from `head`, `tail` or the chain iterators and walk the chain with `parent`
69/// and `child`.
70#[derive(Clone)]
71pub struct ModifierChainNodeRef<'a> {
72    pub(super) chain: &'a ModifierNodeChain,
73    pub(super) position: ChainPosition,
74}
75
76// Where a node ref points: the head marker, the node at an index of the
77// chain's order, or the tail marker.
78#[derive(Clone, Copy)]
79pub(super) enum ChainPosition {
80    Head,
81    Node(usize),
82    Tail,
83}
84
85impl ModifierChainNodeRef<'_> {
86    fn path(&self) -> Option<NodePath> {
87        match self.position {
88            ChainPosition::Node(index) => Some(self.chain.order_at(index).0),
89            ChainPosition::Head | ChainPosition::Tail => None,
90        }
91    }
92
93    /// The table and the words of the plain element at this position.
94    #[inline]
95    pub fn plain_words(&self) -> Option<(&'static PlainFns, &[u32])> {
96        let path = self.path()?;
97        path.delegates()
98            .is_empty()
99            .then(|| self.chain.plain_words(path.entry()))
100            .flatten()
101    }
102
103    /// The value of the plain element at this position, when it is an `E`.
104    #[inline]
105    pub fn plain<E: PlainElement>(&self) -> Option<E> {
106        let (fns, words) = self.plain_words()?;
107        fns.read(words)
108    }
109
110    /// Provides access to the node via a closure, properly handling RefCell borrows.
111    /// Returns None for sentinel nodes and for plain elements, which have no node.
112    pub fn with_node<R>(&self, f: impl FnOnce(&dyn ModifierNode) -> R) -> Option<R> {
113        self.chain.with_path(self.path()?, f)
114    }
115
116    /// Returns the parent reference, including sentinel head when applicable.
117    #[inline]
118    pub fn parent(&self) -> Option<Self> {
119        let position = match self.position {
120            ChainPosition::Head => return None,
121            ChainPosition::Node(index) => index.checked_sub(1),
122            ChainPosition::Tail => self.chain.order_len().checked_sub(1),
123        }
124        .map_or(ChainPosition::Head, ChainPosition::Node);
125        Some(self.chain.node_ref(position))
126    }
127
128    /// Returns the child reference, including sentinel tail for the last entry.
129    #[inline]
130    pub fn child(&self) -> Option<Self> {
131        let next = match self.position {
132            ChainPosition::Head => 0,
133            ChainPosition::Node(index) => index + 1,
134            ChainPosition::Tail => return None,
135        };
136        let position = if next < self.chain.order_len() {
137            ChainPosition::Node(next)
138        } else {
139            ChainPosition::Tail
140        };
141        Some(self.chain.node_ref(position))
142    }
143
144    /// Returns the capability mask for this specific node.
145    #[inline]
146    pub fn kind_set(&self) -> NodeCapabilities {
147        match self.position {
148            ChainPosition::Node(index) => self.chain.order_at(index).1,
149            ChainPosition::Head | ChainPosition::Tail => NodeCapabilities::empty(),
150        }
151    }
152
153    /// Returns the entry index backing this node when it is part of the chain.
154    pub fn entry_index(&self) -> Option<usize> {
155        self.path().map(|path| path.entry())
156    }
157
158    /// Returns how many delegate hops separate this node from its root element.
159    pub fn delegate_depth(&self) -> usize {
160        self.path().map_or(0, |path| path.delegates().len())
161    }
162
163    /// Returns the aggregated capability mask for the subtree rooted at this node.
164    #[inline]
165    pub fn aggregate_child_capabilities(&self) -> NodeCapabilities {
166        match self.position {
167            ChainPosition::Head => self.chain.aggregated_capabilities,
168            ChainPosition::Node(index) => self.chain.order_at(index).2,
169            ChainPosition::Tail => NodeCapabilities::empty(),
170        }
171    }
172
173    /// Returns true if this reference targets the sentinel head.
174    pub fn is_head(&self) -> bool {
175        matches!(self.position, ChainPosition::Head)
176    }
177
178    /// Returns true if this reference targets the sentinel tail.
179    pub fn is_tail(&self) -> bool {
180        matches!(self.position, ChainPosition::Tail)
181    }
182
183    /// Returns true if this reference targets either sentinel.
184    pub fn is_sentinel(&self) -> bool {
185        matches!(self.position, ChainPosition::Head | ChainPosition::Tail)
186    }
187
188    /// Returns true if this node has any capability bits present in `mask`.
189    pub fn has_capability(&self, mask: NodeCapabilities) -> bool {
190        !mask.is_empty() && self.kind_set().intersects(mask)
191    }
192
193    /// Visits descendant nodes, optionally including `self`, in insertion order.
194    pub fn visit_descendants<F>(self, include_self: bool, mut f: F)
195    where
196        F: FnMut(Self),
197    {
198        let mut current = if include_self {
199            Some(self)
200        } else {
201            self.child()
202        };
203        while let Some(node) = current {
204            if node.is_tail() {
205                break;
206            }
207            if !node.is_sentinel() {
208                f(node.clone());
209            }
210            current = node.child();
211        }
212    }
213
214    /// Visits descendant nodes that match `mask`, short-circuiting when possible.
215    pub fn visit_descendants_matching<F>(self, include_self: bool, mask: NodeCapabilities, mut f: F)
216    where
217        F: FnMut(Self),
218    {
219        if mask.is_empty() {
220            self.visit_descendants(include_self, f);
221            return;
222        }
223
224        if !self.aggregate_child_capabilities().intersects(mask) {
225            return;
226        }
227
228        self.visit_descendants(include_self, |node| {
229            if node.kind_set().intersects(mask) {
230                f(node);
231            }
232        });
233    }
234
235    /// Visits ancestor nodes up to (but excluding) the sentinel head.
236    pub fn visit_ancestors<F>(self, include_self: bool, mut f: F)
237    where
238        F: FnMut(Self),
239    {
240        let mut current = if include_self {
241            Some(self)
242        } else {
243            self.parent()
244        };
245        while let Some(node) = current {
246            if node.is_head() {
247                break;
248            }
249            f(node.clone());
250            current = node.parent();
251        }
252    }
253
254    /// Visits ancestor nodes that match `mask`.
255    pub fn visit_ancestors_matching<F>(self, include_self: bool, mask: NodeCapabilities, mut f: F)
256    where
257        F: FnMut(Self),
258    {
259        if mask.is_empty() {
260            self.visit_ancestors(include_self, f);
261            return;
262        }
263
264        self.visit_ancestors(include_self, |node| {
265            if node.kind_set().intersects(mask) {
266                f(node);
267            }
268        });
269    }
270}