generational_arena_tree/lib.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5#![feature(doc_cfg)]
6#![warn(clippy::missing_const_for_fn)]
7
8//! Trees based on indexes to a generational arena.
9//!
10//! # Features
11//! - `default`
12//! - `split`, `unified`, `deque`
13//! - `split`
14//! - Enables
15#![cfg_attr(not(feature = "split"), doc = " split")]
16#![cfg_attr(feature = "split", doc = " [split]")]
17//! nodes, where each [node] is split into
18#,")]
19#,")]
20//! which may have [children], and
21#![cfg_attr(not(feature = "split"), doc = " 'leaves',")]
22#,")]
23//! which may not have [children].
24//! - `unified`
25//! - Enables
26#![cfg_attr(not(feature = "unified"), doc = " unified")]
27#![cfg_attr(feature = "unified", doc = " [unified]")]
28//! nodes, where every [node] may have [children].
29//! - `deque`
30//! - Enables [nodes] which have [`VecDeque`] [children], rather than siblings forming a [linked]
31//! list, allowing operations by index.
32//! - `serde`
33//! - Enables implementations of [serde]'s [`Serialize`] and [`Deserialize`] traits.
34//!
35//! [serde]: https://serde.rs/
36//! [`Serialize`]: https://docs.rs/serde/1.0.193/serde/trait.Serialize.html
37//! [`Deserialize`]: https://docs.rs/serde/1.0.193/serde/trait.Deserialize.html
38//!
39//! [node]: Node
40//! [nodes]: Node
41//! [linked]: LinkedNode
42//! [children]: BranchNode::children
43
44pub mod iter;
45
46#[cfg(feature = "split")]
47#[doc(cfg(feature = "split"))]
48pub mod split;
49#[cfg(feature = "unified")]
50#[doc(cfg(feature = "unified"))]
51pub mod unified;
52
53macro_rules! token_to_node {
54 ($(ref $($mut:ident)?,)? $N:ty: $token:expr, $arena:expr) => {
55 <$(&$($mut)?)? $N as TryFrom<$(&$($mut)?)? <$N as Node>::Base>>::try_from(
56 $(&$($mut)?)? ($arena).0[($token).idx()]
57 )
58 .expect("We know this is the correct node type.")
59 };
60}
61
62use std::{
63 collections::VecDeque,
64 fmt::{Debug, Formatter},
65 hash::{Hash, Hasher},
66 iter::FusedIterator,
67 marker::PhantomData,
68 ops::Index,
69};
70
71use cfg_attrs::cfg_attrs;
72#[cfg(feature = "serde")]
73use serde::{Deserialize, Deserializer, Serialize, Serializer};
74pub(crate) use token_to_node;
75
76pub struct Token<N: Node> {
77 idx: generational_arena::Index,
78 _marker: PhantomData<N>,
79}
80
81#[cfg(feature = "serde")]
82impl<N: Node> Serialize for Token<N> {
83 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
84 where
85 S: Serializer,
86 {
87 self.idx.serialize(serializer)
88 }
89}
90
91#[cfg(feature = "serde")]
92impl<'a, N: Node> Deserialize<'a> for Token<N> {
93 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
94 where
95 D: Deserializer<'a>,
96 {
97 Ok(Self {
98 idx: generational_arena::Index::deserialize(deserializer)?,
99 _marker: PhantomData,
100 })
101 }
102}
103
104impl<N: Node> Debug for Token<N> {
105 #[inline(always)]
106 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
107 write!(f, "Token({:?})", self.idx)
108 }
109}
110
111impl<N: Node, I: Idx> PartialEq<I> for Token<N> {
112 #[inline(always)]
113 fn eq(&self, other: &I) -> bool {
114 self.idx() == other.idx()
115 }
116}
117
118impl<N: Node> Eq for Token<N> {}
119
120impl<N: Node> Hash for Token<N> {
121 #[inline(always)]
122 fn hash<H: Hasher>(&self, state: &mut H) {
123 self.idx().hash(state)
124 }
125}
126
127impl<N: Node> Clone for Token<N> {
128 #[inline(always)]
129 fn clone(&self) -> Self {
130 *self
131 }
132}
133
134impl<N: Node> Copy for Token<N> {}
135
136mod sealed {
137 /// Seals a trait, restricting external crates from implementing it.
138 pub trait Sealed {}
139
140 /// Provides a [`NodeToken`]'s [arena index] and seals the trait.
141 ///
142 /// [`NodeToken`]: NodeToken
143 /// [arena index]: generational_arena::Index
144 pub trait Idx {
145 /// Return's this [token]'s [arena index].
146 ///
147 /// [token]: NodeToken
148 /// [arena index]: generational_arena::Index;
149 fn idx(&self) -> generational_arena::Index;
150 }
151}
152
153pub(crate) use sealed::*;
154
155pub trait NodeToken<N: Node>: Idx + Copy + PartialEq + Debug {
156 /// Returns this [node]'s parent's token.
157 ///
158 /// If this token refers to a root node, that node will have no parent, so [`None`] is returned.
159 ///
160 /// [node]: Node
161 #[inline(always)]
162 fn parent(&self, arena: &Arena<N::Base>) -> Option<<<N::Base as BaseNode>::Branch as Node>::Token> {
163 arena.0[self.idx()].parent()
164 }
165
166 /// Returns an iterator over the tokens of this [node]'s ancestors.
167 ///
168 /// This iterator begins with the [node]'s [parent] and ends with the [root] node (i.e. the
169 /// ancestor with no [parent]).
170 ///
171 /// [node]: Node
172 /// [parent]: Self::parent
173 /// [root]: Self::root
174 #[inline(always)]
175 fn ancestors<'arena>(&self, arena: &'arena Arena<N::Base>) -> iter::Ancestors<'arena, N::Base> {
176 arena.0[self.idx()].ancestors(arena)
177 }
178
179 /// Returns this [node]'s root node.
180 ///
181 /// The root node is the most distant [ancestor]; it is the only [node] in a tree that does not
182 /// have a [parent].
183 ///
184 /// If this [node] is the root node, [`RootToken::This`] is returned. Otherwise,
185 /// [`RootToken::Ancestor`] is returned with the root node's token.
186 ///
187 /// Internally, this method iterates over the [node]'s [ancestors] to find the last one, so it
188 /// is `O(n)` best, average, and worst case.
189 ///
190 /// [node]: Node
191 /// [ancestor]: Self::ancestors
192 /// [parent]: Self::parent
193 /// [ancestors]: Self::ancestors
194 #[inline]
195 fn root<'arena>(&self, arena: &'arena Arena<N::Base>) -> RootToken<N>
196 where
197 for<'base> &'base N: TryFrom<&'base N::Base>,
198 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
199 {
200 token_to_node!(ref, N: self, arena).root(arena)
201 }
202
203 /// Returns a reference to the [data] associated with this [node].
204 ///
205 /// [node]: Node
206 /// [data]: N::Data
207 #[inline]
208 fn data<'arena>(&self, arena: &'arena Arena<N::Base>) -> N::DataRef<'arena>
209 where
210 for<'base> &'base N: TryFrom<&'base N::Base>,
211 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
212 {
213 token_to_node!(ref, N: self, arena).data()
214 }
215
216 /// Returns a mutable reference to the [data] associated with this [node].
217 ///
218 /// [node]: DataNode
219 /// [data]: N::Data
220 #[inline]
221 fn data_mut<'arena>(&self, arena: &'arena mut Arena<N::Base>) -> N::DataRefMut<'arena>
222 where
223 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
224 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
225 {
226 token_to_node!(ref mut, N: self, arena).data_mut()
227 }
228
229 /// Returns the token of this [node]'s previous sibling.
230 ///
231 /// If this [node] is the first child of its [parent], that means there is no previous sibling
232 /// and thus [`None`] is returned.
233 ///
234 /// [node]: LinkedNode
235 /// [parent]: Self::parent
236 #[inline(always)]
237 fn prev(&self, arena: &Arena<N::Base>) -> Option<<N::Base as Node>::Token>
238 where
239 N::Base: LinkedNode,
240 {
241 arena.0[self.idx()].prev()
242 }
243 /// Returns the token of this [node]'s next sibling.
244 ///
245 /// If this [node] is the last child of its [parent], that means there is no next sibling and
246 /// thus [`None`] is returned.
247 ///
248 /// [node]: LinkedNode
249 /// [parent]: Self::parent
250 #[inline(always)]
251 fn next(&self, arena: &Arena<N::Base>) -> Option<<N::Base as Node>::Token>
252 where
253 N::Base: LinkedNode,
254 {
255 arena.0[self.idx()].next()
256 }
257
258 /// Returns an iterator over the tokens of this [node]'s preceding siblings.
259 ///
260 /// This iterator begins with the [previous] node and ends with the [first child] of the
261 /// [parent] node.
262 ///
263 /// If this is the [first child], the iterator will be empty.
264 ///
265 /// [node]: Node
266 /// [previous]: Self::prev
267 /// [first child]: BranchNode::first
268 /// [parent]: Self::parent
269 #[inline(always)]
270 fn preceding_siblings<'arena>(&self, arena: &'arena Arena<N::Base>) -> iter::PrecedingSiblings<'arena, N>
271 where
272 N::Base: LinkedNode,
273 {
274 iter::PrecedingSiblings::new(arena, self.prev(arena))
275 }
276
277 /// Returns an iterator over the tokens of this [node]'s following siblings.
278 ///
279 /// This iterator begins with the [next] node and ends with the [last child] of the [parent]
280 /// node.
281 ///
282 /// If this is the [last child], the iterator will be empty.
283 ///
284 /// [node]: Node
285 /// [next]: Self::next
286 /// [last child]: BranchNode::last
287 /// [parent]: Self::parent
288 #[inline(always)]
289 fn following_siblings<'arena>(&self, arena: &'arena Arena<N::Base>) -> iter::FollowingSiblings<'arena, N>
290 where
291 N::Base: LinkedNode,
292 {
293 iter::FollowingSiblings::new(arena, self.next(arena))
294 }
295
296 /// Returns the token of this [branch node]'s first child.
297 ///
298 /// If this [branch node] has no children, [`None`] is returned.
299 ///
300 /// [branch node]: BranchNode
301 #[inline]
302 fn first(&self, arena: &Arena<N::Base>) -> Option<<N::Base as Node>::Token>
303 where
304 N: BranchNode,
305 for<'base> &'base N: TryFrom<&'base N::Base>,
306 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
307 {
308 token_to_node!(ref, N: self, arena).first()
309 }
310 /// Returns the token of this [branch node]'s last child.
311 ///
312 /// If this [branch node] has no children, [`None`] is returned.
313 ///
314 /// [branch node]: BranchNode
315 #[inline]
316 fn last(&self, arena: &Arena<N::Base>) -> Option<<N::Base as Node>::Token>
317 where
318 N: BranchNode,
319 for<'base> &'base N: TryFrom<&'base N::Base>,
320 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
321 {
322 token_to_node!(ref, N: self, arena).last()
323 }
324
325 /// Returns an iterator over the tokens of this [branch node]'s children.
326 ///
327 /// [branch node]: BranchNode
328 #[inline]
329 fn children<'arena>(&self, arena: &'arena Arena<N::Base>) -> N::ChildrenIter<'arena>
330 where
331 N: BranchNode,
332 for<'base> &'base N: TryFrom<&'base N::Base>,
333 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
334 {
335 token_to_node!(ref, N: self, arena).children(arena)
336 }
337
338 /// Returns an iterator over the tokens of this [branch node]'s descendants.
339 ///
340 /// This iterator is a breadth-first traversal of the branch node's descendants: its [children]
341 /// are done first, then those [children]'s [children] in the same order, and so on and so on.
342 ///
343 /// [branch node]: BranchNode
344 /// [children]: Self::children
345 #[inline]
346 fn descendants<'arena>(&self, arena: &'arena Arena<N::Base>) -> iter::Descendants<'arena, N>
347 where
348 N: BranchNode,
349 for<'base> &'base N: TryFrom<&'base N::Base>,
350 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
351 {
352 iter::Descendants::new(token_to_node!(ref, N: self, arena), arena)
353 }
354
355 #[cfg(feature = "deque")]
356 /// Returns the number of children this [branch node] has.
357 ///
358 /// [branch node]: BranchNodeDeque
359 #[doc(cfg(feature = "deque"))]
360 #[inline]
361 fn len(&self, arena: &Arena<N::Base>) -> usize
362 where
363 N: BranchNodeDeque,
364 for<'base> &'base N: TryFrom<&'base N::Base>,
365 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
366 {
367 token_to_node!(ref, N: self, arena).len()
368 }
369
370 /// Returns whether this [branch node] has no children.
371 ///
372 /// [branch node]: BranchNode
373 #[inline]
374 fn is_empty(&self, arena: &Arena<N::Base>) -> bool
375 where
376 N: BranchNode,
377 for<'base> &'base N: TryFrom<&'base N::Base>,
378 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
379 {
380 token_to_node!(ref, N: self, arena).is_empty()
381 }
382
383 #[cfg(feature = "deque")]
384 /// Returns the token of the child at the given `index`.
385 ///
386 /// # Panics
387 /// This method will panic if `index` is out of bounds.
388 ///
389 /// # See also
390 /// For a fallible version, see [`get`].
391 ///
392 /// [`get`]: Self::get
393 #[doc(cfg(feature = "deque"))]
394 #[inline]
395 fn get_unchecked(&self, arena: &Arena<N::Base>, index: usize) -> <N::Base as Node>::Token
396 where
397 N: BranchNodeDeque,
398 for<'base> &'base N: TryFrom<&'base N::Base>,
399 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
400 {
401 token_to_node!(ref, N: self, arena)[index]
402 }
403
404 #[cfg(feature = "deque")]
405 /// Returns the token of the child at the given `index`.
406 ///
407 /// If `index` is out of bounds, [`None`] is returned.
408 ///
409 /// # See also
410 /// For a version without bounds checks, see [`get_unchecked`].
411 ///
412 /// [`get_unchecked`]: Self::get_unchecked
413 #[doc(cfg(feature = "deque"))]
414 #[inline]
415 fn get(&self, arena: &Arena<N::Base>, index: usize) -> Option<<N::Base as Node>::Token>
416 where
417 N: BranchNodeDeque,
418 for<'base> &'base N: TryFrom<&'base N::Base>,
419 for<'base> <&'base N as TryFrom<&'base N::Base>>::Error: Debug,
420 {
421 token_to_node!(ref, N: self, arena).get(index)
422 }
423
424 #[cfg_attrs]
425 /// Detaches this branch node's [first child], returning its token.
426 ///
427 /// If this branch node is [empty] then there is no child to detach, so [`None`] is
428 /// returned. Otherwise, the child is removed from this branch node's [children], but
429 /// remains in the [arena].
430 ///
431 /// This function is useful if you want to move a [node] from one [parent] to another.
432 ///
433 /// # See also
434 /// The [last child] may also be detached using [`detach_back`].
435 #[configure(
436 feature = "deque",
437 /// If this is a [`BranchNodeDeque`], children may also be detached by index using
438 /// [`detach`].
439 ///
440 /// [`detach`]: BranchNodeDeque::detach
441 )]
442 /// If you want to remove a child and its descendants from the [arena] altogether, see
443 #[configure(
444 feature = "deque",
445 /// [`pop_front`], [`pop_back`], or, if this is a [`BranchNodeDeque`], [`remove`].
446 ///
447 /// [`remove`]: BranchNodeDeque::remove
448 )]
449 #[configure(
450 not(feature = "deque"),
451 /// [`pop_front`] and [`pop_back`].
452 )]
453 /// [`detach_back`]: Self::detach_back
454 ///
455 /// [`pop_front`]: Self::pop_front
456 /// [`pop_back`]: Self::pop_back
457 ///
458 /// [first child]: Self::first
459 /// [last child]: Self::last
460 /// [empty]: Self::is_empty
461 /// [children]: Self::children
462 /// [arena]: Arena
463 /// [node]: Node
464 /// [parent]: Node::parent
465 #[inline]
466 fn detach_front(&self, arena: &mut Arena<N::Base>) -> Option<<N::Base as Node>::Token>
467 where
468 N: BranchNode<Token = Self>,
469 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
470 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
471 {
472 N::detach_front(*self, arena)
473 }
474 #[cfg_attrs]
475 /// Detaches this branch node's [last child], returning its token.
476 ///
477 /// If this branch node is [empty] then there is no child to detach, so [`None`] is
478 /// returned. Otherwise, the child is removed from this branch node's [children], but
479 /// remains in the [arena].
480 ///
481 /// This function is useful if you want to move a [node] from one [parent] to another.
482 ///
483 /// # See also
484 /// The [first child] may also be detached using [`detach_front`].
485 #[configure(
486 feature = "deque",
487 /// If this is a [`BranchNodeDeque`], children may also be detached by index using
488 /// [`detach`].
489 ///
490 /// [`detach`]: BranchNodeDeque::detach
491 )]
492 /// If you want to remove a child and its descendants from the [arena] altogether, see
493 #[configure(
494 feature = "deque",
495 /// [`pop_front`], [`pop_back`], or, if this is a [`BranchNodeDeque`], [`remove`].
496 ///
497 /// [`remove`]: BranchNodeDeque::remove
498 )]
499 #[configure(
500 not(feature = "deque"),
501 /// [`pop_front`] and [`pop_back`].
502 )]
503 /// [`detach_front`]: Self::detach_front
504 ///
505 /// [`pop_front`]: Self::pop_front
506 /// [`pop_back`]: Self::pop_back
507 /// [`remove`]: BranchNodeDeque::remove
508 ///
509 /// [first child]: Self::first
510 /// [last child]: Self::last
511 /// [empty]: Self::is_empty
512 /// [children]: Self::children
513 /// [arena]: Arena
514 /// [node]: Node
515 /// [parent]: Node::parent
516 #[inline]
517 fn detach_back(&self, arena: &mut Arena<N::Base>) -> Option<<N::Base as Node>::Token>
518 where
519 N: BranchNode<Token = Self>,
520 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
521 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
522 {
523 N::detach_back(*self, arena)
524 }
525
526 #[cfg_attrs]
527 /// Removes this branch node's [first child].
528 ///
529 /// If this branch node is [empty] then there is no child to remove, so [`None`] is
530 /// returned. Otherwise, the removed [node] is returned.
531 ///
532 /// # See also
533 /// The [last child] may also be removed using [`pop_back`].
534 #[configure(
535 feature = "deque",
536 /// If this is a [`BranchNodeDeque`], children may also be removed by index using
537 /// [`remove`].
538 ///
539 /// [`remove`]: BranchNodeDeque::remove
540 )]
541 /// If you don't want to remove a child from the [arena], but merely make it a [root node]
542 /// or move it to another [parent], see
543 #[configure(
544 feature = "deque",
545 /// [`detach_front`], [`detach_back`], or, if this is a [`BranchNodeDeque`], [`detach`].
546 ///
547 /// [`detach`]: BranchNodeDeque::detach
548 )]
549 #[configure(
550 not(feature = "deque"),
551 /// [`detach_front`] and [`detach_back`].
552 )]
553 /// [`pop_back`]: Self::pop_back
554 ///
555 /// [`detach_front`]: Self::detach_front
556 /// [`detach_back`]: Self::detach_back
557 ///
558 /// [first child]: Self::first
559 /// [last child]: Self::last
560 /// [node]: BaseNode
561 /// [empty]: Self::is_empty
562 /// [arena]: Arena
563 /// [root node]: Self::root
564 /// [parent]: Self::parent
565 #[inline]
566 fn pop_front(&self, arena: &mut Arena<N::Base>) -> Option<<N::Base as BaseNode>::Representation>
567 where
568 N: BranchNode<Token = Self>,
569 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
570 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
571 {
572 N::pop_front(*self, arena)
573 }
574 #[cfg_attrs]
575 /// Removes this branch node's [last child].
576 ///
577 /// If this branch node is [empty] then there is no child to remove, so [`None`] is
578 /// returned. Otherwise, the removed [node] is returned.
579 ///
580 /// # See also
581 /// The [first child] may also be removed using [`pop_front`].
582 #[configure(
583 feature = "deque",
584 /// If this is a [`BranchNodeDeque`], children may also be removed by index using
585 /// [`remove`].
586 ///
587 /// [`remove`]: BranchNodeDeque::remove
588 )]
589 /// If you don't want to remove a child from the [arena], but merely make it a [root node]
590 /// or move it to another [parent], see
591 #[configure(
592 feature = "deque",
593 /// [`detach_front`], [`detach_back`], or, if this is a [`BranchNodeDeque`], [`detach`].
594 ///
595 /// [`detach`]: BranchNodeDeque::detach
596 )]
597 #[configure(
598 not(feature = "deque"),
599 /// [`detach_front`] and [`detach_back`].
600 )]
601 /// [`pop_front`]: Self::pop_front
602 ///
603 /// [`detach_front`]: Self::detach_front
604 /// [`detach_back`]: Self::detach_back
605 ///
606 /// [first child]: Self::first
607 /// [last child]: Self::last
608 /// [node]: BaseNode
609 /// [empty]: Self::is_empty
610 /// [arena]: Arena
611 /// [root node]: Self::root
612 /// [parent]: Self::parent
613 #[inline]
614 fn pop_back(&self, arena: &mut Arena<N::Base>) -> Option<<N::Base as BaseNode>::Representation>
615 where
616 N: BranchNode<Token = Self>,
617 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
618 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
619 {
620 N::pop_front(*self, arena)
621 }
622
623 #[cfg_attrs]
624 /// Pushes the given `new` token's [node] to the beginning of this branch node's
625 /// [children].
626 ///
627 /// # Panics
628 /// This method will panic if the given `new` token refers to either:
629 /// - this branch node's [root]; or
630 /// - a [node] that already has a [parent].
631 ///
632 /// # See also
633 /// A child may also be pushed to the end with [`push_back`].
634 #[configure(
635 feature = "deque",
636 /// If this is a [`BranchNodeDeque`], [children] may also be inserted by index using
637 /// [`insert`].
638 ///
639 /// [`insert`]: BranchNodeDeque::insert
640 )]
641 /// [`push_back`]: Self::push_back
642 ///
643 /// [node]: BaseNode
644 /// [children]: Self::children
645 /// [root]: Self::root
646 /// [parent]: Node::parent
647 #[inline]
648 fn push_front(&self, arena: &mut Arena<N::Base>, new: <N::Base as Node>::Token)
649 where
650 N: BranchNode<Token = Self>,
651 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
652 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
653 {
654 N::push_front(*self, arena, new);
655 }
656 #[cfg_attrs]
657 /// Pushes the given `new` token's [node] to the end of this branch node's [children].
658 ///
659 /// # Panics
660 /// This method will panic if the given `new` token refers to either:
661 /// - this branch node's [root]; or
662 /// - a [node] that already has a [parent].
663 ///
664 /// # See also
665 /// A child may also be pushed to the beginning with [`push_front`]. If this is a
666 /// [`BranchNodeDeque`], children may also be inserted by index using [`insert`].
667 #[configure(
668 feature = "deque",
669 /// If this is a [`BranchNodeDeque`], [children] may also be inserted by index using
670 /// [`insert`].
671 ///
672 /// [`insert`]: BranchNodeDeque::insert
673 )]
674 /// [`push_front`]: Self::push_front
675 ///
676 /// [node]: BaseNode
677 /// [children]: Self::children
678 /// [root]: Self::root
679 /// [parent]: Node::parent
680 #[inline]
681 fn push_back(&self, arena: &mut Arena<N::Base>, new: <N::Base as Node>::Token)
682 where
683 N: BranchNode<Token = Self>,
684 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
685 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
686 {
687 N::push_back(*self, arena, new);
688 }
689
690 #[cfg(feature = "deque")]
691 /// Detaches the child at the given `index`, returning its token.
692 ///
693 /// This function is useful if you want to move a [node] from one [parent] to another.
694 ///
695 /// # Panics
696 /// This method will panic if the given `index` is out of bounds.
697 ///
698 /// # See also
699 /// The [first child] or [last child] may be detached with [`detach_front`] and [`detach_back`]
700 /// respectively.
701 ///
702 /// If you want to remove a child and its descendents from the [arena] altogether, see
703 /// [`remove`], [`pop_front`], or [`pop_back`].
704 ///
705 /// [`detach_front`]: Self::detach_front
706 /// [`detach_back`]: Self::detach_back
707 ///
708 /// [`remove`]: Self::remove
709 /// [`pop_front`]: Self::pop_front
710 /// [`pop_back`]: Self::pop_back
711 ///
712 /// [node]: Node
713 /// [arena]: Arena
714 /// [parent]: Node::parent
715 /// [first child]: Self::first
716 /// [last child]: Self::last
717 #[doc(cfg(feature = "deque"))]
718 #[inline]
719 fn detach(&self, arena: &mut Arena<N::Base>, index: usize) -> <N::Base as Node>::Token
720 where
721 N: BranchNodeDeque<Token = Self>,
722 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
723 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
724 {
725 N::detach(*self, arena, index)
726 }
727
728 #[cfg(feature = "deque")]
729 /// Removes the child at the given `index`.
730 ///
731 /// # Panics
732 /// This method will panic if the given `index` is out of bounds.
733 ///
734 /// # See also
735 /// The [first child] or [last child] may be removed with [`pop_front`] and [`pop_back`]
736 /// respectively.
737 ///
738 /// If you don't want to remove a child from the [arena], but merely make it a [root node] or
739 /// move it to another [parent], see [`detach`], [`detach_front`], or [`detach_back`].
740 ///
741 /// [`pop_front`]: Self::pop_front
742 /// [`pop_back`]: Self::pop_back
743 ///
744 /// [`detach`]: Self::detach
745 /// [`detach_front`]: Self::detach_front
746 /// [`detach_back`]: Self::detach_back
747 ///
748 /// [arena]: Arena
749 /// [root node]: Self::root
750 /// [first child]: Self::first
751 /// [last child]: Self::last
752 /// [parent]: Node::parent
753 #[doc(cfg(feature = "deque"))]
754 #[inline]
755 fn remove(&self, arena: &mut Arena<N::Base>, index: usize) -> <N::Base as BaseNode>::Representation
756 where
757 N: BranchNodeDeque<Token = Self>,
758 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
759 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
760 {
761 N::remove(*self, arena, index)
762 }
763
764 #[cfg(feature = "deque")]
765 /// Inserts the given `new` token's [node] at the given `index`.
766 ///
767 /// # Panics
768 /// This method will panic if:
769 /// - the given `index` is greater than the [`len()`]; or
770 /// - the given `new` [token] refers to either:
771 /// - this branch node's [root]; or
772 /// - a [node] that already has a [parent].
773 ///
774 /// # See also
775 /// A child can also be pushed to the beginning or end of this [branch node]'s [children] with
776 /// [`push_front`] and [`push_back`] respectively.
777 ///
778 /// [branch node]: BranchNodeDeque
779 /// [children]: Self::children
780 /// [`push_front`]: Self::push_front
781 /// [`push_back`]: Self::push_back
782 ///
783 /// [node]: BaseNode
784 /// [token]: Self::Token
785 /// [root]: Self::root
786 /// [parent]: Node::parent
787 ///
788 /// [`len()`]: Self::len
789 #[doc(cfg(feature = "deque"))]
790 #[inline]
791 fn insert(&self, arena: &mut Arena<N::Base>, index: usize, new: <N::Base as Node>::Token)
792 where
793 N: BranchNodeDeque<Token = Self>,
794 for<'base> &'base mut N: TryFrom<&'base mut N::Base>,
795 for<'base> <&'base mut N as TryFrom<&'base mut N::Base>>::Error: Debug,
796 {
797 N::insert(*self, arena, index, new)
798 }
799}
800
801impl<N: Node> Token<N> {
802 /// Creates a new token wrapping the given [arena index].
803 ///
804 /// [arena index]: generational_arena::Index
805 #[inline(always)]
806 pub(crate) const fn new(idx: generational_arena::Index) -> Self {
807 Self {
808 idx,
809 _marker: PhantomData,
810 }
811 }
812}
813
814impl<N: Node> Idx for Token<N> {
815 #[inline(always)]
816 fn idx(&self) -> generational_arena::Index {
817 self.idx
818 }
819}
820
821impl<N: Node<Token = Self>> NodeToken<N> for Token<N> {}
822
823/// A node in a tree.
824pub trait Node: Debug + Sealed {
825 /// The 'base node' used in the [arena].
826 ///
827 /// For typed nodes where there is a typed node type in addition to separate branch and leaf
828 /// types, all of those types will use the typed node type as the `ArenaNode`.
829 ///
830 /// [arena]: Arena
831 type Base: BaseNode;
832 /// The [token] associated with this type of node.
833 ///
834 /// [token]: NodeToken
835 type Token: NodeToken<Self>
836 where
837 Self: Sized;
838
839 /// The custom data associated with this node.
840 type Data;
841 /// A type acting as a reference to the node's [data].
842 ///
843 /// This is the type returned by [`data`].
844 ///
845 /// [data]: Self::Data
846 /// [`data`]: Self::data
847 type DataRef<'data>
848 where
849 Self: 'data;
850 /// A type acting as a mutable reference to the node's [data].
851 ///
852 /// This is the type returned by [`data_mut`].
853 ///
854 /// [data]: Self::Data
855 /// [`data_mut`]: Self::data_mut
856 type DataRefMut<'data>
857 where
858 Self: 'data;
859
860 /// Creates a new node allocated in the given `arena` using the given `data`.
861 ///
862 /// The node's [token] is returned.
863 ///
864 /// [token]: Token
865 fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Self::Token
866 where
867 Self: Sized;
868
869 /// Returns this node's [token].
870 ///
871 /// [token]: Self::Token
872 fn token(&self) -> Self::Token
873 where
874 Self: Sized;
875
876 /// Returns the [token] of this node's parent.
877 ///
878 /// If this node is the root node of its tree, that means it has no parent and thus [`None`] is
879 /// returned.
880 ///
881 /// [token]: Token
882 fn parent(&self) -> Option<<<Self::Base as BaseNode>::Branch as Node>::Token>;
883
884 /// Returns an iterator over the [tokens] of this node's ancestors.
885 ///
886 /// This iterator begins with the node's [parent] and ends with the [root] node (i.e. the
887 /// ancestor with no [parent]).
888 ///
889 /// [tokens]: Self::Token
890 /// [parent]: Self::parent
891 /// [root]: Self::root
892 #[inline(always)]
893 fn ancestors<'node>(&'node self, arena: &'node Arena<Self::Base>) -> iter::Ancestors<'node, Self::Base>
894 where
895 Self: Sized,
896 {
897 iter::Ancestors::new(arena, self.parent())
898 }
899
900 /// Returns this node's root node.
901 ///
902 /// The root node is the most distant [ancestor]; it is the only node in a tree that does not
903 /// have a [parent].
904 ///
905 /// If this node is the root node, [`RootToken::This`] is returned. Otherwise,
906 /// [`RootToken::Ancestor`] is returned with the root node's token.
907 ///
908 /// Internally, this method iterates over the node's [ancestors] to find the last one, so it is
909 /// `O(n)` best, average, and worst case.
910 ///
911 /// [ancestor]: Self::ancestors
912 /// [parent]: Self::parent
913 /// [ancestors]: Self::ancestors
914 #[inline(always)]
915 fn root<'node>(&'node self, arena: &'node Arena<Self::Base>) -> RootToken<Self>
916 where
917 Self: Sized,
918 {
919 match self.ancestors(arena).last() {
920 Some(root) => RootToken::Ancestor(root),
921 None => RootToken::This(self.token()),
922 }
923 }
924
925 /// Returns a reference to the [data] associated with this node.
926 ///
927 /// [data]: Self::Data
928 fn data(&self) -> Self::DataRef<'_>;
929
930 /// Returns a mutable reference to the [data] associated with this node.
931 ///
932 /// [data]: Self::Data
933 fn data_mut(&mut self) -> Self::DataRefMut<'_>;
934}
935
936#[derive(Debug)]
937pub enum RootToken<N: Node> {
938 Ancestor(<<N::Base as BaseNode>::Branch as Node>::Token),
939 This(N::Token),
940}
941
942impl<N: Node> Idx for RootToken<N> {
943 #[inline(always)]
944 fn idx(&self) -> generational_arena::Index {
945 match self {
946 Self::Ancestor(token) => token.idx(),
947 Self::This(token) => token.idx(),
948 }
949 }
950}
951
952impl<N: Node, I: Idx> PartialEq<I> for RootToken<N> {
953 fn eq(&self, other: &I) -> bool {
954 self.idx() == other.idx()
955 }
956}
957
958impl<N: Node> Eq for RootToken<N> {}
959
960impl<N: Node> Hash for RootToken<N> {
961 #[inline(always)]
962 fn hash<H: Hasher>(&self, state: &mut H) {
963 self.idx().hash(state);
964 }
965}
966
967impl<N: Node> Copy for RootToken<N> {}
968
969impl<N: Node> Clone for RootToken<N> {
970 fn clone(&self) -> Self {
971 *self
972 }
973}
974
975impl<N: Node> NodeToken<N::Base> for RootToken<N> {}
976
977pub trait BaseNode: Node<Base = Self> {
978 /// The representation of the node after it is removed from the [arena].
979 ///
980 /// If this is a [branch node], this representation should include its children.
981 ///
982 /// [arena]: Arena
983 /// [branch node]: BranchNode
984 type Representation;
985
986 /// The type used for branch nodes.
987 ///
988 /// This may be the base node itself, or a separate node type.
989 type Branch: BranchNode;
990 /// The type used for leaf nodes.
991 ///
992 /// This may be the base node itself, or a separate node type.
993 type Leaf: Node;
994
995 /// Converts this node into its [representation].
996 ///
997 /// If this is a [branch node], this node's children should be removed from the `arena` and
998 /// included in the [representation].
999 ///
1000 /// [representation]: Self::Representation
1001 /// [branch node]: BranchNode
1002 fn into_representation(self, arena: &mut Arena<Self>) -> Self::Representation
1003 where
1004 Self: Sized;
1005}
1006
1007#[cfg(feature = "deque")]
1008/// Removes the given children from the [branch node], returning their [representations].
1009///
1010/// [branch node]: BranchNodeDeque
1011/// [representations]: BaseNode::Representation
1012#[doc(cfg(feature = "deque"))]
1013pub(crate) fn remove_children_deque<Branch: BranchNodeDeque>(
1014 branch: &Branch,
1015 arena: &mut Arena<Branch::Base>,
1016) -> VecDeque<<Branch::Base as BaseNode>::Representation> {
1017 let mut children = VecDeque::new();
1018
1019 for i in 0..branch.len() {
1020 children.push_back(
1021 arena
1022 .0
1023 .remove(branch[i].idx())
1024 .expect("tried to remove child but there was no such node in the `arena`")
1025 .into_representation(arena),
1026 );
1027 }
1028
1029 children
1030}
1031
1032/// Removes the given children from the [branch node], returning their [representations].
1033///
1034/// [branch node]: BranchNode
1035/// [representations]: BaseNode::Representation
1036pub(crate) fn remove_children_linked<Branch: BranchNode>(
1037 branch: &Branch,
1038 arena: &mut Arena<Branch::Base>,
1039) -> VecDeque<<Branch::Base as BaseNode>::Representation>
1040where
1041 Branch::Base: LinkedNode,
1042{
1043 let mut children = VecDeque::new();
1044 let mut child = branch.first();
1045
1046 while let Some(token) = &child {
1047 let removed = arena
1048 .0
1049 .remove(token.idx())
1050 .expect("tried to remove child but there was no such node in the `arena`");
1051
1052 child = removed.next();
1053 children.push_back(removed.into_representation(arena));
1054 }
1055
1056 children
1057}
1058
1059/// A [node] that is linked to its [previous] and [next] siblings.
1060///
1061/// [node]: Node
1062/// [previous]: Self::prev
1063/// [next]: Self::next
1064pub trait LinkedNode: Node
1065where
1066 Self::Base: LinkedNode,
1067{
1068 /// Returns the [token] of this node's previous sibling.
1069 ///
1070 /// If this node is the first child of its [parent], that means there is no previous sibling and
1071 /// thus [`None`] is returned.
1072 ///
1073 /// [token]: Self::Token
1074 /// [parent]: Self::parent
1075 fn prev(&self) -> Option<<Self::Base as Node>::Token>;
1076 /// Returns the [token] of this node's next sibling.
1077 ///
1078 /// If this node is the last child of its [parent], that means there is no next sibling and thus
1079 /// [`None`] is returned.
1080 ///
1081 /// [token]: Self::Token
1082 /// [parent]: Self::parent
1083 fn next(&self) -> Option<<Self::Base as Node>::Token>;
1084
1085 /// Returns an iterator over the [tokens] of this node's preceding siblings.
1086 ///
1087 /// This iterator begins with the [previous] node and ends with the [first child] of the
1088 /// [parent] node.
1089 ///
1090 /// If this is the [first child], the iterator will be empty.
1091 ///
1092 /// [tokens]: Self::Token
1093 /// [previous]: Self::prev
1094 /// [first child]: BranchNode::first
1095 /// [parent]: Self::parent
1096 fn preceding_siblings<'node>(&'node self, arena: &'node Arena<Self::Base>) -> iter::PrecedingSiblings<'node, Self>
1097 where
1098 Self: Sized,
1099 {
1100 iter::PrecedingSiblings::new(arena, self.prev())
1101 }
1102 /// Returns an iterator over the [tokens] of this node's following siblings.
1103 ///
1104 /// This iterator begins with the [next] node and ends with the [last child] of the [parent]
1105 /// node.
1106 ///
1107 /// If this is the [last child], the iterator will be empty.
1108 ///
1109 /// [tokens]: Self::Token
1110 /// [next]: Self::next
1111 /// [last child]: BranchNode::last
1112 /// [parent]: Self::parent
1113 #[inline(always)]
1114 fn following_siblings<'node>(&'node self, arena: &'node Arena<Self::Base>) -> iter::FollowingSiblings<'node, Self>
1115 where
1116 Self: Sized,
1117 {
1118 iter::FollowingSiblings::new(arena, self.next())
1119 }
1120}
1121
1122#[cfg_attrs]
1123/// A [node] that can have [children].
1124///
1125/// [node]: Node
1126/// [children]: Self::children
1127pub trait BranchNode: Node {
1128 /// The iterator returned by [`children`].
1129 ///
1130 /// [`children`]: Self::children
1131 type ChildrenIter<'branch>: DoubleEndedIterator<Item = <Self::Base as Node>::Token> + FusedIterator
1132 where
1133 Self: 'branch;
1134
1135 /// Returns the [token] of this branch node's first child.
1136 ///
1137 /// If this branch node has no children, [`None`] is returned.
1138 ///
1139 /// [token]: Self::Token
1140 fn first(&self) -> Option<<Self::Base as Node>::Token>;
1141 /// Returns the [token] of this branch node's last child.
1142 ///
1143 /// If this branch node has no children, [`None`] is returned.
1144 ///
1145 /// [token]: Self::Token
1146 fn last(&self) -> Option<<Self::Base as Node>::Token>;
1147
1148 // TODO: Should there be a separate version for linked branch nodes and `BranchNodeDeque`s? For
1149 // : `BranchNodeDeque`s, `arena` is not necessary.
1150 /// Returns an iterator over the [tokens] of this branch node's children.
1151 ///
1152 /// [tokens]: Self::Token
1153 fn children<'branch>(&'branch self, arena: &'branch Arena<Self::Base>) -> Self::ChildrenIter<'branch>;
1154
1155 /// Returns an iterator over the [tokens] of this branch node's descendants.
1156 ///
1157 /// This iterator is a breadth-first traversal of the branch node's descendants: its [children]
1158 /// are done first, then those [children]'s [children] in the same order, and so on and so on.
1159 ///
1160 /// [tokens]: Node::Token
1161 /// [children]: Self::children
1162 #[inline(always)]
1163 fn descendants<'branch>(&'branch self, arena: &'branch Arena<Self::Base>) -> iter::Descendants<'branch, Self>
1164 where
1165 Self: Sized,
1166 for<'base> &'base Self: TryFrom<&'base Self::Base>,
1167 {
1168 iter::Descendants::new(self, arena)
1169 }
1170
1171 /// Returns whether this branch node has no children.
1172 fn is_empty(&self) -> bool;
1173
1174 /// Detaches this branch node's [first child], returning its [token].
1175 ///
1176 /// If this branch node is [empty] then there is no child to detach, so [`None`] is
1177 /// returned. Otherwise, the child is removed from this branch node's [children], but
1178 /// remains in the [arena].
1179 ///
1180 /// This function is useful if you want to move a [node] from one [parent] to another.
1181 ///
1182 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to
1183 /// avoid having multiple mutable references into the arena at a time.
1184 ///
1185 /// # See also
1186 /// The [last child] may also be detached using [`detach_back`].
1187 #[configure(
1188 feature = "deque",
1189 /// If this is a [`BranchNodeDeque`], children may also be detached by index using
1190 /// [`detach`].
1191 ///
1192 /// [`detach`]: BranchNodeDeque::detach
1193 )]
1194 /// If you want to remove a child and its descendants from the [arena] altogether, see
1195 #[configure(
1196 feature = "deque",
1197 /// [`pop_front`], [`pop_back`], or, if this is a [`BranchNodeDeque`], [`remove`].
1198 ///
1199 /// [`remove`]: BranchNodeDeque::remove
1200 )]
1201 #[configure(
1202 not(feature = "deque"),
1203 /// [`pop_front`] and [`pop_back`].
1204 )]
1205 /// [`detach_back`]: Self::detach_back
1206 ///
1207 /// [`pop_front`]: Self::pop_front
1208 /// [`pop_back`]: Self::pop_back
1209 ///
1210 /// [first child]: Self::first
1211 /// [last child]: Self::last
1212 /// [token]: Node::Token
1213 /// [empty]: Self::is_empty
1214 /// [children]: Self::children
1215 /// [arena]: Arena
1216 /// [node]: Node
1217 /// [parent]: Node::parent
1218 fn detach_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token>
1219 where
1220 Self: Sized,
1221 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1222 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1223 /// Detaches this branch node's [last child], returning its [token].
1224 ///
1225 /// If this branch node is [empty] then there is no child to detach, so [`None`] is
1226 /// returned. Otherwise, the child is removed from this branch node's [children], but
1227 /// remains in the [arena].
1228 ///
1229 /// This function is useful if you want to move a [node] from one [parent] to another.
1230 ///
1231 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to
1232 /// avoid having multiple mutable references into the arena at a time.
1233 ///
1234 /// # See also
1235 /// The [first child] may also be detached using [`detach_front`].
1236 #[configure(
1237 feature = "deque",
1238 /// If this is a [`BranchNodeDeque`], children may also be detached by index using
1239 /// [`detach`].
1240 ///
1241 /// [`detach`]: BranchNodeDeque::detach
1242 )]
1243 /// If you want to remove a child and its descendants from the [arena] altogether, see
1244 #[configure(
1245 feature = "deque",
1246 /// [`pop_front`], [`pop_back`], or, if this is a [`BranchNodeDeque`], [`remove`].
1247 ///
1248 /// [`remove`]: BranchNodeDeque::remove
1249 )]
1250 #[configure(
1251 not(feature = "deque"),
1252 /// [`pop_front`] and [`pop_back`].
1253 )]
1254 /// [`detach_front`]: Self::detach_front
1255 ///
1256 /// [`pop_front`]: Self::pop_front
1257 /// [`pop_back`]: Self::pop_back
1258 /// [`remove`]: BranchNodeDeque::remove
1259 ///
1260 /// [first child]: Self::first
1261 /// [last child]: Self::last
1262 /// [token]: Node::Token
1263 /// [empty]: Self::is_empty
1264 /// [children]: Self::children
1265 /// [arena]: Arena
1266 /// [node]: Node
1267 /// [parent]: Node::parent
1268 fn detach_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token>
1269 where
1270 Self: Sized,
1271 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1272 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1273
1274 /// Removes this branch node's [first child].
1275 ///
1276 /// If this branch node is [empty] then there is no child to remove, so [`None`] is
1277 /// returned. Otherwise, the removed [node] is returned.
1278 ///
1279 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to
1280 /// avoid having multiple mutable references into the arena at a time.
1281 ///
1282 /// # See also
1283 /// The [last child] may also be removed using [`pop_back`].
1284 #[configure(
1285 feature = "deque",
1286 /// If this is a [`BranchNodeDeque`], children may also be removed by index using
1287 /// [`remove`].
1288 ///
1289 /// [`remove`]: BranchNodeDeque::remove
1290 )]
1291 /// If you don't want to remove a child from the [arena], but merely make it a [root node]
1292 /// or move it to another [parent], see
1293 #[configure(
1294 feature = "deque",
1295 /// [`detach_front`], [`detach_back`], or, if this is a [`BranchNodeDeque`], [`detach`].
1296 ///
1297 /// [`detach`]: BranchNodeDeque::detach
1298 )]
1299 #[configure(
1300 not(feature = "deque"),
1301 /// [`detach_front`] and [`detach_back`].
1302 )]
1303 /// [`pop_back`]: Self::pop_back
1304 ///
1305 /// [`detach_front`]: Self::detach_front
1306 /// [`detach_back`]: Self::detach_back
1307 ///
1308 /// [first child]: Self::first
1309 /// [last child]: Self::last
1310 /// [node]: BaseNode
1311 /// [empty]: Self::is_empty
1312 /// [token]: Self::Token
1313 /// [arena]: Arena
1314 /// [root node]: Self::root
1315 /// [parent]: Self::parent
1316 fn pop_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as BaseNode>::Representation>
1317 where
1318 Self: Sized,
1319 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1320 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1321 /// Removes this branch node's [last child].
1322 ///
1323 /// If this branch node is [empty] then there is no child to remove, so [`None`] is
1324 /// returned. Otherwise, the removed [node] is returned.
1325 ///
1326 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver
1327 /// avoid having multiple mutable references into the arena at a time.
1328 ///
1329 /// # See also
1330 /// The [first child] may also be removed using [`pop_front`].
1331 #[configure(
1332 feature = "deque",
1333 /// If this is a [`BranchNodeDeque`], children may also be removed by index using
1334 /// [`remove`].
1335 ///
1336 /// [`remove`]: BranchNodeDeque::remove
1337 )]
1338 /// If you don't want to remove a child from the [arena], but merely make it a [root node]
1339 /// or move it to another [parent], see
1340 #[configure(
1341 feature = "deque",
1342 /// [`detach_front`], [`detach_back`], or, if this is a [`BranchNodeDeque`], [`detach`].
1343 ///
1344 /// [`detach`]: BranchNodeDeque::detach
1345 )]
1346 #[configure(
1347 not(feature = "deque"),
1348 /// [`detach_front`] and [`detach_back`].
1349 )]
1350 /// [`pop_front`]: Self::pop_front
1351 ///
1352 /// [`detach_front`]: Self::detach_front
1353 /// [`detach_back`]: Self::detach_back
1354 ///
1355 /// [first child]: Self::first
1356 /// [last child]: Self::last
1357 /// [node]: BaseNode
1358 /// [empty]: Self::is_empty
1359 /// [token]: Self::Token
1360 /// [arena]: Arena
1361 /// [root node]: Self::root
1362 /// [parent]: Self::parent
1363 fn pop_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as BaseNode>::Representation>
1364 where
1365 Self: Sized,
1366 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1367 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1368
1369 /// Pushes the given `new` [token]'s [node] to the beginning of this branch node's
1370 /// [children].
1371 ///
1372 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to
1373 /// avoid having multiple mutable references into the arena at a time.
1374 ///
1375 /// # Panics
1376 /// This method will panic if the given `new` [token] refers to either:
1377 /// - this branch node's [root]; or
1378 /// - a [node] that already has a [parent].
1379 ///
1380 /// # See also
1381 /// A child may also be pushed to the end with [`push_back`].
1382 #[configure(
1383 feature = "deque",
1384 /// If this is a [`BranchNodeDeque`], [children] may also be inserted by index using
1385 /// [`insert`].
1386 ///
1387 /// [`insert`]: BranchNodeDeque::insert
1388 )]
1389 /// [`push_back`]: Self::push_back
1390 ///
1391 /// [token]: Self::Token
1392 /// [node]: BaseNode
1393 /// [children]: Self::children
1394 /// [root]: Self::root
1395 /// [parent]: Node::parent
1396 fn push_front(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token)
1397 where
1398 Self: Sized,
1399 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1400 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1401 /// Pushes the given `new` [token]'s [node] to the end of this branch node's [children].
1402 ///
1403 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to
1404 /// avoid having multiple mutable references into the arena at a time.
1405 ///
1406 /// # Panics
1407 /// This method will panic if the given `new` [token] refers to either:
1408 /// - this branch node's [root]; or
1409 /// - a [node] that already has a [parent].
1410 ///
1411 /// # See also
1412 /// A child may also be pushed to the beginning with [`push_front`]. If this is a
1413 /// [`BranchNodeDeque`], children may also be inserted by index using [`insert`].
1414 #[configure(
1415 feature = "deque",
1416 /// If this is a [`BranchNodeDeque`], [children] may also be inserted by index using
1417 /// [`insert`].
1418 ///
1419 /// [`insert`]: BranchNodeDeque::insert
1420 )]
1421 /// [`push_front`]: Self::push_front
1422 ///
1423 /// [token]: Self::Token
1424 /// [node]: BaseNode
1425 /// [children]: Self::children
1426 /// [root]: Self::root
1427 /// [parent]: Node::parent
1428 fn push_back(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token)
1429 where
1430 Self: Sized,
1431 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1432 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1433}
1434
1435#[cfg(feature = "deque")]
1436/// A [node] that stores its [children] as a [`VecDeque`], allowing them to be [indexed].
1437///
1438/// [node]: Node
1439/// [children]: Self::children
1440///
1441/// [indexed]: Index
1442#[doc(cfg(feature = "deque"))]
1443pub trait BranchNodeDeque: BranchNode
1444where
1445 Self: Index<usize, Output = <Self::Base as Node>::Token> + Sized,
1446{
1447 /// Returns the number of children this branch node has.
1448 fn len(&self) -> usize;
1449
1450 /// Returns the [token] of the child at the given `index`.
1451 ///
1452 /// If `index` is out of bounds, [`None`] is returned.
1453 ///
1454 /// [token]: Node::Token
1455 #[inline]
1456 fn get(&self, index: usize) -> Option<<Self::Base as Node>::Token> {
1457 if index < self.len() {
1458 Some(self[index])
1459 } else {
1460 None
1461 }
1462 }
1463
1464 /// Detaches the child at the given `index`, returning its [token].
1465 ///
1466 /// This function is useful if you want to move a [node] from one [parent] to another.
1467 ///
1468 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to avoid
1469 /// having multiple mutable references into the [arena] at a time.
1470 ///
1471 /// # Panics
1472 /// This method will panic if the given `index` is out of bounds.
1473 ///
1474 /// # See also
1475 /// The [first child] or [last child] may be detached with [`detach_front`] and [`detach_back`]
1476 /// respectively.
1477 ///
1478 /// If you want to remove a child and its descendents from the [arena] altogether, see
1479 /// [`remove`], [`pop_front`], or [`pop_back`].
1480 ///
1481 /// [`detach_front`]: Self::detach_front
1482 /// [`detach_back`]: Self::detach_back
1483 ///
1484 /// [`remove`]: Self::remove
1485 /// [`pop_front`]: Self::pop_front
1486 /// [`pop_back`]: Self::pop_back
1487 ///
1488 /// [token]: Node::Token
1489 /// [node]: Node
1490 /// [arena]: Arena
1491 /// [parent]: Node::parent
1492 /// [first child]: Self::first
1493 /// [last child]: Self::last
1494 fn detach(token: Self::Token, arena: &mut Arena<Self::Base>, index: usize) -> <Self::Base as Node>::Token
1495 where
1496 Self: Sized,
1497 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1498 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1499
1500 /// Removes the child at the given `index`.
1501 ///
1502 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to avoid
1503 /// having multiple mutable references into the [arena] at a time.
1504 ///
1505 /// # Panics
1506 /// This method will panic if the given `index` is out of bounds.
1507 ///
1508 /// # See also
1509 /// The [first child] or [last child] may be removed with [`pop_front`] and [`pop_back`]
1510 /// respectively.
1511 ///
1512 /// If you don't want to remove a child from the [arena], but merely make it a [root node] or
1513 /// move it to another [parent], see [`detach`], [`detach_front`], or [`detach_back`].
1514 ///
1515 /// [`pop_front`]: Self::pop_front
1516 /// [`pop_back`]: Self::pop_back
1517 ///
1518 /// [`detach`]: Self::detach
1519 /// [`detach_front`]: Self::detach_front
1520 /// [`detach_back`]: Self::detach_back
1521 ///
1522 /// [token]: Self::Token
1523 /// [arena]: Arena
1524 /// [root node]: Self::root
1525 /// [first child]: Self::first
1526 /// [last child]: Self::last
1527 /// [parent]: Node::parent
1528 fn remove(
1529 token: Self::Token,
1530 arena: &mut Arena<Self::Base>,
1531 index: usize,
1532 ) -> <Self::Base as BaseNode>::Representation
1533 where
1534 Self: Sized,
1535 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1536 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1537
1538 /// Inserts the given `new` [token]'s [node] at the given `index`.
1539 ///
1540 /// This function takes its [token] as a parameter instead of `&mut self` as a receiver to avoid
1541 /// having multiple mutable references into the arena at a time.
1542 ///
1543 /// # Panics
1544 /// This method will panic if:
1545 /// - the given `index` is greater than the [`len()`]; or
1546 /// - the given `new` [token] refers to either:
1547 /// - this branch node's [root]; or
1548 /// - a [node] that already has a [parent].
1549 ///
1550 /// # See also
1551 /// A child can also be pushed to the beginning or end of this branch node's [children] with
1552 /// [`push_front`] and [`push_back`] respectively.
1553 ///
1554 /// [children]: Self::children
1555 /// [`push_front`]: Self::push_front
1556 /// [`push_back`]: Self::push_back
1557 ///
1558 /// [node]: BaseNode
1559 /// [token]: Self::Token
1560 /// [root]: Self::root
1561 /// [parent]: Node::parent
1562 ///
1563 /// [`len()`]: Self::len
1564 fn insert(token: Self::Token, arena: &mut Arena<Self::Base>, index: usize, new: <Self::Base as Node>::Token)
1565 where
1566 Self: Sized,
1567 for<'base> &'base mut Self: TryFrom<&'base mut Self::Base>,
1568 for<'base> <&'base mut Self as TryFrom<&'base mut Self::Base>>::Error: Debug;
1569}
1570
1571/// An arena in which nodes are allocated.
1572///
1573/// # Examples
1574/// TODO
1575#[derive(Debug, Default)]
1576pub struct Arena<N: Node>(pub(crate) generational_arena::Arena<N>);
1577
1578impl<N: Node> Arena<N> {
1579 /// Creates a new, empty arena.
1580 pub fn new() -> Self {
1581 Self(generational_arena::Arena::new())
1582 }
1583
1584 /// Creates a new, empty arena with the given initial `capacity`.
1585 ///
1586 /// A number of nodes equal to the `capacity` may be allocated in the arena without allocating
1587 /// further memory for the arena itself.
1588 pub fn with_capacity(capacity: usize) -> Self {
1589 Self(generational_arena::Arena::with_capacity(capacity))
1590 }
1591}
1592
1593#[cfg(feature = "serde")]
1594impl<N: Node + Serialize> Serialize for Arena<N> {
1595 #[inline(always)]
1596 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1597 where
1598 S: Serializer,
1599 {
1600 self.0.serialize(serializer)
1601 }
1602}
1603
1604#[cfg(feature = "serde")]
1605impl<'de, N: Node + Deserialize<'de>> Deserialize<'de> for Arena<N> {
1606 #[inline(always)]
1607 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1608 where
1609 D: Deserializer<'de>,
1610 {
1611 Ok(Self(generational_arena::Arena::deserialize(deserializer)?))
1612 }
1613}