1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod audit_tests {
5
    use super::*;
6
    use crate::styled_dom::NodeHierarchyItem;
7

            
8
    #[test]
9
1
    fn parents_by_depth_empty_hierarchy() {
10
1
        let h = NodeHierarchy::new(Vec::new());
11
1
        assert!(h.as_ref().get_parents_sorted_by_depth().is_empty());
12
1
    }
13

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

            
21
    #[test]
22
1
    fn parents_by_depth_root_with_child() {
23
1
        let root = Node {
24
1
            parent: None,
25
1
            previous_sibling: None,
26
1
            next_sibling: None,
27
1
            last_child: Some(NodeId::new(1)),
28
1
        };
29
1
        let child = Node {
30
1
            parent: Some(NodeId::new(0)),
31
1
            ..Node::ROOT
32
1
        };
33
1
        let h = NodeHierarchy::new(vec![root, child]);
34
1
        let parents = h.as_ref().get_parents_sorted_by_depth();
35
1
        assert_eq!(parents, vec![(0, NodeId::new(0))]);
36
1
    }
37

            
38
6
    fn item(parent: Option<usize>) -> NodeHierarchyItem {
39
        NodeHierarchyItem {
40
6
            parent: parent.map_or(0, |p| p + 1),
41
            previous_sibling: 0,
42
            next_sibling: 0,
43
            last_child: 0,
44
        }
45
6
    }
46

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

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

            
65
    #[test]
66
1
    fn node_id_add_saturates() {
67
1
        assert_eq!(NodeId::new(5) + 3, NodeId::new(8));
68
1
        assert_eq!(NodeId::new(usize::MAX) + 1, NodeId::new(usize::MAX));
69
1
        let mut n = NodeId::new(usize::MAX);
70
1
        n += 10;
71
1
        assert_eq!(n, NodeId::new(usize::MAX));
72
1
    }
73
}
74

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

            
80
    use super::*;
81
    use crate::styled_dom::NodeHierarchyItem;
82

            
83
    // ---------------------------------------------------------------------
84
    // helpers
85
    // ---------------------------------------------------------------------
86

            
87
    /// A well-formed 5-node tree (children are always contiguous after the
88
    /// parent, as the `first_child = parent + 1` design requires):
89
    ///
90
    /// ```text
91
    /// 0 ── 1 ── 2
92
    ///  │    └── 3
93
    ///  └── 4
94
    /// ```
95
    fn tree_5() -> Vec<Node> {
96
        vec![
97
            Node {
98
                parent: None,
99
                previous_sibling: None,
100
                next_sibling: None,
101
                last_child: Some(NodeId::new(4)),
102
            },
103
            Node {
104
                parent: Some(NodeId::new(0)),
105
                previous_sibling: None,
106
                next_sibling: Some(NodeId::new(4)),
107
                last_child: Some(NodeId::new(3)),
108
            },
109
            Node {
110
                parent: Some(NodeId::new(1)),
111
                previous_sibling: None,
112
                next_sibling: Some(NodeId::new(3)),
113
                last_child: None,
114
            },
115
            Node {
116
                parent: Some(NodeId::new(1)),
117
                previous_sibling: Some(NodeId::new(2)),
118
                next_sibling: None,
119
                last_child: None,
120
            },
121
            Node {
122
                parent: Some(NodeId::new(0)),
123
                previous_sibling: Some(NodeId::new(1)),
124
                next_sibling: None,
125
                last_child: None,
126
            },
127
        ]
128
    }
129

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

            
134
    // ---------------------------------------------------------------------
135
    // NodeId::new / index / ZERO  (constructor + getter)
136
    // ---------------------------------------------------------------------
137

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

            
145
    #[test]
146
    fn node_id_zero_matches_new_zero() {
147
        assert_eq!(NodeId::ZERO, NodeId::new(0));
148
        assert_eq!(NodeId::ZERO.index(), 0);
149
    }
150

            
151
    #[test]
152
    fn node_id_usize_conversions_are_lossless() {
153
        for v in [0_usize, 7, usize::MAX] {
154
            let id: NodeId = v.into();
155
            let back: usize = id.into();
156
            assert_eq!(back, v);
157
        }
158
    }
159

            
160
    #[test]
161
    fn node_id_ordering_follows_index() {
162
        assert!(NodeId::new(0) < NodeId::new(1));
163
        assert!(NodeId::new(1) < NodeId::new(usize::MAX));
164
        assert_eq!(NodeId::new(3), NodeId::new(3));
165
    }
166

            
167
    // ---------------------------------------------------------------------
168
    // NodeId::from_usize / into_raw  (1-based FFI encoding round-trip)
169
    // ---------------------------------------------------------------------
170

            
171
    #[test]
172
    fn from_usize_zero_is_none_and_shifts_by_one() {
173
        assert_eq!(NodeId::from_usize(0), None);
174
        assert_eq!(NodeId::from_usize(1), Some(NodeId::new(0)));
175
        assert_eq!(NodeId::from_usize(2), Some(NodeId::new(1)));
176
        // usize::MAX must NOT overflow the `i - 1` decode.
177
        assert_eq!(
178
            NodeId::from_usize(usize::MAX),
179
            Some(NodeId::new(usize::MAX - 1))
180
        );
181
    }
182

            
183
    #[test]
184
    fn into_raw_encodes_none_as_zero() {
185
        assert_eq!(NodeId::into_raw(&None), 0);
186
        assert_eq!(NodeId::into_raw(&Some(NodeId::new(0))), 1);
187
        assert_eq!(NodeId::into_raw(&Some(NodeId::new(41))), 42);
188
        // Largest index that survives the +1 encode without overflowing.
189
        assert_eq!(
190
            NodeId::into_raw(&Some(NodeId::new(usize::MAX - 1))),
191
            usize::MAX
192
        );
193
    }
194

            
195
    #[test]
196
    fn encode_decode_roundtrip_is_identity() {
197
        // decode(encode(x)) == x
198
        for x in [
199
            None,
200
            Some(NodeId::new(0)),
201
            Some(NodeId::new(1)),
202
            Some(NodeId::new(9_999)),
203
            Some(NodeId::new(usize::MAX - 1)),
204
        ] {
205
            assert_eq!(
206
                NodeId::from_usize(NodeId::into_raw(&x)),
207
                x,
208
                "decode(encode({x:?}))"
209
            );
210
        }
211
        // encode(decode(n)) == n
212
        for n in [0_usize, 1, 2, 12_345, usize::MAX] {
213
            assert_eq!(
214
                NodeId::into_raw(&NodeId::from_usize(n)),
215
                n,
216
                "encode(decode({n}))"
217
            );
218
        }
219
    }
220

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

            
242
    // ---------------------------------------------------------------------
243
    // NodeId Display / Debug  (serializer)
244
    // ---------------------------------------------------------------------
245

            
246
    #[test]
247
    fn node_id_display_and_debug_are_well_formed() {
248
        assert_eq!(alloc::format!("{}", NodeId::new(0)), "0");
249
        assert_eq!(alloc::format!("{}", NodeId::new(7)), "7");
250
        assert_eq!(alloc::format!("{:?}", NodeId::new(7)), "NodeId(7)");
251
        // Extreme values must render without panicking and stay non-empty.
252
        let max = alloc::format!("{}", NodeId::new(usize::MAX));
253
        assert_eq!(max, alloc::format!("{}", usize::MAX));
254
        assert!(!max.is_empty());
255
        assert_eq!(
256
            alloc::format!("{:?}", NodeId::new(usize::MAX)),
257
            alloc::format!("NodeId({})", usize::MAX)
258
        );
259
    }
260

            
261
    // ---------------------------------------------------------------------
262
    // Node predicates + get_first_child
263
    // ---------------------------------------------------------------------
264

            
265
    #[test]
266
    fn node_root_and_default_have_no_relations() {
267
        for n in [Node::ROOT, Node::default()] {
268
            assert!(!n.has_parent());
269
            assert!(!n.has_previous_sibling());
270
            assert!(!n.has_next_sibling());
271
            assert!(!n.has_first_child());
272
            assert!(!n.has_last_child());
273
            assert_eq!(n.get_first_child(NodeId::new(0)), None);
274
        }
275
        assert_eq!(Node::default(), Node::ROOT);
276
    }
277

            
278
    #[test]
279
    fn node_predicates_report_each_populated_field() {
280
        let full = Node {
281
            parent: Some(NodeId::new(1)),
282
            previous_sibling: Some(NodeId::new(2)),
283
            next_sibling: Some(NodeId::new(3)),
284
            last_child: Some(NodeId::new(4)),
285
        };
286
        assert!(full.has_parent());
287
        assert!(full.has_previous_sibling());
288
        assert!(full.has_next_sibling());
289
        assert!(full.has_first_child());
290
        assert!(full.has_last_child());
291
    }
292

            
293
    /// INVARIANT: `has_first_child()` and `has_last_child()` read the same
294
    /// field, so they can never disagree — child-presence is all-or-nothing.
295
    #[test]
296
    fn has_first_child_always_agrees_with_has_last_child() {
297
        for last_child in [None, Some(NodeId::new(0)), Some(NodeId::new(usize::MAX))] {
298
            let n = Node {
299
                last_child,
300
                ..Node::ROOT
301
            };
302
            assert_eq!(n.has_first_child(), n.has_last_child());
303
            assert_eq!(n.has_first_child(), last_child.is_some());
304
        }
305
    }
306

            
307
    #[test]
308
    fn get_first_child_is_self_plus_one_and_saturates() {
309
        let parent = Node {
310
            last_child: Some(NodeId::new(9)),
311
            ..Node::ROOT
312
        };
313
        assert_eq!(parent.get_first_child(NodeId::new(0)), Some(NodeId::new(1)));
314
        assert_eq!(parent.get_first_child(NodeId::new(5)), Some(NodeId::new(6)));
315
        // Extreme id: the `+ 1` is saturating, so this must not panic/wrap. It
316
        // yields an obviously-invalid id that fails loudly at the next lookup.
317
        assert_eq!(
318
            parent.get_first_child(NodeId::new(usize::MAX)),
319
            Some(NodeId::new(usize::MAX))
320
        );
321
        // A leaf has no first child regardless of how extreme the id is.
322
        assert_eq!(Node::ROOT.get_first_child(NodeId::new(usize::MAX)), None);
323
    }
324

            
325
    // ---------------------------------------------------------------------
326
    // NodeHierarchy / NodeHierarchyRef
327
    // ---------------------------------------------------------------------
328

            
329
    #[test]
330
    fn hierarchy_new_preserves_len_and_contents() {
331
        let h = NodeHierarchy::new(tree_5());
332
        assert_eq!(h.as_ref().len(), 5);
333
        assert!(!h.as_ref().is_empty());
334
        assert_eq!(h.as_ref().get(NodeId::new(0)), Some(&tree_5()[0]));
335
        assert_eq!(h.as_ref().internal, &tree_5()[..]);
336
    }
337

            
338
    #[test]
339
    fn empty_hierarchy_is_empty_everywhere() {
340
        let h = NodeHierarchy::new(Vec::new());
341
        let r = h.as_ref();
342
        assert_eq!(r.len(), 0);
343
        assert!(r.is_empty());
344
        assert_eq!(r.get(NodeId::new(0)), None);
345
        assert_eq!(r.linear_iter().count(), 0);
346
        assert!(r.get_parents_sorted_by_depth().is_empty());
347

            
348
        let default = NodeHierarchy::default();
349
        assert!(default.as_ref().is_empty());
350
    }
351

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

            
358
        let nodes = tree_5();
359
        let r = NodeHierarchyRef::from_slice(&nodes);
360
        assert_eq!(r.len(), 5);
361
        assert!(!r.is_empty());
362
    }
363

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

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

            
385
    #[test]
386
    fn hierarchy_linear_iter_walks_every_index_in_order() {
387
        let nodes = tree_5();
388
        let r = NodeHierarchyRef::from_slice(&nodes);
389
        let ids: Vec<NodeId> = r.linear_iter().collect();
390
        assert_eq!(
391
            ids,
392
            (0..5).map(NodeId::new).collect::<Vec<_>>(),
393
            "linear_iter must yield 0..len exactly once, in order"
394
        );
395
    }
396

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

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

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

            
425
    // ---------------------------------------------------------------------
426
    // NodeId::children / preceding_siblings  (NodeHierarchyRef iterators)
427
    // ---------------------------------------------------------------------
428

            
429
    #[test]
430
    fn children_yields_direct_children_only() {
431
        let nodes = tree_5();
432
        let r = NodeHierarchyRef::from_slice(&nodes);
433
        assert_eq!(
434
            NodeId::new(0).children(&r).collect::<Vec<_>>(),
435
            vec![NodeId::new(1), NodeId::new(4)]
436
        );
437
        assert_eq!(
438
            NodeId::new(1).children(&r).collect::<Vec<_>>(),
439
            vec![NodeId::new(2), NodeId::new(3)]
440
        );
441
        // Leaves have no children.
442
        assert_eq!(NodeId::new(2).children(&r).count(), 0);
443
        assert_eq!(NodeId::new(4).children(&r).count(), 0);
444
    }
445

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

            
456
    #[test]
457
    fn preceding_siblings_starts_with_self_then_walks_backwards() {
458
        let nodes = tree_5();
459
        let r = NodeHierarchyRef::from_slice(&nodes);
460
        assert_eq!(
461
            NodeId::new(3).preceding_siblings(&r).collect::<Vec<_>>(),
462
            vec![NodeId::new(3), NodeId::new(2)],
463
            "the iterator includes the node itself first"
464
        );
465
        // A first-born has only itself.
466
        assert_eq!(
467
            NodeId::new(2).preceding_siblings(&r).collect::<Vec<_>>(),
468
            vec![NodeId::new(2)]
469
        );
470
    }
471

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

            
492
    // ---------------------------------------------------------------------
493
    // NodeDataContainer / Ref / RefMut
494
    // ---------------------------------------------------------------------
495

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

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

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

            
515
    #[test]
516
    fn data_container_ref_get_out_of_bounds_returns_none() {
517
        let data = [1_u8, 2, 3];
518
        let r = NodeDataContainerRef::from_slice(&data);
519
        assert_eq!(r.get(NodeId::new(0)), Some(&1));
520
        assert_eq!(r.get(NodeId::new(3)), None);
521
        assert_eq!(r.get(NodeId::new(usize::MAX)), None);
522
    }
523

            
524
    #[test]
525
    #[should_panic]
526
    fn data_container_ref_index_out_of_bounds_panics() {
527
        let data = [1_u8, 2, 3];
528
        let r = NodeDataContainerRef::from_slice(&data);
529
        let _ = &r[NodeId::new(3)];
530
    }
531

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

            
540
        let empty: [u8; 0] = [];
541
        let e = NodeDataContainerRef::from_slice(&empty);
542
        assert_eq!(e.len(), 0);
543
        assert!(e.is_empty());
544
        assert_eq!(e.iter().count(), 0);
545
        assert_eq!(e.linear_iter().next(), None);
546
    }
547

            
548
    #[test]
549
    fn data_container_ref_mut_get_mut_is_bounds_checked() {
550
        let mut c = NodeDataContainer::new(vec![1_u32, 2, 3]);
551
        let mut m = c.as_ref_mut();
552
        assert_eq!(m.get_mut(NodeId::new(3)), None);
553
        assert_eq!(m.get_mut(NodeId::new(usize::MAX)), None);
554
        *m.get_mut(NodeId::new(1)).unwrap() = 99;
555
        m[NodeId::new(2)] = 7;
556
        assert_eq!(m[NodeId::new(2)], 7);
557
        assert_eq!(c.internal, vec![1, 99, 7]);
558
    }
559

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

            
568
    #[test]
569
    #[should_panic]
570
    fn data_container_ref_mut_index_out_of_bounds_panics() {
571
        let mut data = [1_u8, 2];
572
        let m = NodeDataContainerRefMut::from_slice(&mut data);
573
        let _ = &m[NodeId::new(2)];
574
    }
575

            
576
    // ---------------------------------------------------------------------
577
    // transform_nodeid_optional
578
    // ---------------------------------------------------------------------
579

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

            
589
    #[test]
590
    fn transform_nodeid_optional_empty_input_never_calls_the_closure() {
591
        let empty: [u32; 0] = [];
592
        let r = NodeDataContainerRef::from_slice(&empty);
593
        let calls = AtomicUsize::new(0);
594
        let out = r.transform_nodeid_optional(|_| {
595
            calls.fetch_add(1, Ordering::SeqCst);
596
            Some(1_u32)
597
        });
598
        assert_eq!(calls.load(Ordering::SeqCst), 0);
599
        assert!(out.is_empty());
600
    }
601

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

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

            
634
    // ---------------------------------------------------------------------
635
    // NodeId::az_children / az_reverse_children / az_children_collect
636
    // ---------------------------------------------------------------------
637

            
638
    #[test]
639
    fn az_children_walks_forwards_and_reverse_walks_backwards() {
640
        let nodes = tree_5();
641
        let it = items(&nodes);
642
        let h = NodeDataContainerRef::from_slice(&it);
643

            
644
        assert_eq!(
645
            NodeId::new(0).az_children_collect(&h),
646
            vec![NodeId::new(1), NodeId::new(4)]
647
        );
648
        assert_eq!(
649
            NodeId::new(1).az_children(&h).collect::<Vec<_>>(),
650
            vec![NodeId::new(2), NodeId::new(3)]
651
        );
652
        assert_eq!(
653
            NodeId::new(1).az_reverse_children(&h).collect::<Vec<_>>(),
654
            vec![NodeId::new(3), NodeId::new(2)],
655
            "reverse iteration starts at last_child and walks previous_sibling"
656
        );
657
        // Leaves yield nothing in either direction.
658
        assert_eq!(NodeId::new(2).az_children(&h).count(), 0);
659
        assert_eq!(NodeId::new(2).az_reverse_children(&h).count(), 0);
660
        assert!(NodeId::new(3).az_children_collect(&h).is_empty());
661
    }
662

            
663
    #[test]
664
    #[should_panic]
665
    fn az_children_of_out_of_bounds_node_panics_loudly() {
666
        let nodes = tree_5();
667
        let it = items(&nodes);
668
        let h = NodeDataContainerRef::from_slice(&it);
669
        let _ = NodeId::new(5).az_children(&h);
670
    }
671

            
672
    /// ADVERSARIAL: a `next_sibling` that points back at the node itself makes
673
    /// `az_children` an infinite iterator. It must not panic, but
674
    /// `az_children_collect` on such a hierarchy would allocate until OOM —
675
    /// so only a bounded prefix is taken here.
676
    #[test]
677
    fn az_children_on_sibling_cycle_repeats_without_panicking() {
678
        let nodes = vec![
679
            Node {
680
                last_child: Some(NodeId::new(1)),
681
                ..Node::ROOT
682
            },
683
            Node {
684
                parent: Some(NodeId::new(0)),
685
                previous_sibling: None,
686
                next_sibling: Some(NodeId::new(1)), // points at itself
687
                last_child: None,
688
            },
689
        ];
690
        let it = items(&nodes);
691
        let h = NodeDataContainerRef::from_slice(&it);
692
        let prefix: Vec<NodeId> = NodeId::new(0).az_children(&h).take(5).collect();
693
        assert_eq!(prefix, vec![NodeId::new(1); 5]);
694
    }
695

            
696
    // ---------------------------------------------------------------------
697
    // NodeId::get_nearest_matching_parent
698
    // ---------------------------------------------------------------------
699

            
700
    #[test]
701
    fn nearest_matching_parent_skips_non_matching_ancestors() {
702
        let nodes = tree_5();
703
        let it = items(&nodes);
704
        let h = NodeDataContainerRef::from_slice(&it);
705
        // From node 2, the first ancestor is 1, then the root 0.
706
        assert_eq!(
707
            NodeId::new(2).get_nearest_matching_parent(&h, |_| true),
708
            Some(NodeId::new(1))
709
        );
710
        assert_eq!(
711
            NodeId::new(2).get_nearest_matching_parent(&h, |n| n == NodeId::new(0)),
712
            Some(NodeId::new(0))
713
        );
714
        // The root has no parent at all.
715
        assert_eq!(
716
            NodeId::new(0).get_nearest_matching_parent(&h, |_| true),
717
            None
718
        );
719
        // Nothing matches -> None, and the walk terminates.
720
        assert_eq!(
721
            NodeId::new(3).get_nearest_matching_parent(&h, |_| false),
722
            None
723
        );
724
    }
725

            
726
    #[test]
727
    fn nearest_matching_parent_out_of_bounds_self_returns_none() {
728
        let nodes = tree_5();
729
        let it = items(&nodes);
730
        let h = NodeDataContainerRef::from_slice(&it);
731
        assert_eq!(
732
            NodeId::new(5).get_nearest_matching_parent(&h, |_| true),
733
            None
734
        );
735
        assert_eq!(
736
            NodeId::new(usize::MAX).get_nearest_matching_parent(&h, |_| true),
737
            None
738
        );
739
    }
740

            
741
    #[test]
742
    fn nearest_matching_parent_self_parent_cycle_terminates() {
743
        // node 1 is its own parent — the node-count cap must break the loop.
744
        let nodes = vec![
745
            Node::ROOT,
746
            Node {
747
                parent: Some(NodeId::new(1)),
748
                ..Node::ROOT
749
            },
750
        ];
751
        let it = items(&nodes);
752
        let h = NodeDataContainerRef::from_slice(&it);
753
        assert_eq!(
754
            NodeId::new(1).get_nearest_matching_parent(&h, |_| false),
755
            None
756
        );
757
    }
758

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

            
776
        // Rejecting predicate: the dangling id fails the `get()` and yields None.
777
        assert_eq!(
778
            NodeId::new(1).get_nearest_matching_parent(&h, |_| false),
779
            None
780
        );
781
        // Accepting predicate: the dangling id is returned as-is.
782
        assert_eq!(
783
            NodeId::new(1).get_nearest_matching_parent(&h, |_| true),
784
            Some(NodeId::new(99))
785
        );
786
        assert!(
787
            h.get(NodeId::new(99)).is_none(),
788
            "and it is NOT a valid index"
789
        );
790
    }
791
}