azul-core 0.0.9

Common datatypes used for the Azul document object model, shared across all azul-* crates
Documentation
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! Node tree data structures and hierarchy management.
//!
//! This module provides the core data structures for managing DOM-like tree hierarchies:
//!
//! - `NodeId`: Type-safe node identifiers with Option<NodeId> optimization
//! - `NodeHierarchy`: Parent-child relationships between nodes
//! - `NodeDataContainer`: Generic storage for node data with efficient indexing
//!
//! # Memory Layout
//!
//! `NodeId` stores a plain `usize` index internally. For FFI structs that need
//! `Option<NodeId>`, a manual 1-based encoding is used (0 = None, n > 0 = Some(n-1)).
//!
//! # Performance
//!
//! - Node lookups are O(1) via direct array indexing
//! - Parent/child traversal is O(1) via pre-computed indices
//! - No heap allocations after initial tree construction

use alloc::vec::Vec;
use core::{
    ops::{Index, IndexMut},
    slice::Iter,
};

pub use self::node_id::NodeId;
use crate::styled_dom::NodeHierarchyItem;

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

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

    use alloc::vec::Vec;
    use core::{
        fmt,
        ops::{Add, AddAssign},
    };

    /// A type-safe identifier for a node within a DOM tree.
    ///
    /// `NodeId` is FFI-safe (`#[repr(C)]`) and stores a **zero-based** index internally.
    /// Use `NodeId::index()` to get the array index for direct node access.
    ///
    /// # Zero-based indexing
    ///
    /// - `NodeId::new(0)` → first node (index 0)
    /// - `NodeId::new(5)` → sixth node (index 5)
    /// - Use `node_id.index()` to get the array index
    ///
    /// # FFI Encoding (for `Option<NodeId>`)
    ///
    /// When storing `Option<NodeId>` in FFI structs (like `NodeHierarchyItem`),
    /// we use a **1-based encoding** to represent None:
    ///
    /// - `0` means `None` (no node)
    /// - `n > 0` means `Some(NodeId(n - 1))`
    ///
    /// Use [`NodeId::from_usize`] to decode and [`NodeId::into_raw`] to encode.
    /// See also: [`crate::styled_dom::NodeHierarchyItemId`] for the FFI wrapper type.
    ///
    /// # Warning
    ///
    /// **Never manually construct raw usize values for node hierarchy fields!**
    /// Always use the provided `from_usize`/`into_raw` functions to avoid
    /// off-by-one errors that can cause index-out-of-bounds panics.
    ///
    #[repr(C)]
    #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct NodeId {
        // Private field to prevent direct manipulation.
        // Use NodeId::new() to create, NodeId::index() to read.
        inner: usize,
    }

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

        /// Creates a new `NodeId` from a zero-based index.
        #[inline]
        #[must_use] pub const fn new(value: usize) -> Self {
            Self { inner: value }
        }

        /// Decodes a raw `usize` to `Option<NodeId>` using 1-based encoding.
        ///
        /// This is the inverse of [`NodeId::into_usize`].
        ///
        /// - `0` → `None` (no node)
        /// - `n > 0` → `Some(NodeId(n - 1))`
        ///
        /// # Warning
        ///
        /// This function is for decoding values stored in FFI structs like
        /// `NodeHierarchyItem`. Do not use raw usize values directly - always
        /// decode them first!
        #[inline]
        #[must_use] pub const fn from_usize(value: usize) -> Option<Self> {
            match value {
                0 => None,
                i => Some(Self { inner: i - 1 }),
            }
        }

        /// Encodes `Option<NodeId>` to a raw `usize` for storage in FFI structs.
        ///
        /// - `None` → `0`
        /// - `Some(NodeId(n))` → `n + 1`
        ///
        /// The returned value uses **1-based encoding**! A value of `0` means "no node",
        /// NOT "node at index 0". Use [`NodeId::from_usize`] to decode.
        ///
        #[inline]
        #[must_use] pub const fn into_raw(val: &Option<Self>) -> usize {
            match val {
                None => 0,
                Some(s) => s.inner + 1,
            }
        }

        /// Returns the **zero-based** index of this node.
        ///
        /// This is the actual array index where the node data is stored.
        #[inline]
        #[must_use] pub const fn index(&self) -> usize {
            self.inner
        }
    }

    impl From<usize> for NodeId {
        fn from(val: usize) -> Self {
            Self::new(val)
        }
    }

    impl From<NodeId> for usize {
        fn from(val: NodeId) -> Self {
            val.inner
        }
    }

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

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

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

    impl fmt::Debug for NodeId {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "NodeId({})", self.inner)
        }
    }
}

/// Hierarchical information about a node (stores the indices of the parent / child nodes).
#[derive(Debug, Default, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Node {
    pub parent: Option<NodeId>,
    pub previous_sibling: Option<NodeId>,
    pub next_sibling: Option<NodeId>,
    pub last_child: Option<NodeId>,
    // NOTE: first_child can be calculated on the fly:
    //
    //   - if last_child is None, first_child is None
    //   - if last_child is Some, first_child is parent_index + 1
    //
    // This makes the "Node" struct take up 4 registers instead of 5
    //
    // pub first_child: Option<NodeId>,
}

impl Node {
    pub const ROOT: Self = Self {
        parent: None,
        previous_sibling: None,
        next_sibling: None,
        last_child: None,
    };

    #[inline]
    #[must_use] pub const fn has_parent(&self) -> bool {
        self.parent.is_some()
    }
    #[inline]
    #[must_use] pub const fn has_previous_sibling(&self) -> bool {
        self.previous_sibling.is_some()
    }
    #[inline]
    #[must_use] pub const fn has_next_sibling(&self) -> bool {
        self.next_sibling.is_some()
    }
    #[inline]
    #[must_use] pub const fn has_first_child(&self) -> bool {
        self.last_child.is_some() /* last_child and first_child are always set together */
    }
    #[inline]
    #[must_use] pub const fn has_last_child(&self) -> bool {
        self.last_child.is_some()
    }

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

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

impl NodeHierarchy {
    #[inline]
    #[must_use] pub const fn new(data: Vec<Node>) -> Self {
        Self { internal: data }
    }

    #[inline]
    #[must_use] pub fn as_ref(&self) -> NodeHierarchyRef<'_> {
        NodeHierarchyRef {
            internal: &self.internal[..],
        }
    }

}

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

impl<'a> NodeHierarchyRef<'a> {
    #[inline]
    #[must_use] pub const fn from_slice(data: &'a [Node]) -> Self {
        NodeHierarchyRef { internal: data }
    }

    #[inline]
    #[must_use] pub const fn len(&self) -> usize {
        self.internal.len()
    }

    #[inline]
    #[must_use] pub const fn is_empty(&self) -> bool {
        self.internal.is_empty()
    }

    #[inline]
    #[must_use] pub fn get(&self, id: NodeId) -> Option<&Node> {
        self.internal.get(id.index())
    }

    #[inline]
    #[must_use] pub const fn linear_iter(&self) -> LinearIterator {
        LinearIterator {
            arena_len: self.len(),
            position: 0,
        }
    }

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

        let root = NodeId::new(0);
        let mut non_leaf_nodes = Vec::new();

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

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

        loop {
            for id in &current_children {
                for child_id in id.1.children(self).filter(|id| self[*id].has_first_child()) {
                    next_children.push((depth, child_id));
                }
            }

            non_leaf_nodes.extend(&mut current_children.drain(..));

            if next_children.is_empty() {
                break;
            }
            current_children.extend(&mut next_children.drain(..));
            depth += 1;
        }

        non_leaf_nodes
    }

}

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

impl<T> From<Vec<T>> for NodeDataContainer<T> {
    fn from(v: Vec<T>) -> Self {
        Self { internal: v }
    }
}

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

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

impl<T> Default for NodeDataContainer<T> {
    fn default() -> Self {
        Self {
            internal: Vec::new(),
        }
    }
}

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

    #[inline]
    fn index(&self, node_id: NodeId) -> &Node {
        &self.internal[node_id.index()]
    }
}

impl<T> NodeDataContainer<T> {
    #[inline]
    #[must_use] pub const fn new(data: Vec<T>) -> Self {
        Self { internal: data }
    }

    #[inline]
    #[must_use] pub const fn is_empty(&self) -> bool {
        self.internal.is_empty()
    }

    #[inline]
    #[must_use] pub fn as_ref(&self) -> NodeDataContainerRef<'_, T> {
        NodeDataContainerRef {
            internal: &self.internal[..],
        }
    }

    #[inline]
    pub fn as_ref_mut(&mut self) -> NodeDataContainerRefMut<'_, T> {
        NodeDataContainerRefMut {
            internal: &mut self.internal[..],
        }
    }

    #[inline]
    #[must_use] pub const fn len(&self) -> usize {
        self.internal.len()
    }
}

impl<'a, T: 'a> NodeDataContainerRefMut<'a, T> {
    #[inline]
    pub const fn from_slice(data: &'a mut [T]) -> Self {
        NodeDataContainerRefMut { internal: data }
    }
}

impl<'a, T: 'a> NodeDataContainerRefMut<'a, T> {
    #[inline]
    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut T> {
        self.internal.get_mut(id.index())
    }
}

impl<'a, T: Send + 'a> NodeDataContainerRef<'a, T> {
    pub fn transform_nodeid_optional<U: Send, F>(
        &self,
        closure: F,
    ) -> NodeDataContainer<U>
    where
        F: Send + Sync + Fn(NodeId) -> Option<U>,
    {
        let len = self.len();
        NodeDataContainer {
            internal: (0..len)
                .filter_map(|node_id| closure(NodeId::new(node_id)))
                .collect::<Vec<U>>(),
        }
    }
}

impl<'a, T> IntoIterator for &NodeDataContainerRef<'a, T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.internal.iter()
    }
}

impl<'a, T: 'a> NodeDataContainerRef<'a, T> {
    #[inline]
    pub const fn from_slice(data: &'a [T]) -> Self {
        NodeDataContainerRef { internal: data }
    }

    #[inline]
    #[must_use] pub const fn len(&self) -> usize {
        self.internal.len()
    }

    #[inline]
    #[must_use] pub const fn is_empty(&self) -> bool {
        self.internal.is_empty()
    }

    #[inline]
    #[must_use] pub fn get(&self, id: NodeId) -> Option<&T> {
        self.internal.get(id.index())
    }

    #[inline]
    pub fn iter(&self) -> Iter<'_, T> {
        self.internal.iter()
    }

    #[inline]
    #[must_use] pub const fn linear_iter(&self) -> LinearIterator {
        LinearIterator {
            arena_len: self.len(),
            position: 0,
        }
    }
}

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

    #[inline]
    fn index(&self, node_id: NodeId) -> &T {
        &self.internal[node_id.index()]
    }
}

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

    #[inline]
    fn index(&self, node_id: NodeId) -> &T {
        &self.internal[node_id.index()]
    }
}

impl<T> IndexMut<NodeId> for NodeDataContainerRefMut<'_, T> {
    #[inline]
    fn index_mut(&mut self, node_id: NodeId) -> &mut T {
        &mut self.internal[node_id.index()]
    }
}

impl NodeId {
    /// Return an iterator of references to this node and the siblings before it.
    ///
    /// Call `.next().unwrap()` once on the iterator to skip the node itself.
    #[inline]
    #[must_use] pub const fn preceding_siblings<'a>(
        self,
        node_hierarchy: &'a NodeHierarchyRef<'a>,
    ) -> PrecedingSiblings<'a> {
        PrecedingSiblings {
            node_hierarchy,
            node: Some(self),
        }
    }

    /// Return an iterator of references to this node's children.
    #[inline]
    #[must_use] pub fn children<'a>(self, node_hierarchy: &'a NodeHierarchyRef<'a>) -> Children<'a> {
        Children {
            node_hierarchy,
            node: node_hierarchy[self].get_first_child(self),
        }
    }
}

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

            fn next(&mut self) -> Option<NodeId> {
                match self.node.take() {
                    Some(node) => {
                        self.node = $next(&self.node_hierarchy[node]);
                        Some(node)
                    }
                    None => None,
                }
            }
        }
    };
}

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

impl Iterator for LinearIterator {
    type Item = NodeId;

    fn next(&mut self) -> Option<NodeId> {
        if self.arena_len < 1 || self.position > (self.arena_len - 1) {
            None
        } else {
            let new_id = Some(NodeId::new(self.position));
            self.position += 1;
            new_id
        }
    }
}

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

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

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

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

    fn next(&mut self) -> Option<NodeId> {
        match self.node.take() {
            Some(node) => {
                self.node = self.node_hierarchy[node].next_sibling_id();
                Some(node)
            }
            None => None,
        }
    }
}

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

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

    fn next(&mut self) -> Option<NodeId> {
        match self.node.take() {
            Some(node) => {
                self.node = self.node_hierarchy[node].previous_sibling_id();
                Some(node)
            }
            None => None,
        }
    }
}

impl NodeId {
    /// Traverse up through the hierarchy until a node matching the predicate is found.
    ///
    /// Necessary to resolve the last positioned (= relative)
    /// element of an absolute node.
    pub fn get_nearest_matching_parent<'a, F>(
        self,
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
        predicate: F,
    ) -> Option<Self>
    where
        F: Fn(Self) -> bool,
    {
        // AUDIT: guard against (a) an out-of-bounds `self` and (b) a cycle in a
        // corrupt hierarchy (a `parent_id` that points back down into a
        // descendant). Use checked `get` and cap the walk at the node count —
        // a valid parent chain can never be longer than the number of nodes.
        let node_count = node_hierarchy.internal.len();
        let mut current_node = node_hierarchy.internal.get(self.index())?.parent_id()?;
        for _ in 0..node_count {
            if predicate(current_node) {
                return Some(current_node);
            }
            current_node = node_hierarchy.internal.get(current_node.index())?.parent_id()?;
        }
        None
    }

    /// Return the children of this node (necessary for parallel iteration over children)
    #[inline]
    #[must_use] pub fn az_children_collect<'a>(
        self,
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
    ) -> Vec<Self> {
        self.az_children(node_hierarchy).collect()
    }

    /// Return an iterator of references to this node's children.
    #[inline]
    #[must_use] pub fn az_children<'a>(
        self,
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
    ) -> AzChildren<'a> {
        AzChildren {
            node_hierarchy,
            node: node_hierarchy[self].first_child_id(self),
        }
    }

    /// Return an iterator of references to this node's children.
    #[inline]
    #[must_use] pub fn az_reverse_children<'a>(
        self,
        node_hierarchy: &'a NodeDataContainerRef<'a, NodeHierarchyItem>,
    ) -> AzReverseChildren<'a> {
        AzReverseChildren {
            node_hierarchy,
            node: node_hierarchy[self].last_child_id(),
        }
    }
}

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

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

#[cfg(test)]
mod audit_tests {
    use super::*;
    use crate::styled_dom::NodeHierarchyItem;

    #[test]
    fn parents_by_depth_empty_hierarchy() {
        let h = NodeHierarchy::new(Vec::new());
        assert!(h.as_ref().get_parents_sorted_by_depth().is_empty());
    }

    #[test]
    fn parents_by_depth_single_childless_root() {
        // A single-node DOM: the root is a LEAF, not a parent.
        let h = NodeHierarchy::new(vec![Node::ROOT]);
        assert!(h.as_ref().get_parents_sorted_by_depth().is_empty());
    }

    #[test]
    fn parents_by_depth_root_with_child() {
        let root = Node {
            parent: None,
            previous_sibling: None,
            next_sibling: None,
            last_child: Some(NodeId::new(1)),
        };
        let child = Node {
            parent: Some(NodeId::new(0)),
            ..Node::ROOT
        };
        let h = NodeHierarchy::new(vec![root, child]);
        let parents = h.as_ref().get_parents_sorted_by_depth();
        assert_eq!(parents, vec![(0, NodeId::new(0))]);
    }

    fn item(parent: Option<usize>) -> NodeHierarchyItem {
        NodeHierarchyItem {
            parent: parent.map_or(0, |p| p + 1),
            previous_sibling: 0,
            next_sibling: 0,
            last_child: 0,
        }
    }

    #[test]
    fn nearest_matching_parent_cycle_terminates() {
        // node1.parent = 2, node2.parent = 1 — cyclic, must not hang.
        let items = vec![item(None), item(Some(2)), item(Some(1))];
        let cont = NodeDataContainerRef { internal: &items };
        let r = NodeId::new(1).get_nearest_matching_parent(&cont, |_| false);
        assert_eq!(r, None);
    }

    #[test]
    fn nearest_matching_parent_finds_match() {
        // 0 <- 1 <- 2 ; from 2, find the root (index 0).
        let items = vec![item(None), item(Some(0)), item(Some(1))];
        let cont = NodeDataContainerRef { internal: &items };
        let r = NodeId::new(2).get_nearest_matching_parent(&cont, |n| n == NodeId::new(0));
        assert_eq!(r, Some(NodeId::new(0)));
    }

    #[test]
    fn node_id_add_saturates() {
        assert_eq!(NodeId::new(5) + 3, NodeId::new(8));
        assert_eq!(NodeId::new(usize::MAX) + 1, NodeId::new(usize::MAX));
        let mut n = NodeId::new(usize::MAX);
        n += 10;
        assert_eq!(n, NodeId::new(usize::MAX));
    }
}

#[cfg(test)]
#[allow(clippy::pedantic, clippy::nursery)]
mod autotest_generated {
    use core::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::styled_dom::NodeHierarchyItem;

    // ---------------------------------------------------------------------
    // helpers
    // ---------------------------------------------------------------------

    /// A well-formed 5-node tree (children are always contiguous after the
    /// parent, as the `first_child = parent + 1` design requires):
    ///
    /// ```text
    /// 0 ── 1 ── 2
    ///  │    └── 3
    ///  └── 4
    /// ```
    fn tree_5() -> Vec<Node> {
        vec![
            Node {
                parent: None,
                previous_sibling: None,
                next_sibling: None,
                last_child: Some(NodeId::new(4)),
            },
            Node {
                parent: Some(NodeId::new(0)),
                previous_sibling: None,
                next_sibling: Some(NodeId::new(4)),
                last_child: Some(NodeId::new(3)),
            },
            Node {
                parent: Some(NodeId::new(1)),
                previous_sibling: None,
                next_sibling: Some(NodeId::new(3)),
                last_child: None,
            },
            Node {
                parent: Some(NodeId::new(1)),
                previous_sibling: Some(NodeId::new(2)),
                next_sibling: None,
                last_child: None,
            },
            Node {
                parent: Some(NodeId::new(0)),
                previous_sibling: Some(NodeId::new(1)),
                next_sibling: None,
                last_child: None,
            },
        ]
    }

    fn items(nodes: &[Node]) -> Vec<NodeHierarchyItem> {
        nodes.iter().copied().map(NodeHierarchyItem::from).collect()
    }

    // ---------------------------------------------------------------------
    // NodeId::new / index / ZERO  (constructor + getter)
    // ---------------------------------------------------------------------

    #[test]
    fn node_id_new_roundtrips_index_at_boundaries() {
        for v in [0_usize, 1, 2, 42, usize::MAX - 1, usize::MAX] {
            assert_eq!(NodeId::new(v).index(), v, "index() must echo new()");
        }
    }

    #[test]
    fn node_id_zero_matches_new_zero() {
        assert_eq!(NodeId::ZERO, NodeId::new(0));
        assert_eq!(NodeId::ZERO.index(), 0);
    }

    #[test]
    fn node_id_usize_conversions_are_lossless() {
        for v in [0_usize, 7, usize::MAX] {
            let id: NodeId = v.into();
            let back: usize = id.into();
            assert_eq!(back, v);
        }
    }

    #[test]
    fn node_id_ordering_follows_index() {
        assert!(NodeId::new(0) < NodeId::new(1));
        assert!(NodeId::new(1) < NodeId::new(usize::MAX));
        assert_eq!(NodeId::new(3), NodeId::new(3));
    }

    // ---------------------------------------------------------------------
    // NodeId::from_usize / into_raw  (1-based FFI encoding round-trip)
    // ---------------------------------------------------------------------

    #[test]
    fn from_usize_zero_is_none_and_shifts_by_one() {
        assert_eq!(NodeId::from_usize(0), None);
        assert_eq!(NodeId::from_usize(1), Some(NodeId::new(0)));
        assert_eq!(NodeId::from_usize(2), Some(NodeId::new(1)));
        // usize::MAX must NOT overflow the `i - 1` decode.
        assert_eq!(
            NodeId::from_usize(usize::MAX),
            Some(NodeId::new(usize::MAX - 1))
        );
    }

    #[test]
    fn into_raw_encodes_none_as_zero() {
        assert_eq!(NodeId::into_raw(&None), 0);
        assert_eq!(NodeId::into_raw(&Some(NodeId::new(0))), 1);
        assert_eq!(NodeId::into_raw(&Some(NodeId::new(41))), 42);
        // Largest index that survives the +1 encode without overflowing.
        assert_eq!(NodeId::into_raw(&Some(NodeId::new(usize::MAX - 1))), usize::MAX);
    }

    #[test]
    fn encode_decode_roundtrip_is_identity() {
        // decode(encode(x)) == x
        for x in [
            None,
            Some(NodeId::new(0)),
            Some(NodeId::new(1)),
            Some(NodeId::new(9_999)),
            Some(NodeId::new(usize::MAX - 1)),
        ] {
            assert_eq!(NodeId::from_usize(NodeId::into_raw(&x)), x, "decode(encode({x:?}))");
        }
        // encode(decode(n)) == n
        for n in [0_usize, 1, 2, 12_345, usize::MAX] {
            assert_eq!(NodeId::into_raw(&NodeId::from_usize(n)), n, "encode(decode({n}))");
        }
    }

    /// BOUNDARY: `NodeId::new(usize::MAX)` is the one index that cannot be
    /// encoded — `into_raw` computes `inner + 1`, which overflows. Unlike the
    /// `Add`/`AddAssign` impls (which were deliberately made saturating), this
    /// add is unchecked: debug builds panic, release builds wrap to `0`, i.e.
    /// the `None` encoding. Either way the node is lost; assert that it never
    /// silently produces some *other* valid-looking node id.
    #[cfg(feature = "std")]
    #[test]
    fn into_raw_at_usize_max_never_yields_a_bogus_node() {
        let encoded = std::panic::catch_unwind(|| NodeId::into_raw(&Some(NodeId::new(usize::MAX))));
        match encoded {
            // debug: overflow check fires — loud failure, acceptable.
            Err(_) => {}
            // release: wraps to 0 == the "no node" encoding.
            Ok(raw) => {
                assert_eq!(raw, 0, "wrapped encode must not alias a real node id");
                assert_eq!(NodeId::from_usize(raw), None);
            }
        }
    }

    // ---------------------------------------------------------------------
    // NodeId Display / Debug  (serializer)
    // ---------------------------------------------------------------------

    #[test]
    fn node_id_display_and_debug_are_well_formed() {
        assert_eq!(alloc::format!("{}", NodeId::new(0)), "0");
        assert_eq!(alloc::format!("{}", NodeId::new(7)), "7");
        assert_eq!(alloc::format!("{:?}", NodeId::new(7)), "NodeId(7)");
        // Extreme values must render without panicking and stay non-empty.
        let max = alloc::format!("{}", NodeId::new(usize::MAX));
        assert_eq!(max, alloc::format!("{}", usize::MAX));
        assert!(!max.is_empty());
        assert_eq!(
            alloc::format!("{:?}", NodeId::new(usize::MAX)),
            alloc::format!("NodeId({})", usize::MAX)
        );
    }

    // ---------------------------------------------------------------------
    // Node predicates + get_first_child
    // ---------------------------------------------------------------------

    #[test]
    fn node_root_and_default_have_no_relations() {
        for n in [Node::ROOT, Node::default()] {
            assert!(!n.has_parent());
            assert!(!n.has_previous_sibling());
            assert!(!n.has_next_sibling());
            assert!(!n.has_first_child());
            assert!(!n.has_last_child());
            assert_eq!(n.get_first_child(NodeId::new(0)), None);
        }
        assert_eq!(Node::default(), Node::ROOT);
    }

    #[test]
    fn node_predicates_report_each_populated_field() {
        let full = Node {
            parent: Some(NodeId::new(1)),
            previous_sibling: Some(NodeId::new(2)),
            next_sibling: Some(NodeId::new(3)),
            last_child: Some(NodeId::new(4)),
        };
        assert!(full.has_parent());
        assert!(full.has_previous_sibling());
        assert!(full.has_next_sibling());
        assert!(full.has_first_child());
        assert!(full.has_last_child());
    }

    /// INVARIANT: `has_first_child()` and `has_last_child()` read the same
    /// field, so they can never disagree — child-presence is all-or-nothing.
    #[test]
    fn has_first_child_always_agrees_with_has_last_child() {
        for last_child in [None, Some(NodeId::new(0)), Some(NodeId::new(usize::MAX))] {
            let n = Node {
                last_child,
                ..Node::ROOT
            };
            assert_eq!(n.has_first_child(), n.has_last_child());
            assert_eq!(n.has_first_child(), last_child.is_some());
        }
    }

    #[test]
    fn get_first_child_is_self_plus_one_and_saturates() {
        let parent = Node {
            last_child: Some(NodeId::new(9)),
            ..Node::ROOT
        };
        assert_eq!(parent.get_first_child(NodeId::new(0)), Some(NodeId::new(1)));
        assert_eq!(parent.get_first_child(NodeId::new(5)), Some(NodeId::new(6)));
        // Extreme id: the `+ 1` is saturating, so this must not panic/wrap. It
        // yields an obviously-invalid id that fails loudly at the next lookup.
        assert_eq!(
            parent.get_first_child(NodeId::new(usize::MAX)),
            Some(NodeId::new(usize::MAX))
        );
        // A leaf has no first child regardless of how extreme the id is.
        assert_eq!(Node::ROOT.get_first_child(NodeId::new(usize::MAX)), None);
    }

    // ---------------------------------------------------------------------
    // NodeHierarchy / NodeHierarchyRef
    // ---------------------------------------------------------------------

    #[test]
    fn hierarchy_new_preserves_len_and_contents() {
        let h = NodeHierarchy::new(tree_5());
        assert_eq!(h.as_ref().len(), 5);
        assert!(!h.as_ref().is_empty());
        assert_eq!(h.as_ref().get(NodeId::new(0)), Some(&tree_5()[0]));
        assert_eq!(h.as_ref().internal, &tree_5()[..]);
    }

    #[test]
    fn empty_hierarchy_is_empty_everywhere() {
        let h = NodeHierarchy::new(Vec::new());
        let r = h.as_ref();
        assert_eq!(r.len(), 0);
        assert!(r.is_empty());
        assert_eq!(r.get(NodeId::new(0)), None);
        assert_eq!(r.linear_iter().count(), 0);
        assert!(r.get_parents_sorted_by_depth().is_empty());

        let default = NodeHierarchy::default();
        assert!(default.as_ref().is_empty());
    }

    #[test]
    fn hierarchy_ref_from_slice_matches_len_and_emptiness() {
        let empty: [Node; 0] = [];
        assert_eq!(NodeHierarchyRef::from_slice(&empty).len(), 0);
        assert!(NodeHierarchyRef::from_slice(&empty).is_empty());

        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        assert_eq!(r.len(), 5);
        assert!(!r.is_empty());
    }

    /// `get()` is the bounds-checked accessor: an out-of-range id must return
    /// `None`, never panic and never read out of bounds.
    #[test]
    fn hierarchy_ref_get_out_of_bounds_returns_none() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        assert!(r.get(NodeId::new(4)).is_some());
        assert_eq!(r.get(NodeId::new(5)), None);
        assert_eq!(r.get(NodeId::new(usize::MAX)), None);
    }

    /// `Index` (unlike `get`) is unchecked-by-contract: it must fail loudly
    /// rather than silently hand back an unrelated node.
    #[test]
    #[should_panic]
    fn hierarchy_ref_index_out_of_bounds_panics() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        let _ = &r[NodeId::new(5)];
    }

    #[test]
    fn hierarchy_linear_iter_walks_every_index_in_order() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        let ids: Vec<NodeId> = r.linear_iter().collect();
        assert_eq!(
            ids,
            (0..5).map(NodeId::new).collect::<Vec<_>>(),
            "linear_iter must yield 0..len exactly once, in order"
        );
    }

    /// The `arena_len < 1` guard exists because `arena_len - 1` would underflow
    /// on an empty arena; check the 0- and 1-element boundaries explicitly.
    #[test]
    fn linear_iter_len_zero_and_one_boundaries() {
        let empty: [Node; 0] = [];
        assert_eq!(
            NodeHierarchyRef::from_slice(&empty).linear_iter().next(),
            None
        );

        let one = [Node::ROOT];
        let mut it = NodeHierarchyRef::from_slice(&one).linear_iter();
        assert_eq!(it.next(), Some(NodeId::new(0)));
        assert_eq!(it.next(), None);
        // Exhausted iterators stay exhausted.
        assert_eq!(it.next(), None);
    }

    #[test]
    fn get_parents_sorted_by_depth_is_depth_ordered_and_leaf_free() {
        let h = NodeHierarchy::new(tree_5());
        let parents = h.as_ref().get_parents_sorted_by_depth();
        // Only 0 and 1 have children; 2/3/4 are leaves and must not appear.
        assert_eq!(parents, vec![(0, NodeId::new(0)), (1, NodeId::new(1))]);
        // Depths must be non-decreasing.
        assert!(parents.windows(2).all(|w| w[0].0 <= w[1].0));
    }

    // ---------------------------------------------------------------------
    // NodeId::children / preceding_siblings  (NodeHierarchyRef iterators)
    // ---------------------------------------------------------------------

    #[test]
    fn children_yields_direct_children_only() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        assert_eq!(
            NodeId::new(0).children(&r).collect::<Vec<_>>(),
            vec![NodeId::new(1), NodeId::new(4)]
        );
        assert_eq!(
            NodeId::new(1).children(&r).collect::<Vec<_>>(),
            vec![NodeId::new(2), NodeId::new(3)]
        );
        // Leaves have no children.
        assert_eq!(NodeId::new(2).children(&r).count(), 0);
        assert_eq!(NodeId::new(4).children(&r).count(), 0);
    }

    #[test]
    #[should_panic]
    fn children_of_out_of_bounds_node_panics_loudly() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        // `children()` indexes the hierarchy directly — an id past the end must
        // abort rather than fabricate a child list.
        let _ = NodeId::new(99).children(&r);
    }

    #[test]
    fn preceding_siblings_starts_with_self_then_walks_backwards() {
        let nodes = tree_5();
        let r = NodeHierarchyRef::from_slice(&nodes);
        assert_eq!(
            NodeId::new(3).preceding_siblings(&r).collect::<Vec<_>>(),
            vec![NodeId::new(3), NodeId::new(2)],
            "the iterator includes the node itself first"
        );
        // A first-born has only itself.
        assert_eq!(
            NodeId::new(2).preceding_siblings(&r).collect::<Vec<_>>(),
            vec![NodeId::new(2)]
        );
    }

    /// ADVERSARIAL: a corrupt hierarchy whose `previous_sibling` points at the
    /// node itself makes the iterator cycle forever. It must not panic — but a
    /// caller that `collect()`s it would hang, so only ever take a bounded
    /// prefix from an untrusted hierarchy.
    #[test]
    fn preceding_siblings_on_self_cycle_repeats_without_panicking() {
        let nodes = vec![
            Node::ROOT,
            Node {
                parent: Some(NodeId::new(0)),
                previous_sibling: Some(NodeId::new(1)), // points at itself
                next_sibling: None,
                last_child: None,
            },
        ];
        let r = NodeHierarchyRef::from_slice(&nodes);
        let first_4: Vec<NodeId> = NodeId::new(1).preceding_siblings(&r).take(4).collect();
        assert_eq!(first_4, vec![NodeId::new(1); 4]);
    }

    // ---------------------------------------------------------------------
    // NodeDataContainer / Ref / RefMut
    // ---------------------------------------------------------------------

    #[test]
    fn data_container_new_and_len_track_the_vec() {
        let c = NodeDataContainer::new(vec![10_u32, 20, 30]);
        assert_eq!(c.len(), 3);
        assert!(!c.is_empty());
        assert_eq!(c.as_ref().len(), 3);
        assert_eq!(c.as_ref().get(NodeId::new(2)), Some(&30));

        let empty: NodeDataContainer<u32> = NodeDataContainer::new(Vec::new());
        assert_eq!(empty.len(), 0);
        assert!(empty.is_empty());
        assert!(empty.as_ref().is_empty());
        assert_eq!(empty.as_ref().get(NodeId::new(0)), None);

        // Default and From<Vec<T>> agree with the explicit constructor.
        assert!(NodeDataContainer::<u32>::default().is_empty());
        assert_eq!(NodeDataContainer::from(vec![1_u32, 2]).len(), 2);
    }

    #[test]
    fn data_container_ref_get_out_of_bounds_returns_none() {
        let data = [1_u8, 2, 3];
        let r = NodeDataContainerRef::from_slice(&data);
        assert_eq!(r.get(NodeId::new(0)), Some(&1));
        assert_eq!(r.get(NodeId::new(3)), None);
        assert_eq!(r.get(NodeId::new(usize::MAX)), None);
    }

    #[test]
    #[should_panic]
    fn data_container_ref_index_out_of_bounds_panics() {
        let data = [1_u8, 2, 3];
        let r = NodeDataContainerRef::from_slice(&data);
        let _ = &r[NodeId::new(3)];
    }

    #[test]
    fn data_container_ref_iterators_cover_all_elements() {
        let data = [1_u8, 2, 3];
        let r = NodeDataContainerRef::from_slice(&data);
        assert_eq!(r.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
        assert_eq!((&r).into_iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);
        assert_eq!(r.linear_iter().count(), 3);

        let empty: [u8; 0] = [];
        let e = NodeDataContainerRef::from_slice(&empty);
        assert_eq!(e.len(), 0);
        assert!(e.is_empty());
        assert_eq!(e.iter().count(), 0);
        assert_eq!(e.linear_iter().next(), None);
    }

    #[test]
    fn data_container_ref_mut_get_mut_is_bounds_checked() {
        let mut c = NodeDataContainer::new(vec![1_u32, 2, 3]);
        let mut m = c.as_ref_mut();
        assert_eq!(m.get_mut(NodeId::new(3)), None);
        assert_eq!(m.get_mut(NodeId::new(usize::MAX)), None);
        *m.get_mut(NodeId::new(1)).unwrap() = 99;
        m[NodeId::new(2)] = 7;
        assert_eq!(m[NodeId::new(2)], 7);
        assert_eq!(c.internal, vec![1, 99, 7]);
    }

    #[test]
    fn data_container_ref_mut_from_slice_on_empty_slice() {
        let mut empty: [u32; 0] = [];
        let mut m = NodeDataContainerRefMut::from_slice(&mut empty);
        assert_eq!(m.get_mut(NodeId::new(0)), None);
        assert!(m.internal.is_empty());
    }

    #[test]
    #[should_panic]
    fn data_container_ref_mut_index_out_of_bounds_panics() {
        let mut data = [1_u8, 2];
        let m = NodeDataContainerRefMut::from_slice(&mut data);
        let _ = &m[NodeId::new(2)];
    }

    // ---------------------------------------------------------------------
    // transform_nodeid_optional
    // ---------------------------------------------------------------------

    #[test]
    fn transform_nodeid_optional_maps_every_index() {
        let data = [0_u32; 4];
        let r = NodeDataContainerRef::from_slice(&data);
        let out = r.transform_nodeid_optional(|id| Some(id.index() as u32 * 10));
        assert_eq!(out.internal, vec![0, 10, 20, 30]);
        assert_eq!(out.len(), r.len());
    }

    #[test]
    fn transform_nodeid_optional_empty_input_never_calls_the_closure() {
        let empty: [u32; 0] = [];
        let r = NodeDataContainerRef::from_slice(&empty);
        let calls = AtomicUsize::new(0);
        let out = r.transform_nodeid_optional(|_| {
            calls.fetch_add(1, Ordering::SeqCst);
            Some(1_u32)
        });
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        assert!(out.is_empty());
    }

    /// CONTRACT TRAP: `None` results are *filtered out*, so the output is
    /// COMPACTED — it is shorter than the input and its positions no longer
    /// line up with the `NodeId`s that produced them. Indexing the result by a
    /// `NodeId` therefore reads the wrong element (or goes out of bounds).
    /// Pinned here so the aliasing behaviour can't change silently.
    #[test]
    fn transform_nodeid_optional_compacts_and_breaks_nodeid_alignment() {
        let data = [0_u32; 5];
        let r = NodeDataContainerRef::from_slice(&data);
        // Keep only even node ids: 0, 2, 4.
        let out = r.transform_nodeid_optional(|id| {
            if id.index() % 2 == 0 {
                Some(id.index() as u32)
            } else {
                None
            }
        });
        assert_eq!(out.len(), 3, "output is compacted, NOT padded to the input len");
        assert_eq!(out.internal, vec![0, 2, 4]);
        // Position 1 holds node 2's value — the result is not index-aligned.
        assert_eq!(out.as_ref().get(NodeId::new(1)), Some(&2));
        assert_eq!(out.as_ref().get(NodeId::new(4)), None);

        // All-None closure yields an empty container rather than panicking.
        let none_out = r.transform_nodeid_optional(|_| -> Option<u32> { None });
        assert!(none_out.is_empty());
    }

    // ---------------------------------------------------------------------
    // NodeId::az_children / az_reverse_children / az_children_collect
    // ---------------------------------------------------------------------

    #[test]
    fn az_children_walks_forwards_and_reverse_walks_backwards() {
        let nodes = tree_5();
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);

        assert_eq!(
            NodeId::new(0).az_children_collect(&h),
            vec![NodeId::new(1), NodeId::new(4)]
        );
        assert_eq!(
            NodeId::new(1).az_children(&h).collect::<Vec<_>>(),
            vec![NodeId::new(2), NodeId::new(3)]
        );
        assert_eq!(
            NodeId::new(1).az_reverse_children(&h).collect::<Vec<_>>(),
            vec![NodeId::new(3), NodeId::new(2)],
            "reverse iteration starts at last_child and walks previous_sibling"
        );
        // Leaves yield nothing in either direction.
        assert_eq!(NodeId::new(2).az_children(&h).count(), 0);
        assert_eq!(NodeId::new(2).az_reverse_children(&h).count(), 0);
        assert!(NodeId::new(3).az_children_collect(&h).is_empty());
    }

    #[test]
    #[should_panic]
    fn az_children_of_out_of_bounds_node_panics_loudly() {
        let nodes = tree_5();
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);
        let _ = NodeId::new(5).az_children(&h);
    }

    /// ADVERSARIAL: a `next_sibling` that points back at the node itself makes
    /// `az_children` an infinite iterator. It must not panic, but
    /// `az_children_collect` on such a hierarchy would allocate until OOM —
    /// so only a bounded prefix is taken here.
    #[test]
    fn az_children_on_sibling_cycle_repeats_without_panicking() {
        let nodes = vec![
            Node {
                last_child: Some(NodeId::new(1)),
                ..Node::ROOT
            },
            Node {
                parent: Some(NodeId::new(0)),
                previous_sibling: None,
                next_sibling: Some(NodeId::new(1)), // points at itself
                last_child: None,
            },
        ];
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);
        let prefix: Vec<NodeId> = NodeId::new(0).az_children(&h).take(5).collect();
        assert_eq!(prefix, vec![NodeId::new(1); 5]);
    }

    // ---------------------------------------------------------------------
    // NodeId::get_nearest_matching_parent
    // ---------------------------------------------------------------------

    #[test]
    fn nearest_matching_parent_skips_non_matching_ancestors() {
        let nodes = tree_5();
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);
        // From node 2, the first ancestor is 1, then the root 0.
        assert_eq!(
            NodeId::new(2).get_nearest_matching_parent(&h, |_| true),
            Some(NodeId::new(1))
        );
        assert_eq!(
            NodeId::new(2).get_nearest_matching_parent(&h, |n| n == NodeId::new(0)),
            Some(NodeId::new(0))
        );
        // The root has no parent at all.
        assert_eq!(
            NodeId::new(0).get_nearest_matching_parent(&h, |_| true),
            None
        );
        // Nothing matches -> None, and the walk terminates.
        assert_eq!(
            NodeId::new(3).get_nearest_matching_parent(&h, |_| false),
            None
        );
    }

    #[test]
    fn nearest_matching_parent_out_of_bounds_self_returns_none() {
        let nodes = tree_5();
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);
        assert_eq!(
            NodeId::new(5).get_nearest_matching_parent(&h, |_| true),
            None
        );
        assert_eq!(
            NodeId::new(usize::MAX).get_nearest_matching_parent(&h, |_| true),
            None
        );
    }

    #[test]
    fn nearest_matching_parent_self_parent_cycle_terminates() {
        // node 1 is its own parent — the node-count cap must break the loop.
        let nodes = vec![
            Node::ROOT,
            Node {
                parent: Some(NodeId::new(1)),
                ..Node::ROOT
            },
        ];
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);
        assert_eq!(
            NodeId::new(1).get_nearest_matching_parent(&h, |_| false),
            None
        );
    }

    /// ADVERSARIAL: a corrupt `parent` index that points past the end of the
    /// arena. The lookup must not panic. Note the predicate is still called
    /// with that out-of-bounds id, so a permissive predicate hands the caller
    /// back an id that will panic when used to index the arena — callers must
    /// bounds-check the returned id, not assume it is valid.
    #[test]
    fn nearest_matching_parent_out_of_bounds_ancestor_does_not_panic() {
        let nodes = vec![
            Node::ROOT,
            Node {
                parent: Some(NodeId::new(99)), // dangling
                ..Node::ROOT
            },
        ];
        let it = items(&nodes);
        let h = NodeDataContainerRef::from_slice(&it);

        // Rejecting predicate: the dangling id fails the `get()` and yields None.
        assert_eq!(
            NodeId::new(1).get_nearest_matching_parent(&h, |_| false),
            None
        );
        // Accepting predicate: the dangling id is returned as-is.
        assert_eq!(
            NodeId::new(1).get_nearest_matching_parent(&h, |_| true),
            Some(NodeId::new(99))
        );
        assert!(h.get(NodeId::new(99)).is_none(), "and it is NOT a valid index");
    }
}