generational_arena_tree/
split.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
5use std::{
6	collections::VecDeque,
7	fmt::{Debug, Formatter},
8	hash::{Hash, Hasher},
9};
10
11use cfg_attrs::cfg_attrs;
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use crate::{
16	iter,
17	remove_children_linked,
18	sealed::{Idx, Sealed},
19	token_to_node,
20	Arena,
21	BaseNode,
22	BranchNode,
23	LinkedNode,
24	Node,
25	NodeToken,
26	Token,
27};
28
29#[cfg(feature = "deque")]
30#[doc(cfg(feature = "deque"))]
31mod deque;
32
33#[cfg(feature = "deque")]
34pub use deque::*;
35
36type BranchToken<BranchData, LeafData> = Token<Branch<BranchData, LeafData>>;
37type LeafToken<BranchData, LeafData> = Token<Leaf<BranchData, LeafData>>;
38
39#[cfg_attrs]
40/// A [node] that is split into separate [branch] and [leaf] nodes.
41#[configure(
42	feature = "deque",
43	/// This is the non-[deque] version, where [children] are represented as a [linked] list. In
44	/// this version, a [node]'s [previous sibling][prev][(s)][preceding] and
45	/// [next sibling][next][(s)][following] are available, but [branches] cannot be
46	/// [directly indexed], nor can [children] be [detached], [removed], or [inserted] by index.
47	///
48	/// [deque]: crate::BranchNodeDeque
49	/// [linked]: crate::LinkedNode
50	/// [children]: Branch::children
51	///
52	/// [directly indexed]: core::ops::Index
53	/// [detached]: crate::BranchNodeDeque::detach
54	/// [remove]: crate::BranchNodeDeque::remove
55	/// [inserted]: crate::BranchNodeDeque::insert
56	///
57	/// [prev]: SplitNode::prev
58	/// [preceding]: SplitNode::preceding_siblings
59	/// [next]: SplitNode::next
60	/// [following]: SplitNode::following_siblings
61	///
62)]
63/// `BranchData` represents the [custom data](Branch::Data) associated with [branches], while
64/// `LeafData` represents the [custom data](Leaf::Data) associated with [leaves].
65#[configure(
66	any(feature = "unified", feature = "deque"),
67	/// # See also
68	#[configure(
69		feature = "deque",
70		/// For the [deque] version, see [`SplitNodeDeque`].
71		///
72		/// [deque]: crate::BranchNodeDeque
73		///
74	)]
75	#[configure(
76		feature = "unified",
77		/// For a [node] that _isn't_ split into separate branch and leaf nodes, see
78		#[configure(
79			not(feature = "deque"),
80			/// [`UnifiedNode`].
81			///
82		)]
83		#[configure(
84			feature = "deque",
85			/// [`UnifiedNode`] and [`UnifiedNodeDeque`].
86			///
87			/// [`UnifiedNodeDeque`]: crate::unified::UnifiedNodeDeque
88		)]
89		/// [`UnifiedNode`]: crate::unified::UnifiedNode
90		///
91	)]
92)]
93/// [node]: Node
94/// [branch]: Branch
95/// [branches]: Branch
96/// [leaf]: Leaf
97/// [leaves]: Leaf
98#[derive(Debug)]
99#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
100pub enum SplitNode<BranchData: Debug, LeafData: Debug> {
101	/// A [branch] node that may have children.
102	///
103	/// [branch]: Branch
104	Branch(Branch<BranchData, LeafData>),
105	/// A [leaf] node that may not have children.
106	///
107	/// [leaf]: Leaf
108	Leaf(Leaf<BranchData, LeafData>),
109}
110
111#[cfg_attrs]
112/// The [custom data] associated with a
113#[configure(
114	not(feature = "deque"),
115	/// [`SplitNode`].
116	///
117)]
118#[configure(
119	feature = "deque",
120	/// [`SplitNode`] or [`SplitNodeDeque`].
121	///
122)]
123/// [custom data]: Node::Data
124#[derive(Debug, PartialEq, Eq, Hash, Clone)]
125#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
126pub enum SplitData<BranchData: Debug, LeafData: Debug> {
127	/// The [data] associated with a
128	#[configure(
129		not(feature = "deque"),
130		/// [`Branch`].
131		///
132	)]
133	#[configure(
134		feature = "deque",
135		/// [`Branch`] or [`BranchDeque`].
136		///
137	)]
138	/// [data]: Branch::Data
139	Branch(BranchData),
140	/// The [data] associated with a
141	#[configure(
142		not(feature = "deque"),
143		/// [`Leaf`].
144		///
145	)]
146	#[configure(
147		feaute = "deque",
148		/// [`Leaf`] or [`LeafDeque`].
149		///
150	)]
151	/// [data]: Leaf::Data
152	/// [leaf]: Leaf
153	Leaf(LeafData),
154}
155
156#[cfg_attrs]
157/// The [representation] of a [`SplitNode`]
158#[configure(
159	feature = "deque",
160	/// or [`SplitNodeDeque`]
161)]
162/// after it has been removed from the [arena].
163///
164/// [representation]: BaseNode::Representation
165/// [arena]: Arena
166#[derive(Debug, PartialEq, Eq, Hash, Clone)]
167#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
168pub enum SplitNodeRepresentation<BranchData: Debug, LeafData: Debug> {
169	/// The [representation] of a
170	#[configure(
171		not(feature = "deque"),
172		/// [`Branch`].
173		///
174	)]
175	#[configure(
176		feature = "deque",
177		/// [`Branch`] or [`BranchDeque`].
178		///
179	)]
180	/// [representation]: BaseNode::Representation
181	Branch {
182		/// The branch node's [children].
183		///
184		/// [children]: Branch::children
185		children: VecDeque<SplitNodeRepresentation<BranchData, LeafData>>,
186		/// The [data] associated with the branch node.
187		///
188		/// [data]: Branch::Data
189		data: BranchData,
190	},
191
192	/// The [representation] of a
193	#[configure(
194		not(feature = "deque"),
195		/// [`Leaf`].
196		///
197	)]
198	#[configure(
199		feature = "deque",
200		/// [`Leaf`] or [`LeafDeque`].
201		///
202	)]
203	/// [representation]: BaseNode::Representation
204	Leaf {
205		/// The [data] associated with the leaf node.
206		///
207		/// [data]: Leaf::Data
208		data: LeafData,
209	},
210}
211
212/// The [token] type referring to a [`SplitNode`].
213///
214/// [token]: NodeToken
215#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
216pub enum SplitToken<BranchData: Debug, LeafData: Debug> {
217	/// A [branch] node's [token].
218	///
219	/// [branch]: Branch
220	/// [token]: NodeToken
221	Branch(BranchToken<BranchData, LeafData>),
222	/// A [leaf] node's [token].
223	///
224	/// [leaf]: Leaf
225	/// [token]: NodeToken
226	Leaf(LeafToken<BranchData, LeafData>),
227}
228
229/// The [node] representing [branches] in a [split node] tree.
230///
231/// [Branches] are [nodes] which may have [children], as opposed to [leaves], which may not have
232/// [children].
233///
234/// `BranchData` represents the [custom data] associated with branch nodes.
235///
236/// [custom data]: Branch::Data
237///
238/// [node]: Node
239/// [nodes]: Node
240/// [Branches]: BranchNode
241/// [branches]: BranchNode
242/// [leaves]: Leaf
243/// [children]: Branch::children
244/// [split node]: SplitNode
245#[derive(Debug)]
246#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
247pub struct Branch<BranchData: Debug, LeafData: Debug> {
248	token: Token<Self>,
249
250	parent: Option<BranchToken<BranchData, LeafData>>,
251
252	prev: Option<SplitToken<BranchData, LeafData>>,
253	next: Option<SplitToken<BranchData, LeafData>>,
254
255	first_child: Option<SplitToken<BranchData, LeafData>>,
256	last_child: Option<SplitToken<BranchData, LeafData>>,
257
258	data: BranchData,
259}
260
261/// The [node] representing leaves in a [split node] tree.
262///
263/// Leaves are [nodes] which may not have [children], as opposed to [branches], which may have
264/// [children].
265///
266/// `LeafData` represents the [custom data] associated with leaf nodes.
267///
268/// [custom data]: Leaf::Data
269///
270/// [node]: Node
271/// [nodes]: Node
272/// [children]: Branch::children
273/// [branches]: Branch
274/// [split node]: SplitNode
275#[derive(Debug)]
276#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
277pub struct Leaf<BranchData: Debug, LeafData: Debug> {
278	token: Token<Self>,
279
280	parent: Option<BranchToken<BranchData, LeafData>>,
281
282	prev: Option<SplitToken<BranchData, LeafData>>,
283	next: Option<SplitToken<BranchData, LeafData>>,
284
285	data: LeafData,
286}
287
288impl<BranchData, LeafData> Debug for SplitToken<BranchData, LeafData>
289where
290	BranchData: Debug,
291	LeafData: Debug,
292{
293	#[inline(always)]
294	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
295		match self {
296			Self::Branch(branch) => write!(f, "BranchToken({:?})", branch.idx()),
297			Self::Leaf(leaf) => write!(f, "LeafToken({:?})", leaf.idx()),
298		}
299	}
300}
301
302impl<BranchData, LeafData, I: Idx> PartialEq<I> for SplitToken<BranchData, LeafData>
303where
304	BranchData: Debug,
305	LeafData: Debug,
306{
307	#[inline(always)]
308	fn eq(&self, other: &I) -> bool {
309		self.idx() == other.idx()
310	}
311}
312
313impl<BranchData, LeafData> Eq for SplitToken<BranchData, LeafData>
314where
315	BranchData: Debug,
316	LeafData: Debug,
317{
318}
319
320impl<BranchData, LeafData> Hash for SplitToken<BranchData, LeafData>
321where
322	BranchData: Debug,
323	LeafData: Debug,
324{
325	#[inline(always)]
326	fn hash<H: Hasher>(&self, state: &mut H) {
327		match self {
328			Self::Branch(branch) => branch.hash(state),
329			Self::Leaf(leaf) => leaf.hash(state),
330		}
331	}
332}
333
334impl<BranchData, LeafData> Clone for SplitToken<BranchData, LeafData>
335where
336	BranchData: Debug,
337	LeafData: Debug,
338{
339	#[inline(always)]
340	fn clone(&self) -> Self {
341		*self
342	}
343}
344
345impl<BranchData, LeafData> Copy for SplitToken<BranchData, LeafData>
346where
347	BranchData: Debug,
348	LeafData: Debug,
349{
350}
351
352impl<BranchData, LeafData> SplitToken<BranchData, LeafData>
353where
354	BranchData: Debug,
355	LeafData: Debug,
356{
357	/// Creates a new `SplitToken` for a [branch] from the given `token`.
358	///
359	/// [branch]: Branch
360	#[inline(always)]
361	pub const fn new_branch(token: BranchToken<BranchData, LeafData>) -> Self {
362		Self::Branch(token)
363	}
364
365	/// Creates a new `SplitToken` for a [leaf] from the given `token`.
366	///
367	/// [leaf]: Leaf
368	#[inline(always)]
369	pub const fn new_leaf(token: LeafToken<BranchData, LeafData>) -> Self {
370		Self::Leaf(token)
371	}
372}
373
374impl<BranchData, LeafData> Idx for SplitToken<BranchData, LeafData>
375where
376	BranchData: Debug,
377	LeafData: Debug,
378{
379	#[inline(always)]
380	fn idx(&self) -> generational_arena::Index {
381		match self {
382			Self::Branch(branch) => branch.idx(),
383			Self::Leaf(leaf) => leaf.idx(),
384		}
385	}
386}
387
388impl<BranchData, LeafData> NodeToken<SplitNode<BranchData, LeafData>> for SplitToken<BranchData, LeafData>
389where
390	BranchData: Debug,
391	LeafData: Debug,
392{
393}
394
395impl<BranchData, LeafData, Other: Node> PartialEq<Other> for Branch<BranchData, LeafData>
396where
397	BranchData: Debug,
398	LeafData: Debug,
399	<Self as Node>::Token: PartialEq<Other::Token>,
400{
401	#[inline(always)]
402	fn eq(&self, other: &Other) -> bool {
403		self.token == other.token()
404	}
405}
406
407impl<BranchData, LeafData> Eq for Branch<BranchData, LeafData>
408where
409	BranchData: Debug,
410	LeafData: Debug,
411{
412}
413
414impl<BranchData, LeafData> Hash for Branch<BranchData, LeafData>
415where
416	BranchData: Debug,
417	LeafData: Debug,
418{
419	#[inline(always)]
420	fn hash<H: Hasher>(&self, state: &mut H) {
421		self.token.hash(state);
422	}
423}
424
425impl<BranchData, LeafData, Other: Node> PartialEq<Other> for Leaf<BranchData, LeafData>
426where
427	BranchData: Debug,
428	LeafData: Debug,
429	<Self as Node>::Token: PartialEq<Other::Token>,
430{
431	#[inline(always)]
432	fn eq(&self, other: &Other) -> bool {
433		self.token == other.token()
434	}
435}
436
437impl<BranchData, LeafData> Eq for Leaf<BranchData, LeafData>
438where
439	BranchData: Debug,
440	LeafData: Debug,
441{
442}
443
444impl<BranchData, LeafData> Hash for Leaf<BranchData, LeafData>
445where
446	BranchData: Debug,
447	LeafData: Debug,
448{
449	#[inline(always)]
450	fn hash<H: Hasher>(&self, state: &mut H) {
451		self.token.hash(state);
452	}
453}
454
455impl<'node, BranchData, LeafData> TryFrom<&'node SplitNode<BranchData, LeafData>>
456	for &'node Branch<BranchData, LeafData>
457where
458	BranchData: Debug,
459	LeafData: Debug,
460{
461	type Error = &'node SplitNode<BranchData, LeafData>;
462
463	#[inline(always)]
464	fn try_from(node: &'node SplitNode<BranchData, LeafData>) -> Result<Self, Self::Error> {
465		match node {
466			SplitNode::Branch(branch) => Ok(branch),
467			SplitNode::Leaf(_) => Err(node),
468		}
469	}
470}
471
472impl<'node, BranchData, LeafData> TryFrom<&'node mut SplitNode<BranchData, LeafData>>
473	for &'node mut Branch<BranchData, LeafData>
474where
475	BranchData: Debug,
476	LeafData: Debug,
477{
478	type Error = &'node mut SplitNode<BranchData, LeafData>;
479
480	#[inline(always)]
481	fn try_from(node: &'node mut SplitNode<BranchData, LeafData>) -> Result<Self, Self::Error> {
482		match node {
483			SplitNode::Branch(branch) => Ok(branch),
484			SplitNode::Leaf(_) => Err(node),
485		}
486	}
487}
488
489impl<'node, BranchData, LeafData> TryFrom<&'node SplitNode<BranchData, LeafData>> for &'node Leaf<BranchData, LeafData>
490where
491	BranchData: Debug,
492	LeafData: Debug,
493{
494	type Error = &'node SplitNode<BranchData, LeafData>;
495
496	#[inline(always)]
497	fn try_from(node: &'node SplitNode<BranchData, LeafData>) -> Result<Self, Self::Error> {
498		match node {
499			SplitNode::Branch(_) => Err(node),
500			SplitNode::Leaf(leaf) => Ok(leaf),
501		}
502	}
503}
504
505impl<'node, BranchData, LeafData> TryFrom<&'node mut SplitNode<BranchData, LeafData>>
506	for &'node mut Leaf<BranchData, LeafData>
507where
508	BranchData: Debug,
509	LeafData: Debug,
510{
511	type Error = &'node mut SplitNode<BranchData, LeafData>;
512
513	#[inline(always)]
514	fn try_from(node: &'node mut SplitNode<BranchData, LeafData>) -> Result<Self, Self::Error> {
515		match node {
516			SplitNode::Branch(_) => Err(node),
517			SplitNode::Leaf(leaf) => Ok(leaf),
518		}
519	}
520}
521
522impl<BranchData, LeafData> SplitNode<BranchData, LeafData>
523where
524	BranchData: Debug,
525	LeafData: Debug,
526{
527	#[inline(always)]
528	fn set_parent(&mut self, parent: Option<BranchToken<BranchData, LeafData>>) {
529		match self {
530			Self::Branch(branch) => branch.parent = parent,
531			Self::Leaf(leaf) => leaf.parent = parent,
532		}
533	}
534
535	#[inline(always)]
536	fn set_prev(&mut self, prev: Option<SplitToken<BranchData, LeafData>>) {
537		match self {
538			Self::Branch(branch) => branch.prev = prev,
539			Self::Leaf(leaf) => leaf.prev = prev,
540		}
541	}
542
543	#[inline(always)]
544	fn set_next(&mut self, next: Option<SplitToken<BranchData, LeafData>>) {
545		match self {
546			Self::Branch(branch) => branch.next = next,
547			Self::Leaf(leaf) => leaf.next = next,
548		}
549	}
550}
551
552impl<BranchData, LeafData> Sealed for SplitNode<BranchData, LeafData>
553where
554	BranchData: Debug,
555	LeafData: Debug,
556{
557}
558
559impl<BranchData, LeafData> Node for SplitNode<BranchData, LeafData>
560where
561	BranchData: Debug,
562	LeafData: Debug,
563{
564	type Base = Self;
565	type Token = SplitToken<BranchData, LeafData>;
566
567	type Data = SplitData<BranchData, LeafData>;
568	type DataRef<'data> = SplitData<&'data BranchData, &'data LeafData>
569	where
570		Self: 'data;
571	type DataRefMut<'data> = SplitData<&'data mut BranchData, &'data mut LeafData>
572	where
573		Self: 'data;
574
575	#[inline(always)]
576	fn new(arena: &mut Arena<Self>, data: Self::Data) -> Self::Token {
577		match data {
578			SplitData::Branch(data) => SplitToken::Branch(Branch::new(arena, data)),
579			SplitData::Leaf(data) => SplitToken::Leaf(Leaf::new(arena, data)),
580		}
581	}
582
583	#[inline(always)]
584	fn token(&self) -> Self::Token {
585		match self {
586			Self::Branch(branch) => SplitToken::Branch(branch.token()),
587			Self::Leaf(leaf) => SplitToken::Leaf(leaf.token()),
588		}
589	}
590
591	#[inline(always)]
592	fn parent(&self) -> Option<Token<<Self as BaseNode>::Branch>> {
593		match self {
594			Self::Branch(branch) => branch.parent(),
595			Self::Leaf(leaf) => leaf.parent(),
596		}
597	}
598
599	#[inline(always)]
600	fn data(&self) -> Self::DataRef<'_> {
601		match self {
602			Self::Branch(branch) => SplitData::Branch(branch.data()),
603			Self::Leaf(leaf) => SplitData::Leaf(leaf.data()),
604		}
605	}
606
607	#[inline(always)]
608	fn data_mut(&mut self) -> Self::DataRefMut<'_> {
609		match self {
610			Self::Branch(branch) => SplitData::Branch(branch.data_mut()),
611			Self::Leaf(leaf) => SplitData::Leaf(leaf.data_mut()),
612		}
613	}
614}
615
616impl<BranchData, LeafData> BaseNode for SplitNode<BranchData, LeafData>
617where
618	BranchData: Debug,
619	LeafData: Debug,
620{
621	type Representation = SplitNodeRepresentation<BranchData, LeafData>;
622
623	type Branch = Branch<BranchData, LeafData>;
624	type Leaf = Leaf<BranchData, LeafData>;
625
626	fn into_representation(self, arena: &mut Arena<Self::Base>) -> Self::Representation {
627		match self {
628			// Branch.
629			Self::Branch(branch) => SplitNodeRepresentation::Branch {
630				children: remove_children_linked(&branch, arena),
631				data: branch.data,
632			},
633
634			// Leaf.
635			Self::Leaf(leaf) => SplitNodeRepresentation::Leaf { data: leaf.data },
636		}
637	}
638}
639
640impl<BranchData, LeafData> LinkedNode for SplitNode<BranchData, LeafData>
641where
642	BranchData: Debug,
643	LeafData: Debug,
644{
645	#[inline(always)]
646	fn prev(&self) -> Option<Self::Token> {
647		match self {
648			Self::Branch(branch) => branch.prev(),
649			Self::Leaf(leaf) => leaf.prev(),
650		}
651	}
652
653	#[inline(always)]
654	fn next(&self) -> Option<Self::Token> {
655		match self {
656			Self::Branch(branch) => branch.next(),
657			Self::Leaf(leaf) => leaf.next(),
658		}
659	}
660}
661
662impl<BranchData, LeafData> Sealed for Branch<BranchData, LeafData>
663where
664	BranchData: Debug,
665	LeafData: Debug,
666{
667}
668
669impl<BranchData, LeafData> Node for Branch<BranchData, LeafData>
670where
671	BranchData: Debug,
672	LeafData: Debug,
673{
674	type Base = SplitNode<BranchData, LeafData>;
675	type Token = Token<Self>;
676
677	type Data = BranchData;
678	type DataRef<'data> = &'data BranchData
679	where
680		Self: 'data;
681	type DataRefMut<'data> = &'data mut BranchData
682	where
683		Self: 'data;
684
685	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Token<Self> {
686		Token::new(arena.0.insert_with(|idx| {
687			SplitNode::Branch(Self {
688				token: Token::new(idx),
689
690				parent: None,
691
692				prev: None,
693				next: None,
694
695				first_child: None,
696				last_child: None,
697
698				data,
699			})
700		}))
701	}
702
703	#[inline(always)]
704	fn token(&self) -> Self::Token {
705		self.token
706	}
707
708	#[inline(always)]
709	fn parent(&self) -> Option<Token<Self>> {
710		self.parent
711	}
712
713	#[inline(always)]
714	fn data(&self) -> &BranchData {
715		&self.data
716	}
717
718	#[inline(always)]
719	fn data_mut(&mut self) -> &mut BranchData {
720		&mut self.data
721	}
722}
723
724impl<BranchData, LeafData> LinkedNode for Branch<BranchData, LeafData>
725where
726	BranchData: Debug,
727	LeafData: Debug,
728{
729	#[inline(always)]
730	fn prev(&self) -> Option<<Self::Base as Node>::Token> {
731		self.prev
732	}
733
734	#[inline(always)]
735	fn next(&self) -> Option<<Self::Base as Node>::Token> {
736		self.next
737	}
738}
739
740impl<BranchData, LeafData> BranchNode for Branch<BranchData, LeafData>
741where
742	BranchData: Debug,
743	LeafData: Debug,
744{
745	type ChildrenIter<'branch> = iter::ChildrenLinked<'branch, Self>
746	where
747		Self: 'branch;
748
749	#[inline(always)]
750	fn first(&self) -> Option<<Self::Base as Node>::Token> {
751		self.first_child
752	}
753
754	#[inline(always)]
755	fn last(&self) -> Option<<Self::Base as Node>::Token> {
756		self.last_child
757	}
758
759	#[inline(always)]
760	fn children<'branch>(&'branch self, arena: &'branch Arena<Self::Base>) -> Self::ChildrenIter<'branch> {
761		iter::ChildrenLinked::new(arena, self.first_child, self.last_child)
762	}
763
764	#[inline(always)]
765	fn is_empty(&self) -> bool {
766		// Assert that if either the first child or the last child are `None`, both are, because the
767		// if there are 1 or more children, there should always be both a first and last child.
768		debug_assert!(!(self.first_child.is_none() ^ self.last_child.is_none()));
769
770		self.first_child.is_none()
771	}
772
773	fn detach_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token> {
774		let this = token_to_node!(ref mut, Self: token, arena);
775
776		match (this.first_child, this.last_child) {
777			// Just a single child.
778			(Some(first), Some(last)) if first == last => {
779				(this.first_child, this.last_child) = (None, None);
780
781				let node = &mut arena.0[first.idx()];
782
783				// Detach the node's parent and siblings.
784				node.set_parent(None);
785
786				node.set_prev(None);
787				node.set_next(None);
788
789				Some(first)
790			},
791
792			// Multiple children.
793			(Some(first), Some(_)) => {
794				let next = first.next(arena).expect("There are multiple children.");
795
796				let this = token_to_node!(ref mut, Self: token, arena);
797
798				// Move the `next` node to the front.
799				this.first_child = Some(next);
800				arena.0[next.idx()].set_prev(None);
801
802				let node = &mut arena.0[first.idx()];
803
804				// Detach the node's parent and siblings.
805				node.set_parent(None);
806
807				node.set_prev(None);
808				node.set_next(None);
809
810				Some(first)
811			},
812
813			// No children.
814			(..) => {
815				// If either the first child or last child is `None`, both must be `None`.
816				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
817
818				None
819			},
820		}
821	}
822
823	fn detach_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token> {
824		let this = token_to_node!(ref mut, Self: token, arena);
825
826		match (this.first_child, this.last_child) {
827			// Just a single child.
828			(Some(first), Some(last)) if first == last => {
829				(this.first_child, this.last_child) = (None, None);
830
831				let node = &mut arena.0[last.idx()];
832
833				// Detach the node's parent and siblings.
834				node.set_parent(None);
835
836				node.set_prev(None);
837				node.set_next(None);
838
839				Some(last)
840			},
841
842			// Multiple children.
843			(Some(_), Some(last)) => {
844				let prev = last.prev(arena).expect("There are multiple children.");
845
846				let this = token_to_node!(ref mut, Self: token, arena);
847
848				// Move the `prev` node to the back.
849				this.last_child = Some(prev);
850				arena.0[prev.idx()].set_next(None);
851
852				let node = &mut arena.0[last.idx()];
853
854				// Detach the node's parent and siblings.
855				node.set_parent(None);
856
857				node.set_prev(None);
858				node.set_next(None);
859
860				Some(last)
861			},
862
863			// No children.
864			(..) => {
865				// If either the first child or last child is `None`, both must be `None`.
866				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
867
868				None
869			},
870		}
871	}
872
873	fn pop_front(
874		token: Self::Token,
875		arena: &mut Arena<Self::Base>,
876	) -> Option<<Self::Base as BaseNode>::Representation> {
877		let this = token_to_node!(ref mut, Self: token, arena);
878
879		match (this.first_child, this.last_child) {
880			// Just a single child.
881			(Some(first), Some(last)) if first == last => {
882				(this.first_child, this.last_child) = (None, None);
883
884				Some(
885					arena
886						.0
887						.remove(first.idx())
888						.expect("tried to remove child but there was no such node in the `arena`")
889						.into_representation(arena),
890				)
891			},
892
893			// Multiple children.
894			(Some(first), Some(_)) => {
895				let next = first.next(arena).expect("There are multiple children.");
896
897				let this = token_to_node!(ref mut, Self: token, arena);
898
899				// Move the `next` node to the front.
900				this.first_child = Some(next);
901				arena.0[next.idx()].set_prev(None);
902
903				Some(
904					arena
905						.0
906						.remove(first.idx())
907						.expect("tried to remove child but there was no such node in the `arena`")
908						.into_representation(arena),
909				)
910			},
911
912			// No children.
913			(..) => {
914				// If either the first child or last child is `None`, both must be `None`.
915				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
916
917				None
918			},
919		}
920	}
921
922	fn pop_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as BaseNode>::Representation> {
923		let this = token_to_node!(ref mut, Self: token, arena);
924
925		match (this.first_child, this.last_child) {
926			// Just a single child.
927			(Some(first), Some(last)) if first == last => {
928				(this.first_child, this.last_child) = (None, None);
929
930				Some(
931					arena
932						.0
933						.remove(first.idx())
934						.expect("tried to remove child but there was no such node in the `arena`")
935						.into_representation(arena),
936				)
937			},
938
939			// Multiple children.
940			(Some(_), Some(last)) => {
941				let prev = last.prev(arena).expect("There are multiple children.");
942
943				let this = token_to_node!(ref mut, Self: token, arena);
944
945				// Move the `prev` node to the back.
946				this.last_child = Some(prev);
947				arena.0[prev.idx()].set_next(None);
948
949				Some(
950					arena
951						.0
952						.remove(last.idx())
953						.expect("tried to remove child but there was no such node in the `arena`")
954						.into_representation(arena),
955				)
956			},
957
958			// No children.
959			(..) => {
960				// If either the first child or last child is `None`, both must be `None`.
961				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
962
963				None
964			},
965		}
966	}
967
968	fn push_front(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token) {
969		// We're not pushing our own root...
970		assert_ne!(
971			token_to_node!(ref, Self: token, arena).root(arena),
972			new,
973			"tried to push this branch's root node as a child"
974		);
975		// And we're not pushing a child that already has a parent...
976		assert!(
977			arena.0[new.idx()].parent().is_none(),
978			"tried to push a child that already has a parent"
979		);
980
981		// Set the child's parent.
982		arena.0[new.idx()].set_parent(Some(token));
983
984		let this = token_to_node!(ref mut, Self: token, arena);
985
986		match (this.first_child, this.last_child) {
987			// One or more existing children.
988			(Some(first), Some(_)) => {
989				// Move the existing first child forward.
990				this.first_child = Some(new);
991				arena.0[first.idx()].set_prev(Some(new));
992			},
993
994			// No existing children.
995			(..) => {
996				// If either the first child or last child is `None`, both must be `None`.
997				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
998
999				// Update the first and last child.
1000				(this.first_child, this.last_child) = (Some(new), Some(new));
1001			},
1002		}
1003	}
1004
1005	fn push_back(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token) {
1006		// We're not pushing our own root...
1007		assert_ne!(
1008			token_to_node!(ref, Self: token, arena).root(arena),
1009			new,
1010			"tried to push this branch's root node as a child"
1011		);
1012		// And we're not pushing a child that already has a parent...
1013		assert!(
1014			arena.0[new.idx()].parent().is_none(),
1015			"tried to push a child that already has a parent"
1016		);
1017
1018		// Set the child's parent.
1019		arena.0[new.idx()].set_parent(Some(token));
1020
1021		let this = token_to_node!(ref mut, Self: token, arena);
1022
1023		match (this.first_child, this.last_child) {
1024			// One or more existing children.
1025			(Some(_), Some(last)) => {
1026				// Move the existing last child backward.
1027				this.last_child = Some(new);
1028				arena.0[last.idx()].set_prev(Some(new));
1029			},
1030
1031			// No existing children.
1032			(..) => {
1033				// If either the first child or last child is `None`, both must be `None`.
1034				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
1035
1036				// Update the first and last child.
1037				(this.first_child, this.last_child) = (Some(new), Some(new));
1038			},
1039		}
1040	}
1041}
1042
1043impl<BranchData, LeafData> Sealed for Leaf<BranchData, LeafData>
1044where
1045	BranchData: Debug,
1046	LeafData: Debug,
1047{
1048}
1049
1050impl<BranchData, LeafData> Node for Leaf<BranchData, LeafData>
1051where
1052	BranchData: Debug,
1053	LeafData: Debug,
1054{
1055	type Base = SplitNode<BranchData, LeafData>;
1056	type Token = Token<Self>;
1057
1058	type Data = LeafData;
1059	type DataRef<'data> = &'data LeafData
1060	where
1061		Self: 'data;
1062	type DataRefMut<'data> = &'data mut LeafData
1063	where
1064		Self: 'data;
1065
1066	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Self::Token {
1067		Token::new(arena.0.insert_with(|idx| {
1068			SplitNode::Leaf(Self {
1069				token: Token::new(idx),
1070
1071				parent: None,
1072
1073				prev: None,
1074				next: None,
1075
1076				data,
1077			})
1078		}))
1079	}
1080
1081	#[inline(always)]
1082	fn token(&self) -> Self::Token {
1083		self.token
1084	}
1085
1086	#[inline(always)]
1087	fn parent(&self) -> Option<Token<<Self::Base as BaseNode>::Branch>> {
1088		self.parent
1089	}
1090
1091	#[inline(always)]
1092	fn data(&self) -> &LeafData {
1093		&self.data
1094	}
1095
1096	#[inline(always)]
1097	fn data_mut(&mut self) -> &mut LeafData {
1098		&mut self.data
1099	}
1100}
1101
1102impl<BranchData, LeafData> LinkedNode for Leaf<BranchData, LeafData>
1103where
1104	BranchData: Debug,
1105	LeafData: Debug,
1106{
1107	#[inline(always)]
1108	fn prev(&self) -> Option<<Self::Base as Node>::Token> {
1109		self.prev
1110	}
1111
1112	#[inline(always)]
1113	fn next(&self) -> Option<<Self::Base as Node>::Token> {
1114		self.next
1115	}
1116}