indextree 4.9.1

Arena based tree structure by using indices instead of reference counted pointers
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
//! Arena structure and node storage.
//!
//! The [`Arena`] is the central owner of all tree nodes. Nodes are stored
//! contiguously in a single `Vec` and referenced by [`NodeId`](crate::NodeId).
//! Removed nodes are recycled through an internal free list.

#[cfg(not(feature = "std"))]
use alloc::{
    vec,
    vec::{IntoIter, Vec},
};

#[cfg(not(feature = "std"))]
use core::{
    mem,
    num::NonZeroUsize,
    ops::{Index, IndexMut},
    slice,
};

#[cfg(feature = "par_iter")]
use rayon::prelude::*;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "std")]
use std::{
    mem,
    num::NonZeroUsize,
    ops::{Index, IndexMut},
    slice,
    vec::IntoIter,
};

use crate::{Node, NodeId, node::NodeData};

#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// An `Arena` structure containing certain [`Node`]s.
pub struct Arena<T> {
    nodes: Vec<Node<T>>,
    first_free_slot: Option<usize>,
    last_free_slot: Option<usize>,
}

impl<T> Arena<T> {
    /// Creates a new empty `Arena`.
    #[must_use]
    pub const fn new() -> Arena<T> {
        Self {
            nodes: Vec::new(),
            first_free_slot: None,
            last_free_slot: None,
        }
    }

    /// Creates a new empty `Arena` with enough capacity to store `n` nodes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let arena: Arena<i32> = Arena::with_capacity(10);
    /// assert!(arena.capacity() >= 10);
    /// ```
    #[must_use]
    pub fn with_capacity(n: usize) -> Self {
        Self {
            nodes: Vec::with_capacity(n),
            first_free_slot: None,
            last_free_slot: None,
        }
    }

    /// Returns the number of nodes the arena can hold without reallocating.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let arena: Arena<i32> = Arena::with_capacity(10);
    /// assert!(arena.capacity() >= 10);
    /// ```
    pub fn capacity(&self) -> usize {
        self.nodes.capacity()
    }

    /// Reserves capacity for `additional` more nodes to be inserted.
    ///
    /// The arena may reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds isize::MAX bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena: Arena<i32> = Arena::new();
    /// arena.reserve(100);
    /// assert!(arena.capacity() >= 100);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        self.nodes.reserve(additional);
    }

    /// Retrieves the `NodeId` corresponding to a `Node` in the `Arena`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let node = arena.get(foo).unwrap();
    ///
    /// let node_id = arena.get_node_id(node).unwrap();
    /// assert_eq!(*arena[node_id].get(), "foo");
    /// ```
    pub fn get_node_id(&self, node: &Node<T>) -> Option<NodeId> {
        let nodes_range = self.nodes.as_ptr_range();
        let p = node as *const Node<T>;

        if !nodes_range.contains(&p) {
            return None;
        }

        let node_index = (p as usize - nodes_range.start as usize) / mem::size_of::<Node<T>>();
        let node_id = NonZeroUsize::new(node_index.wrapping_add(1))?;

        Some(NodeId::from_non_zero_usize(
            node_id,
            self.nodes[node_index].stamp,
        ))
    }

    /// Retrieves the `NodeId` corresponding to the `Node` at `index` in the `Arena`, if it exists.
    ///
    /// Note: We use 1 based indexing, so the first element is at `1` and not `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// # use std::num::NonZeroUsize;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let node = arena.get(foo).unwrap();
    /// let index: NonZeroUsize = foo.into();
    ///
    /// let new_foo = arena.get_node_id_at(index).unwrap();
    /// assert_eq!(foo, new_foo);
    ///
    /// foo.remove(&mut arena);
    /// let new_foo = arena.get_node_id_at(index);
    /// assert!(new_foo.is_none(), "must be none if the node at the index doesn't exist");
    /// ```
    pub fn get_node_id_at(&self, index: NonZeroUsize) -> Option<NodeId> {
        let index0 = index.get() - 1; // we use 1 based indexing.
        self.nodes
            .get(index0)
            .filter(|n| !n.is_removed())
            .map(|node| NodeId::from_non_zero_usize(index, node.stamp))
    }

    /// Creates a new node from its associated data.
    ///
    /// Freed slots are reused when available. If a slot's internal stamp has
    /// been exhausted (after ~32K remove/reuse cycles), it is skipped and a
    /// fresh slot is appended instead.
    ///
    /// # Panics
    ///
    /// Panics if the arena already has `usize::max_value()` nodes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    ///
    /// assert_eq!(*arena[foo].get(), "foo");
    /// ```
    pub fn new_node(&mut self, data: T) -> NodeId {
        let (index, stamp) = if let Some(index) = self.pop_front_free_node() {
            let node = &mut self.nodes[index];
            node.reuse(data);
            (index, node.stamp)
        } else {
            let index = self.nodes.len();
            let node = Node::new(data);
            let stamp = node.stamp;
            self.nodes.push(node);
            (index, stamp)
        };
        let next_index1 =
            NonZeroUsize::new(index.wrapping_add(1)).expect("Too many nodes in the arena");
        NodeId::from_non_zero_usize(next_index1, stamp)
    }

    /// Returns the number of slots in the arena, including removed nodes.
    ///
    /// Removed nodes are still counted because they remain in the
    /// internal storage. Use [`iter()`] with [`Node::is_removed()`]
    /// to count only live nodes.
    ///
    /// [`iter()`]: Arena::iter
    /// [`Node::is_removed()`]: crate::Node::is_removed
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let _bar = arena.new_node("bar");
    /// assert_eq!(arena.count(), 2);
    /// assert_eq!(arena.len(), 2);
    ///
    /// foo.remove(&mut arena);
    /// // The removed node is still counted.
    /// assert_eq!(arena.count(), 2);
    /// assert_eq!(arena.len(), 2);
    /// ```
    #[deprecated(since = "4.9.0", note = "use len() instead")]
    pub fn count(&self) -> usize {
        self.nodes.len()
    }

    /// Returns the number of slots in the arena, including removed nodes.
    ///
    /// Removed nodes are still counted because they remain in the
    /// internal storage. Use [`iter()`] with [`Node::is_removed()`]
    /// to count only live nodes.
    ///
    /// [`iter()`]: Arena::iter
    /// [`Node::is_removed()`]: crate::Node::is_removed
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let _bar = arena.new_node("bar");
    /// assert_eq!(arena.len(), 2);
    ///
    /// foo.remove(&mut arena);
    /// // The removed node is still counted.
    /// assert_eq!(arena.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Returns `true` if arena has no nodes, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// assert!(arena.is_empty());
    ///
    /// let foo = arena.new_node("foo");
    /// assert!(!arena.is_empty());
    ///
    /// foo.remove(&mut arena);
    /// assert!(!arena.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Returns a reference to the node with the given id if in the arena.
    ///
    /// Returns `None` if the index is out of bounds or the node's stamp
    /// does not match (i.e. the slot was removed and possibly reused).
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::{Arena, NodeId};
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// assert_eq!(arena.get(foo).map(|node| *node.get()), Some("foo"));
    /// ```
    ///
    /// Stale `NodeId`s from removed nodes return `None`:
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// foo.remove(&mut arena);
    /// assert!(arena.get(foo).is_none());
    /// ```
    #[inline]
    pub fn get(&self, id: NodeId) -> Option<&Node<T>> {
        self.nodes
            .get(id.index0())
            .filter(|node| node.stamp == id.stamp())
    }

    /// Returns a mutable reference to the node with the given id if in the
    /// arena.
    ///
    /// Returns `None` if the index is out of bounds or the node's stamp
    /// does not match.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::{Arena, NodeId};
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// assert_eq!(arena.get(foo).map(|node| *node.get()), Some("foo"));
    ///
    /// *arena.get_mut(foo).expect("The `foo` node exists").get_mut() = "FOO!";
    /// assert_eq!(arena.get(foo).map(|node| *node.get()), Some("FOO!"));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut Node<T>> {
        let stamp = id.stamp();
        self.nodes
            .get_mut(id.index0())
            .filter(|node| node.stamp == stamp)
    }

    /// Returns a reference to the data of the node with the given id.
    ///
    /// Returns `None` if the id is out of bounds, the stamp doesn't match,
    /// or the node has been removed.
    ///
    /// This is a shorthand for `arena.get(id).map(|n| n.get())`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// assert_eq!(arena.get_data(foo), Some(&"foo"));
    ///
    /// foo.remove(&mut arena);
    /// assert_eq!(arena.get_data(foo), None);
    /// ```
    #[inline]
    pub fn get_data(&self, id: NodeId) -> Option<&T> {
        self.get(id).map(|n| n.get())
    }

    /// Returns a mutable reference to the data of the node with the given id.
    ///
    /// Returns `None` if the id is out of bounds, the stamp doesn't match,
    /// or the node has been removed.
    ///
    /// This is a shorthand for `arena.get_mut(id).map(|n| n.get_mut())`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// *arena.get_data_mut(foo).unwrap() = "bar";
    /// assert_eq!(arena.get_data(foo), Some(&"bar"));
    /// ```
    #[inline]
    pub fn get_data_mut(&mut self, id: NodeId) -> Option<&mut T> {
        self.get_mut(id).map(|n| n.get_mut())
    }

    /// Returns an iterator of all nodes in the arena in storage-order.
    ///
    /// Note that this iterator returns also removed elements, which can be
    /// tested with the [`is_removed()`] method on the node.
    ///
    /// To iterate over only live nodes by their [`NodeId`], use
    /// [`iter_node_ids()`](Arena::iter_node_ids) instead.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let _foo = arena.new_node("foo");
    /// let _bar = arena.new_node("bar");
    ///
    /// let mut iter = arena.iter();
    /// assert_eq!(iter.next().map(|node| *node.get()), Some("foo"));
    /// assert_eq!(iter.next().map(|node| *node.get()), Some("bar"));
    /// assert_eq!(iter.next().map(|node| *node.get()), None);
    /// ```
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let _foo = arena.new_node("foo");
    /// let bar = arena.new_node("bar");
    /// bar.remove(&mut arena);
    ///
    /// let mut iter = arena.iter();
    /// assert_eq!(iter.next().map(|node| (*node.get(), node.is_removed())), Some(("foo", false)));
    /// assert_eq!(iter.next().map_or(false, |node| node.is_removed()), true);
    /// assert_eq!(iter.next().map(|node| (*node.get(), node.is_removed())), None);
    /// ```
    ///
    /// [`is_removed()`]: Node::is_removed
    pub fn iter(&self) -> slice::Iter<'_, Node<T>> {
        self.nodes.iter()
    }

    /// Returns an iterator of [`NodeId`]s of all non-removed nodes in
    /// the arena in storage-order.
    ///
    /// Unlike [`iter()`], this skips removed nodes and yields `NodeId`s
    /// instead of `&Node<T>`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let bar = arena.new_node("bar");
    /// let baz = arena.new_node("baz");
    /// bar.remove(&mut arena);
    ///
    /// let ids: Vec<_> = arena.iter_node_ids().collect();
    /// assert_eq!(ids, vec![foo, baz]);
    /// ```
    ///
    /// [`iter()`]: Arena::iter
    pub fn iter_node_ids(&self) -> impl Iterator<Item = NodeId> + '_ {
        self.nodes.iter().enumerate().filter_map(|(i, node)| {
            if node.is_removed() {
                return None;
            }
            let index1 = NonZeroUsize::new(i.wrapping_add(1))?;
            Some(NodeId::from_non_zero_usize(index1, node.stamp))
        })
    }

    /// Returns a mutable iterator of all nodes in the arena in storage-order.
    ///
    /// Note that this iterator returns also removed elements, which can be
    /// tested with the [`is_removed()`] method on the node.
    ///
    /// # Example
    ///
    /// ```
    /// # use indextree::Arena;
    /// let arena: &mut Arena<i64> = &mut Arena::new();
    /// let a = arena.new_node(1);
    /// let b = arena.new_node(2);
    /// assert!(a.checked_append(b, arena).is_ok());
    ///
    /// for node in arena.iter_mut() {
    ///     let data = node.get_mut();
    ///     *data = data.wrapping_add(4);
    /// }
    ///
    /// let node_refs = arena.iter().map(|i| i.get().clone()).collect::<Vec<_>>();
    /// assert_eq!(node_refs, vec![5, 6]);
    /// ```
    /// [`is_removed()`]: Node::is_removed
    pub fn iter_mut(&mut self) -> slice::IterMut<'_, Node<T>> {
        self.nodes.iter_mut()
    }

    /// Returns an iterator of [`NodeId`]s of all root nodes (nodes with
    /// no parent) that are not removed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let a = arena.new_node("a");
    /// let b = arena.new_node("b");
    /// let c = arena.new_node("c");
    /// a.append(c, &mut arena);
    ///
    /// let roots: Vec<_> = arena.roots().collect();
    /// assert_eq!(roots, vec![a, b]);
    /// ```
    pub fn roots(&self) -> impl Iterator<Item = NodeId> + '_ {
        self.iter_node_ids()
            .filter(|&id| self[id].parent().is_none())
    }

    /// Creates a new arena by applying a function to the data of every
    /// live node, preserving the tree structure.
    ///
    /// Removed nodes remain as removed slots in the new arena to keep
    /// node indices consistent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let root = arena.new_node(1);
    /// let child = root.append_value(2, &mut arena);
    ///
    /// let mapped: Arena<String> = arena.map(|x| x.to_string());
    /// assert_eq!(mapped.get_data(root), Some(&"1".to_string()));
    /// assert_eq!(mapped.get_data(child), Some(&"2".to_string()));
    /// assert_eq!(mapped[child].parent(), Some(root));
    /// ```
    pub fn map<U>(&self, mut f: impl FnMut(&T) -> U) -> Arena<U> {
        let nodes = self
            .nodes
            .iter()
            .map(|node| Node {
                parent: node.parent,
                previous_sibling: node.previous_sibling,
                next_sibling: node.next_sibling,
                first_child: node.first_child,
                last_child: node.last_child,
                stamp: node.stamp,
                data: match &node.data {
                    NodeData::Data(data) => NodeData::Data(f(data)),
                    NodeData::NextFree(next) => NodeData::NextFree(*next),
                },
            })
            .collect();
        Arena {
            nodes,
            first_free_slot: self.first_free_slot,
            last_free_slot: self.last_free_slot,
        }
    }

    /// Shrinks the internal storage to fit the current number of nodes.
    ///
    /// Calls [`Vec::shrink_to_fit`] on the underlying node storage.
    pub fn shrink_to_fit(&mut self) {
        self.nodes.shrink_to_fit();
    }

    /// Returns the number of live (non-removed) nodes in the arena.
    ///
    /// This is O(n) as it scans all slots. For the total slot count
    /// (including removed nodes), use [`len()`](Arena::len).
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// let bar = arena.new_node("bar");
    /// assert_eq!(arena.live_count(), 2);
    ///
    /// foo.remove(&mut arena);
    /// assert_eq!(arena.live_count(), 1);
    /// assert_eq!(arena.len(), 2);
    /// ```
    pub fn live_count(&self) -> usize {
        self.nodes.iter().filter(|n| !n.is_removed()).count()
    }

    /// Clears all the nodes in the arena, but retains its allocated capacity.
    ///
    /// Note that this does not mark all nodes as removed, but completely
    /// removes them from the arena storage, thus invalidating all the node
    /// IDs that were previously created.
    ///
    /// After clearing, [`NodeId::is_removed`] returns `true` for any
    /// previously created ID (without panicking), and [`Arena::get`]
    /// returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let foo = arena.new_node("foo");
    /// arena.clear();
    /// assert!(arena.is_empty());
    /// assert!(foo.is_removed(&arena));
    /// ```
    pub fn clear(&mut self) {
        self.nodes.clear();
        self.first_free_slot = None;
        self.last_free_slot = None;
    }

    /// Returns a slice of the inner nodes collection.
    ///
    /// The slice contains all nodes in storage order, including removed
    /// nodes. Use [`Node::is_removed()`] to filter them out.
    ///
    /// [`Node::is_removed()`]: crate::Node::is_removed
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// arena.new_node("foo");
    /// arena.new_node("bar");
    /// assert_eq!(arena.as_slice().len(), 2);
    /// ```
    pub fn as_slice(&self) -> &[Node<T>] {
        self.nodes.as_slice()
    }

    /// Validates the internal consistency of the arena's tree structure.
    ///
    /// Returns `true` if the arena passes all of the following checks:
    ///
    /// - Every live node contains actual data (not a free-list entry).
    /// - Parent, previous/next sibling, and first/last child pointers
    ///   all refer to valid, non-removed nodes with matching stamps.
    /// - `first_child` and `last_child` are both set or both unset.
    /// - Sibling back-pointers are reciprocal (prev's next == self,
    ///   next's prev == self).
    /// - Every child in a parent's child chain points back to that
    ///   parent, and the chain ends at `last_child`.
    /// - Every node claiming a parent appears in that parent's child
    ///   chain.
    /// - No cycles exist in sibling chains (bounded by arena length).
    /// - The free list is well-formed: consistent first/last pointers,
    ///   all entries are removed nodes with `NextFree` data, and no
    ///   cycles.
    ///
    /// This is primarily useful after deserialization to detect
    /// corrupted data.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// let mut arena = Arena::new();
    /// let root = arena.new_node(1);
    /// root.append_value(2, &mut arena);
    /// assert!(arena.validate());
    /// ```
    #[must_use]
    pub fn validate(&self) -> bool {
        let len = self.nodes.len();

        let is_valid = |id: NodeId| -> bool {
            let idx = id.index0();
            idx < len && self.nodes[idx].stamp == id.stamp() && !self.nodes[idx].is_removed()
        };

        let mut in_child_chain = vec![false; len];

        for (i, node) in self.nodes.iter().enumerate() {
            if node.is_removed() {
                continue;
            }

            if !matches!(node.data, NodeData::Data(_)) {
                return false;
            }

            if let Some(parent) = node.parent {
                if !is_valid(parent) {
                    return false;
                }
            }

            if let Some(prev) = node.previous_sibling {
                if !is_valid(prev)
                    || self.nodes[prev.index0()].next_sibling.map(|n| n.index0()) != Some(i)
                {
                    return false;
                }
            }
            if let Some(next) = node.next_sibling {
                if !is_valid(next)
                    || self.nodes[next.index0()]
                        .previous_sibling
                        .map(|n| n.index0())
                        != Some(i)
                {
                    return false;
                }
            }

            if node.first_child.is_some() != node.last_child.is_some() {
                return false;
            }

            if let Some(first) = node.first_child {
                if !is_valid(first) {
                    return false;
                }
                let mut child = Some(first);
                let mut last_seen = first;
                let mut steps = 0;
                while let Some(c) = child {
                    let idx = c.index0();
                    if idx >= len {
                        return false;
                    }
                    let child_node = &self.nodes[idx];
                    if child_node.parent.map(|n| n.index0()) != Some(i) {
                        return false;
                    }
                    in_child_chain[idx] = true;
                    last_seen = c;
                    child = child_node.next_sibling;
                    steps += 1;
                    if steps > len {
                        return false;
                    }
                }
                if node.last_child.map(|n| n.index0()) != Some(last_seen.index0()) {
                    return false;
                }
            }
        }

        for (i, node) in self.nodes.iter().enumerate() {
            if !node.is_removed() && node.parent.is_some() && !in_child_chain[i] {
                return false;
            }
        }

        // Validate free list
        if self.first_free_slot.is_some() != self.last_free_slot.is_some() {
            return false;
        }
        let mut free_count = 0;
        let mut last_visited = None;
        let mut slot = self.first_free_slot;
        while let Some(idx) = slot {
            if idx >= len {
                return false;
            }
            let node = &self.nodes[idx];
            if !node.is_removed() {
                return false;
            }
            match node.data {
                NodeData::NextFree(next) => slot = next,
                _ => return false,
            }
            last_visited = Some(idx);
            free_count += 1;
            if free_count > len {
                return false;
            }
        }

        self.last_free_slot == last_visited
    }

    pub(crate) fn free_node(&mut self, id: NodeId) {
        let node = &mut self[id];
        if node.is_removed() {
            return;
        }
        node.data = NodeData::NextFree(None);
        node.stamp.mark_removed();
        let stamp = node.stamp;
        if stamp.reuseable() {
            if let Some(index) = self.last_free_slot {
                let new_last = id.index0();
                self.nodes[index].data = NodeData::NextFree(Some(new_last));
                self.last_free_slot = Some(new_last);
            } else {
                debug_assert!(self.first_free_slot.is_none());
                debug_assert!(self.last_free_slot.is_none());
                self.first_free_slot = Some(id.index0());
                self.last_free_slot = Some(id.index0());
            }
        }
    }

    fn pop_front_free_node(&mut self) -> Option<usize> {
        let first = self.first_free_slot.take();
        if let Some(index) = first {
            if let NodeData::NextFree(next_free) = self.nodes[index].data {
                self.first_free_slot = next_free;
            } else {
                unreachable!("A data node considered as a freed node");
            }
            if self.first_free_slot.is_none() {
                self.last_free_slot = None;
            }
        }

        first
    }
}

#[cfg(feature = "par_iter")]
impl<T: Sync> Arena<T> {
    /// Returns a parallel iterator over the whole arena.
    ///
    /// Requires the `par_iter` feature. Uses [rayon](https://docs.rs/rayon)
    /// for data parallelism across all nodes in storage order.
    ///
    /// Note that this iterator returns also removed elements, which can be
    /// tested with the [`is_removed()`] method on the node.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// # use rayon::prelude::*;
    /// let mut arena = Arena::new();
    /// let root = arena.new_node(1);
    /// root.append_value(2, &mut arena);
    /// root.append_value(3, &mut arena);
    ///
    /// let sum: i64 = arena.par_iter().map(|node| *node.get()).sum();
    /// assert_eq!(sum, 6);
    /// ```
    ///
    /// [`is_removed()`]: Node::is_removed
    pub fn par_iter(&self) -> rayon::slice::Iter<'_, Node<T>> {
        self.nodes.par_iter()
    }
}

#[cfg(feature = "par_iter")]
impl<T: Send> Arena<T> {
    /// Returns a mutable parallel iterator over the whole arena.
    ///
    /// Requires the `par_iter` feature. Uses [rayon](https://docs.rs/rayon)
    /// for data parallelism across all nodes in storage order.
    ///
    /// Note that this iterator returns also removed elements, which can be
    /// tested with the [`is_removed()`] method on the node.
    ///
    /// # Examples
    ///
    /// ```
    /// # use indextree::Arena;
    /// # use rayon::prelude::*;
    /// let mut arena = Arena::new();
    /// let root = arena.new_node(1);
    /// root.append_value(2, &mut arena);
    /// root.append_value(3, &mut arena);
    ///
    /// arena.par_iter_mut().for_each(|node| {
    ///     if let Some(data) = node.try_get_mut() {
    ///         *data *= 10;
    ///     }
    /// });
    ///
    /// let sum: i64 = arena.par_iter().map(|node| *node.get()).sum();
    /// assert_eq!(sum, 60);
    /// ```
    ///
    /// [`is_removed()`]: Node::is_removed
    pub fn par_iter_mut(&mut self) -> rayon::slice::IterMut<'_, Node<T>> {
        self.nodes.par_iter_mut()
    }
}

impl<'a, T> IntoIterator for &'a Arena<T> {
    type Item = &'a Node<T>;
    type IntoIter = slice::Iter<'a, Node<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut Arena<T> {
    type Item = &'a mut Node<T>;
    type IntoIter = slice::IterMut<'a, Node<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<T> Extend<T> for Arena<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        let (lower, _) = iter.size_hint();
        self.reserve(lower);
        for item in iter {
            self.new_node(item);
        }
    }
}

impl<T> core::iter::FromIterator<T> for Arena<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut arena = Arena::new();
        arena.extend(iter);
        arena
    }
}

/// Consumes the arena, returning an iterator over all nodes (including removed ones).
impl<T> IntoIterator for Arena<T> {
    type Item = Node<T>;
    type IntoIter = IntoIter<Node<T>>;

    fn into_iter(self) -> Self::IntoIter {
        self.nodes.into_iter()
    }
}

impl<T> Default for Arena<T> {
    fn default() -> Self {
        Self {
            nodes: Vec::new(),
            first_free_slot: None,
            last_free_slot: None,
        }
    }
}

/// Index by [`NodeId`] for convenient `arena[id]` access.
///
/// Unlike [`Arena::get`], this does **not** validate the node's stamp,
/// so it may silently return data from a reused slot if the `NodeId`
/// is stale. For safe access, prefer [`Arena::get`] or [`Arena::get_mut`].
///
/// # Panics
///
/// Panics if `node` is out of bounds. Note that indexing does not validate
/// that the `NodeId` originated from this arena. Using an ID from a
/// different arena may silently access the wrong node or panic.
impl<T> Index<NodeId> for Arena<T> {
    type Output = Node<T>;

    #[inline]
    fn index(&self, node: NodeId) -> &Node<T> {
        &self.nodes[node.index0()]
    }
}

/// Mutable index by [`NodeId`].
///
/// Like [`Index<NodeId>`], this does **not** validate the node's stamp.
/// For safe access, prefer [`Arena::get_mut`].
///
/// # Panics
///
/// Panics if `node` is out of bounds.
impl<T> IndexMut<NodeId> for Arena<T> {
    #[inline]
    fn index_mut(&mut self, node: NodeId) -> &mut Node<T> {
        &mut self.nodes[node.index0()]
    }
}

#[test]
fn reuse_node() {
    let mut arena = Arena::new();
    let n1_id = arena.new_node("1");
    let n2_id = arena.new_node("2");
    let n3_id = arena.new_node("3");
    n1_id.remove(&mut arena);
    n2_id.remove(&mut arena);
    n3_id.remove(&mut arena);
    let n1_id = arena.new_node("1");
    let n2_id = arena.new_node("2");
    let n3_id = arena.new_node("3");
    assert_eq!(n1_id.index0(), 0);
    assert_eq!(n2_id.index0(), 1);
    assert_eq!(n3_id.index0(), 2);
    assert_eq!(arena.nodes.len(), 3);
}

#[test]
fn conserve_capacity() {
    let mut arena = Arena::with_capacity(5);
    let cap = arena.capacity();
    assert!(cap >= 5);
    for i in 0..cap {
        arena.new_node(i);
    }
    arena.clear();
    assert!(arena.is_empty());
    let n1_id = arena.new_node(1);
    let n2_id = arena.new_node(2);
    let n3_id = arena.new_node(3);
    assert_eq!(n1_id.index0(), 0);
    assert_eq!(n2_id.index0(), 1);
    assert_eq!(n3_id.index0(), 2);
    assert_eq!(arena.len(), 3);
    assert_eq!(arena.capacity(), cap);
}

#[test]
fn stamp_no_cycle() {
    // Regression test for issue #95: stamps should never cycle back to
    // a previously used value after many reuse rounds.
    let mut arena = Arena::new();
    for _ in 0..=i16::MAX as u32 + 1 {
        let id = arena.new_node(42);
        assert!(!id.is_removed(&arena));
        id.remove(&mut arena);
        assert!(id.is_removed(&arena));
        let new_id = arena.new_node(42);
        assert!(!new_id.is_removed(&arena));
        assert!(id.is_removed(&arena));
        new_id.remove(&mut arena);
    }
}