1
//! Node tree data structures and hierarchy management.
2
//!
3
//! This module provides the core data structures for managing DOM-like tree hierarchies:
4
//!
5
//! - `NodeId`: Type-safe node identifiers with Option<NodeId> optimization
6
//! - `NodeHierarchy`: Parent-child relationships between nodes
7
//! - `NodeDataContainer`: Generic storage for node data with efficient indexing
8
//!
9
//! # Memory Layout
10
//!
11
//! `NodeId` stores a plain `usize` index internally. For FFI structs that need
12
//! `Option<NodeId>`, a manual 1-based encoding is used (0 = None, n > 0 = Some(n-1)).
13
//!
14
//! # Performance
15
//!
16
//! - Node lookups are O(1) via direct array indexing
17
//! - Parent/child traversal is O(1) via pre-computed indices
18
//! - No heap allocations after initial tree construction
19

            
20
use alloc::vec::Vec;
21
use core::{
22
    ops::{Index, IndexMut},
23
    slice::Iter,
24
};
25

            
26
pub use self::node_id::NodeId;
27
use crate::styled_dom::NodeHierarchyItem;
28

            
29
/// Type alias for depth-first traversal results: (depth, `node_id`) pairs
30
pub type NodeDepths = Vec<(usize, NodeId)>;
31

            
32
// Simple FFI-safe NodeId - just a wrapper around usize
33
pub mod node_id {
34

            
35
    use alloc::vec::Vec;
36
    use core::{
37
        fmt,
38
        ops::{Add, AddAssign},
39
    };
40

            
41
    /// A type-safe identifier for a node within a DOM tree.
42
    ///
43
    /// `NodeId` is FFI-safe (`#[repr(C)]`) and stores a **zero-based** index internally.
44
    /// Use `NodeId::index()` to get the array index for direct node access.
45
    ///
46
    /// # Zero-based indexing
47
    ///
48
    /// - `NodeId::new(0)` → first node (index 0)
49
    /// - `NodeId::new(5)` → sixth node (index 5)
50
    /// - Use `node_id.index()` to get the array index
51
    ///
52
    /// # FFI Encoding (for `Option<NodeId>`)
53
    ///
54
    /// When storing `Option<NodeId>` in FFI structs (like `NodeHierarchyItem`),
55
    /// we use a **1-based encoding** to represent None:
56
    ///
57
    /// - `0` means `None` (no node)
58
    /// - `n > 0` means `Some(NodeId(n - 1))`
59
    ///
60
    /// Use [`NodeId::from_usize`] to decode and [`NodeId::into_raw`] to encode.
61
    /// See also: [`crate::styled_dom::NodeHierarchyItemId`] for the FFI wrapper type.
62
    ///
63
    /// # Warning
64
    ///
65
    /// **Never manually construct raw usize values for node hierarchy fields!**
66
    /// Always use the provided `from_usize`/`into_raw` functions to avoid
67
    /// off-by-one errors that can cause index-out-of-bounds panics.
68
    #[repr(C)]
69
    #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
70
    pub struct NodeId {
71
        // Private field to prevent direct manipulation.
72
        // Use NodeId::new() to create, NodeId::index() to read.
73
        inner: usize,
74
    }
75

            
76
    impl NodeId {
77
        /// The zero/first node ID (index 0).
78
        pub const ZERO: Self = Self { inner: 0 };
79

            
80
        /// Creates a new `NodeId` from a zero-based index.
81
        #[inline]
82
        #[must_use]
83
32858583
        pub const fn new(value: usize) -> Self {
84
32858583
            Self { inner: value }
85
32858583
        }
86

            
87
        /// Decodes a raw `usize` to `Option<NodeId>` using 1-based encoding.
88
        ///
89
        /// This is the inverse of [`NodeId::into_usize`].
90
        ///
91
        /// - `0` → `None` (no node)
92
        /// - `n > 0` → `Some(NodeId(n - 1))`
93
        ///
94
        /// # Warning
95
        ///
96
        /// This function is for decoding values stored in FFI structs like
97
        /// `NodeHierarchyItem`. Do not use raw usize values directly - always
98
        /// decode them first!
99
        #[inline]
100
        #[must_use]
101
148258171
        pub const fn from_usize(value: usize) -> Option<Self> {
102
148258171
            match value {
103
10115178
                0 => None,
104
138142993
                i => Some(Self { inner: i - 1 }),
105
            }
106
148258171
        }
107

            
108
        /// Encodes `Option<NodeId>` to a raw `usize` for storage in FFI structs.
109
        ///
110
        /// - `None` → `0`
111
        /// - `Some(NodeId(n))` → `n + 1`
112
        ///
113
        /// The returned value uses **1-based encoding**! A value of `0` means "no node",
114
        /// NOT "node at index 0". Use [`NodeId::from_usize`] to decode.
115
        #[inline]
116
        #[must_use]
117
5372552
        pub const fn into_raw(val: &Option<Self>) -> usize {
118
5372552
            match val {
119
1292153
                None => 0,
120
4080399
                Some(s) => s.inner + 1,
121
            }
122
5372552
        }
123

            
124
        /// Returns the **zero-based** index of this node.
125
        ///
126
        /// This is the actual array index where the node data is stored.
127
        #[inline]
128
        #[must_use]
129
690179610
        pub const fn index(&self) -> usize {
130
690179610
            self.inner
131
690179610
        }
132
    }
133

            
134
    impl From<usize> for NodeId {
135
3
        fn from(val: usize) -> Self {
136
3
            Self::new(val)
137
3
        }
138
    }
139

            
140
    impl From<NodeId> for usize {
141
3
        fn from(val: NodeId) -> Self {
142
3
            val.inner
143
3
        }
144
    }
145

            
146
    impl Add<usize> for NodeId {
147
        type Output = Self;
148
        /// AUDIT: saturating add. A raw `self.inner + other` could overflow
149
        /// (debug panic / release wrap to a bogus small index that then aliases
150
        /// a real node). `NodeId` indices are bounded by the arena length, so a
151
        /// saturation to `usize::MAX` is an obviously-invalid index that fails
152
        /// loudly at the next bounds-checked access rather than silently aliasing.
153
        #[inline]
154
6761262
        fn add(self, other: usize) -> Self {
155
6761262
            Self::new(self.inner.saturating_add(other))
156
6761262
        }
157
    }
158

            
159
    impl AddAssign<usize> for NodeId {
160
        /// AUDIT: saturating add — see [`Add`] impl above.
161
        #[inline]
162
1
        fn add_assign(&mut self, other: usize) {
163
1
            *self = *self + other;
164
1
        }
165
    }
166

            
167
    impl fmt::Display for NodeId {
168
302
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169
302
            write!(f, "{}", self.inner)
170
302
        }
171
    }
172

            
173
    impl fmt::Debug for NodeId {
174
2795681
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175
2795681
            write!(f, "NodeId({})", self.inner)
176
2795681
        }
177
    }
178
}
179

            
180
/// Hierarchical information about a node (stores the indices of the parent / child nodes).
181
#[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
182
pub struct Node {
183
    pub parent: Option<NodeId>,
184
    pub previous_sibling: Option<NodeId>,
185
    pub next_sibling: Option<NodeId>,
186
    pub last_child: Option<NodeId>,
187
    // NOTE: first_child can be calculated on the fly:
188
    //
189
    //   - if last_child is None, first_child is None
190
    //   - if last_child is Some, first_child is parent_index + 1
191
    //
192
    // This makes the "Node" struct take up 4 registers instead of 5
193
    //
194
    // pub first_child: Option<NodeId>,
195
}
196

            
197
impl Node {
198
    pub const ROOT: Self = Self {
199
        parent: None,
200
        previous_sibling: None,
201
        next_sibling: None,
202
        last_child: None,
203
    };
204

            
205
    #[inline]
206
    #[must_use]
207
3
    pub const fn has_parent(&self) -> bool {
208
3
        self.parent.is_some()
209
3
    }
210
    #[inline]
211
    #[must_use]
212
3
    pub const fn has_previous_sibling(&self) -> bool {
213
3
        self.previous_sibling.is_some()
214
3
    }
215
    #[inline]
216
    #[must_use]
217
3
    pub const fn has_next_sibling(&self) -> bool {
218
3
        self.next_sibling.is_some()
219
3
    }
220
    #[inline]
221
    #[must_use]
222
858155
    pub const fn has_first_child(&self) -> bool {
223
858155
        self.last_child.is_some() /* last_child and first_child are always set together */
224
858155
    }
225
    #[inline]
226
    #[must_use]
227
6
    pub const fn has_last_child(&self) -> bool {
228
6
        self.last_child.is_some()
229
6
    }
230

            
231
    #[inline]
232
    #[must_use]
233
887691
    pub fn get_first_child(&self, current_node_id: NodeId) -> Option<NodeId> {
234
        // last_child and first_child are always set together
235
887691
        self.last_child.map(|_| current_node_id + 1)
236
887691
    }
237
}
238

            
239
/// The hierarchy of nodes is stored separately from the actual node content in order
240
/// to save on memory, since the hierarchy can be re-used across several DOM trees even
241
/// if the content changes.
242
#[derive(Debug, Default, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
243
pub struct NodeHierarchy {
244
    pub internal: Vec<Node>,
245
}
246

            
247
impl NodeHierarchy {
248
    #[inline]
249
    #[must_use]
250
292
    pub const fn new(data: Vec<Node>) -> Self {
251
292
        Self { internal: data }
252
292
    }
253

            
254
    #[inline]
255
    #[must_use]
256
164482
    pub fn as_ref(&self) -> NodeHierarchyRef<'_> {
257
164482
        NodeHierarchyRef {
258
164482
            internal: &self.internal[..],
259
164482
        }
260
164482
    }
261
}
262

            
263
/// The hierarchy of nodes is stored separately from the actual node content in order
264
/// to save on memory, since the hierarchy can be re-used across several DOM trees even
265
/// if the content changes.
266
#[derive(Debug, PartialEq, Hash, Eq)]
267
pub struct NodeHierarchyRef<'a> {
268
    pub internal: &'a [Node],
269
}
270

            
271
impl<'a> NodeHierarchyRef<'a> {
272
    #[inline]
273
    #[must_use]
274
64
    pub const fn from_slice(data: &'a [Node]) -> Self {
275
64
        NodeHierarchyRef { internal: data }
276
64
    }
277

            
278
    #[inline]
279
    #[must_use]
280
84033
    pub const fn len(&self) -> usize {
281
84033
        self.internal.len()
282
84033
    }
283

            
284
    #[inline]
285
    #[must_use]
286
42119
    pub const fn is_empty(&self) -> bool {
287
42119
        self.internal.is_empty()
288
42119
    }
289

            
290
    #[inline]
291
    #[must_use]
292
5219
    pub fn get(&self, id: NodeId) -> Option<&Node> {
293
5219
        self.internal.get(id.index())
294
5219
    }
295

            
296
    #[inline]
297
    #[must_use]
298
89
    pub const fn linear_iter(&self) -> LinearIterator {
299
89
        LinearIterator {
300
89
            arena_len: self.len(),
301
89
            position: 0,
302
89
        }
303
89
    }
304

            
305
    /// Returns the `(depth, NodeId)` of all parent nodes (i.e. nodes that have a
306
    /// `first_child`), in depth sorted order, (i.e. `NodeId(0)` with a depth of 0) is
307
    /// the first element.
308
    ///
309
    /// Runtime: O(n) max
310
    // the `.drain(..)` calls intentionally empty current/next_children to REUSE
311
    // their allocations across the BFS levels; `into_iter()` would move them.
312
    #[allow(clippy::iter_with_drain)]
313
    #[must_use]
314
42111
    pub fn get_parents_sorted_by_depth(&self) -> NodeDepths {
315
        // AUDIT: an empty hierarchy has no root node — indexing `internal[0]`
316
        // (via `self[root]` below) would panic. Bail out early.
317
42111
        if self.is_empty() {
318
74
            return Vec::new();
319
42037
        }
320

            
321
42037
        let root = NodeId::new(0);
322
42037
        let mut non_leaf_nodes = Vec::new();
323

            
324
        // AUDIT: a childless root (e.g. a single-node DOM) is a LEAF, not a
325
        // parent. The old code seeded `current_children` with the root and
326
        // unconditionally pushed it into `non_leaf_nodes`, mislabeling it as a
327
        // parent. Only descend (and only emit the root) when it actually has a
328
        // first child.
329
42037
        if !self[root].has_first_child() {
330
1751
            return non_leaf_nodes;
331
40286
        }
332

            
333
40286
        let mut current_children = vec![(0, root)];
334
40286
        let mut next_children = Vec::new();
335
40286
        let mut depth = 1_usize;
336

            
337
        loop {
338
559060
            for id in &current_children {
339
816109
                for child_id in id.1.children(self).filter(|id| self[*id].has_first_child()) {
340
403556
                    next_children.push((depth, child_id));
341
403556
                }
342
            }
343

            
344
115218
            non_leaf_nodes.extend(&mut current_children.drain(..));
345

            
346
115218
            if next_children.is_empty() {
347
40286
                break;
348
74932
            }
349
74932
            current_children.extend(&mut next_children.drain(..));
350
74932
            depth += 1;
351
        }
352

            
353
40286
        non_leaf_nodes
354
42111
    }
355
}
356

            
357
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
358
pub struct NodeDataContainer<T> {
359
    pub internal: Vec<T>,
360
}
361

            
362
impl<T> From<Vec<T>> for NodeDataContainer<T> {
363
1
    fn from(v: Vec<T>) -> Self {
364
1
        Self { internal: v }
365
1
    }
366
}
367

            
368
#[derive(Debug, PartialEq, Hash, Eq, PartialOrd, Ord)]
369
pub struct NodeDataContainerRef<'a, T> {
370
    pub internal: &'a [T],
371
}
372

            
373
#[derive(Debug, PartialEq, Hash, Eq, PartialOrd, Ord)]
374
pub struct NodeDataContainerRefMut<'a, T> {
375
    pub internal: &'a mut [T],
376
}
377

            
378
impl<T> Default for NodeDataContainer<T> {
379
1
    fn default() -> Self {
380
1
        Self {
381
1
            internal: Vec::new(),
382
1
        }
383
1
    }
384
}
385

            
386
impl Index<NodeId> for NodeHierarchyRef<'_> {
387
    type Output = Node;
388

            
389
    #[inline]
390
12529033
    fn index(&self, node_id: NodeId) -> &Node {
391
12529033
        &self.internal[node_id.index()]
392
12529033
    }
393
}
394

            
395
impl<T> NodeDataContainer<T> {
396
    #[inline]
397
    #[must_use]
398
11
    pub const fn new(data: Vec<T>) -> Self {
399
11
        Self { internal: data }
400
11
    }
401

            
402
    #[inline]
403
    #[must_use]
404
6
    pub const fn is_empty(&self) -> bool {
405
6
        self.internal.is_empty()
406
6
    }
407

            
408
    #[inline]
409
    #[must_use]
410
350638
    pub fn as_ref(&self) -> NodeDataContainerRef<'_, T> {
411
350638
        NodeDataContainerRef {
412
350638
            internal: &self.internal[..],
413
350638
        }
414
350638
    }
415

            
416
    #[inline]
417
1
    pub fn as_ref_mut(&mut self) -> NodeDataContainerRefMut<'_, T> {
418
1
        NodeDataContainerRefMut {
419
1
            internal: &mut self.internal[..],
420
1
        }
421
1
    }
422

            
423
    #[inline]
424
    #[must_use]
425
41742
    pub const fn len(&self) -> usize {
426
41742
        self.internal.len()
427
41742
    }
428
}
429

            
430
impl<'a, T: 'a> NodeDataContainerRefMut<'a, T> {
431
    #[inline]
432
2
    pub const fn from_slice(data: &'a mut [T]) -> Self {
433
2
        NodeDataContainerRefMut { internal: data }
434
2
    }
435
}
436

            
437
impl<'a, T: 'a> NodeDataContainerRefMut<'a, T> {
438
    #[inline]
439
4
    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut T> {
440
4
        self.internal.get_mut(id.index())
441
4
    }
442
}
443

            
444
impl<'a, T: Send + 'a> NodeDataContainerRef<'a, T> {
445
28302
    pub fn transform_nodeid_optional<U: Send, F>(&self, closure: F) -> NodeDataContainer<U>
446
28302
    where
447
28302
        F: Send + Sync + Fn(NodeId) -> Option<U>,
448
    {
449
28302
        let len = self.len();
450
        NodeDataContainer {
451
28302
            internal: (0..len)
452
849127
                .filter_map(|node_id| closure(NodeId::new(node_id)))
453
28302
                .collect::<Vec<U>>(),
454
        }
455
28302
    }
456
}
457

            
458
impl<'a, T> IntoIterator for &NodeDataContainerRef<'a, T> {
459
    type Item = &'a T;
460
    type IntoIter = Iter<'a, T>;
461
    #[inline]
462
1
    fn into_iter(self) -> Self::IntoIter {
463
1
        self.internal.iter()
464
1
    }
465
}
466

            
467
impl<'a, T: 'a> NodeDataContainerRef<'a, T> {
468
    #[inline]
469
125
    pub const fn from_slice(data: &'a [T]) -> Self {
470
125
        NodeDataContainerRef { internal: data }
471
125
    }
472

            
473
    #[inline]
474
    #[must_use]
475
2422617
    pub const fn len(&self) -> usize {
476
2422617
        self.internal.len()
477
2422617
    }
478

            
479
    #[inline]
480
    #[must_use]
481
6
    pub const fn is_empty(&self) -> bool {
482
6
        self.internal.is_empty()
483
6
    }
484

            
485
    #[inline]
486
    #[must_use]
487
41116677
    pub fn get(&self, id: NodeId) -> Option<&T> {
488
41116677
        self.internal.get(id.index())
489
41116677
    }
490

            
491
    #[inline]
492
30
    pub fn iter(&self) -> Iter<'_, T> {
493
30
        self.internal.iter()
494
30
    }
495

            
496
    #[inline]
497
    #[must_use]
498
24001
    pub const fn linear_iter(&self) -> LinearIterator {
499
24001
        LinearIterator {
500
24001
            arena_len: self.len(),
501
24001
            position: 0,
502
24001
        }
503
24001
    }
504
}
505

            
506
impl<T> Index<NodeId> for NodeDataContainerRef<'_, T> {
507
    type Output = T;
508

            
509
    #[inline]
510
339977253
    fn index(&self, node_id: NodeId) -> &T {
511
339977253
        &self.internal[node_id.index()]
512
339977253
    }
513
}
514

            
515
impl<T> Index<NodeId> for NodeDataContainerRefMut<'_, T> {
516
    type Output = T;
517

            
518
    #[inline]
519
163
    fn index(&self, node_id: NodeId) -> &T {
520
163
        &self.internal[node_id.index()]
521
163
    }
522
}
523

            
524
impl<T> IndexMut<NodeId> for NodeDataContainerRefMut<'_, T> {
525
    #[inline]
526
1625
    fn index_mut(&mut self, node_id: NodeId) -> &mut T {
527
1625
        &mut self.internal[node_id.index()]
528
1625
    }
529
}
530

            
531
impl NodeId {
532
    /// Return an iterator of references to this node and the siblings before it.
533
    ///
534
    /// Call `.next().unwrap()` once on the iterator to skip the node itself.
535
    #[inline]
536
    #[must_use]
537
443842
    pub const fn preceding_siblings<'a>(
538
443842
        self,
539
443842
        node_hierarchy: &'a NodeHierarchyRef<'a>,
540
443842
    ) -> PrecedingSiblings<'a> {
541
443842
        PrecedingSiblings {
542
443842
            node_hierarchy,
543
443842
            node: Some(self),
544
443842
        }
545
443842
    }
546

            
547
    /// Return an iterator of references to this node's children.
548
    #[inline]
549
    #[must_use]
550
887686
    pub fn children<'a>(self, node_hierarchy: &'a NodeHierarchyRef<'a>) -> Children<'a> {
551
887686
        Children {
552
887686
            node_hierarchy,
553
887686
            node: node_hierarchy[self].get_first_child(self),
554
887686
        }
555
887686
    }
556
}
557

            
558
macro_rules! impl_node_iterator {
559
    ($name:ident, $next:expr) => {
560
        impl Iterator for $name<'_> {
561
            type Item = NodeId;
562

            
563
11072531
            fn next(&mut self) -> Option<NodeId> {
564
11072531
                match self.node.take() {
565
9741005
                    Some(node) => {
566
9741005
                        self.node = $next(&self.node_hierarchy[node]);
567
9741005
                        Some(node)
568
                    }
569
1331526
                    None => None,
570
                }
571
11072531
            }
572
        }
573
    };
574
}
575

            
576
/// An linear iterator, does not respect the DOM in any way,
577
/// it just iterates over the nodes like a Vec
578
#[derive(Debug, Clone)]
579
pub struct LinearIterator {
580
    arena_len: usize,
581
    position: usize,
582
}
583

            
584
impl Iterator for LinearIterator {
585
    type Item = NodeId;
586

            
587
1073105
    fn next(&mut self) -> Option<NodeId> {
588
1073105
        if self.arena_len < 1 || self.position > (self.arena_len - 1) {
589
30310
            None
590
        } else {
591
1042795
            let new_id = Some(NodeId::new(self.position));
592
1042795
            self.position += 1;
593
1042795
            new_id
594
        }
595
1073105
    }
596
}
597

            
598
/// An iterator of references to the siblings before a given node.
599
#[derive(Debug)]
600
pub struct PrecedingSiblings<'a> {
601
    node_hierarchy: &'a NodeHierarchyRef<'a>,
602
    node: Option<NodeId>,
603
}
604

            
605
impl_node_iterator!(PrecedingSiblings, |node: &Node| node.previous_sibling);
606

            
607
/// Special iterator for using `NodeDataContainerRef`<AzNode> instead of `NodeHierarchy`
608
#[derive(Debug)]
609
pub struct AzChildren<'a> {
610
    node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
611
    node: Option<NodeId>,
612
}
613

            
614
impl Iterator for AzChildren<'_> {
615
    type Item = NodeId;
616

            
617
2322950
    fn next(&mut self) -> Option<NodeId> {
618
2322950
        match self.node.take() {
619
1249523
            Some(node) => {
620
1249523
                self.node = self.node_hierarchy[node].next_sibling_id();
621
1249523
                Some(node)
622
            }
623
1073427
            None => None,
624
        }
625
2322950
    }
626
}
627

            
628
/// Special iterator for using `NodeDataContainerRef`<AzNode> instead of `NodeHierarchy`
629
#[derive(Debug)]
630
pub struct AzReverseChildren<'a> {
631
    node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
632
    node: Option<NodeId>,
633
}
634

            
635
impl Iterator for AzReverseChildren<'_> {
636
    type Item = NodeId;
637

            
638
4
    fn next(&mut self) -> Option<NodeId> {
639
4
        match self.node.take() {
640
2
            Some(node) => {
641
2
                self.node = self.node_hierarchy[node].previous_sibling_id();
642
2
                Some(node)
643
            }
644
2
            None => None,
645
        }
646
4
    }
647
}
648

            
649
impl NodeId {
650
    /// Traverse up through the hierarchy until a node matching the predicate is found.
651
    ///
652
    /// Necessary to resolve the last positioned (= relative)
653
    /// element of an absolute node.
654
33
    pub fn get_nearest_matching_parent<'a, F>(
655
33
        self,
656
33
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
657
33
        predicate: F,
658
33
    ) -> Option<Self>
659
33
    where
660
33
        F: Fn(Self) -> bool,
661
    {
662
        // AUDIT: guard against (a) an out-of-bounds `self` and (b) a cycle in a
663
        // corrupt hierarchy (a `parent_id` that points back down into a
664
        // descendant). Use checked `get` and cap the walk at the node count —
665
        // a valid parent chain can never be longer than the number of nodes.
666
33
        let node_count = node_hierarchy.internal.len();
667
33
        let mut current_node = node_hierarchy.internal.get(self.index())?.parent_id()?;
668
29
        for _ in 0..node_count {
669
43
            if predicate(current_node) {
670
17
                return Some(current_node);
671
26
            }
672
26
            current_node = node_hierarchy
673
26
                .internal
674
26
                .get(current_node.index())?
675
25
                .parent_id()?;
676
        }
677
2
        None
678
33
    }
679

            
680
    /// Return the children of this node (necessary for parallel iteration over children)
681
    #[inline]
682
    #[must_use]
683
2
    pub fn az_children_collect<'a>(
684
2
        self,
685
2
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
686
2
    ) -> Vec<Self> {
687
2
        self.az_children(node_hierarchy).collect()
688
2
    }
689

            
690
    /// Return an iterator of references to this node's children.
691
    #[inline]
692
    #[must_use]
693
1156259
    pub fn az_children<'a>(
694
1156259
        self,
695
1156259
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
696
1156259
    ) -> AzChildren<'a> {
697
1156259
        AzChildren {
698
1156259
            node_hierarchy,
699
1156259
            node: node_hierarchy[self].first_child_id(self),
700
1156259
        }
701
1156259
    }
702

            
703
    /// Return an iterator of references to this node's children.
704
    #[inline]
705
    #[must_use]
706
2
    pub fn az_reverse_children<'a>(
707
2
        self,
708
2
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
709
2
    ) -> AzReverseChildren<'a> {
710
2
        AzReverseChildren {
711
2
            node_hierarchy,
712
2
            node: node_hierarchy[self].last_child_id(),
713
2
        }
714
2
    }
715
}
716

            
717
/// An iterator of references to the children of a given node.
718
#[derive(Debug)]
719
pub struct Children<'a> {
720
    node_hierarchy: &'a NodeHierarchyRef<'a>,
721
    node: Option<NodeId>,
722
}
723

            
724
impl_node_iterator!(Children, |node: &Node| node.next_sibling);
725

            
726
#[cfg(test)]
727
#[path = "id_test.rs"]
728
mod id_test;
729

            
730
// A node reference that may be absent, C-representable (9g-ii-f-i): what a
731
// page break carries as its `causing_node` across the FFI boundary.
732
azul_css::impl_option!(
733
    NodeId,
734
    OptionNodeId,
735
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
736
);