generational_arena_tree/
unified.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,
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	Arena,
20	BaseNode,
21	BranchNode,
22	LinkedNode,
23	Node,
24	NodeToken,
25	Token,
26};
27
28#[cfg(feature = "deque")]
29#[doc(cfg(feature = "deque"))]
30mod deque;
31
32#[cfg(feature = "deque")]
33pub use deque::*;
34
35#[cfg_attrs]
36/// A [node] that is _not_ split into separate [branch] and leaf [nodes].
37#[configure(
38	feature = "deque",
39	/// This is the non-[deque] version, where [children] are represented as a [linked] list. In
40	/// this version, a [node]'s [previous sibling][prev][(s)][preceding] and
41	/// [next sibling][next][(s)][following] are available, but [nodes] cannot be
42	/// [directly indexed], nor can [children] be [detached], [removed], or [inserted] by index.
43	///
44	/// [deque]: crate::BranchNodeDeque
45	/// [linked]: crate::LinkedNode
46	/// [children]: UnifiedNode::children
47	///
48	/// [directly indexed]: core::ops::Index
49	/// [detached]: crate::BranchNodeDeque::detach
50	/// [removed]: crate::BranchNodeDeque::remove
51	/// [inserted]: crate::BranchNodeDeque::insert
52	///
53	/// [prev]: UnifiedNode::prev
54	/// [preceding]: UnifiedNode::preceding_siblings
55	/// [next]: UnifiedNode::next
56	/// [following]: UnifiedNode::following_siblings
57	///
58)]
59/// `Data` represents the [custom data] associated with the the node.
60#[configure(
61	any(feature = "split", feature = "deque"),
62	/// # See also
63	#[configure(
64		feature = "deque",
65		/// For the [deque] version, see [`UnifiedNodeDeque`].
66		///
67		/// [deque]: crate::BranchNodeDeque
68		///
69	)]
70	#[configure(
71		feature = "split",
72		/// For a [node] that _is_ split into separate [branch] and leaf [nodes], see
73		#[configure(
74			not(feature = "deque"),
75			/// [`SplitNode`].
76			///
77		)]
78		#[configure(
79			feature = "deque",
80			/// [`SplitNode`] and [`SplitNodeDeque`].
81			///
82			/// [`SplitNodeDeque`]: crate::split::SplitNodeDeque
83		)]
84		/// [`SplitNode`]: crate::split::SplitNode
85		///
86	)]
87)]
88/// [node]: Node
89/// [nodes]: Node
90/// [branch]: BranchNode
91/// [custom data]: UnifiedNode::Data
92#[derive(Debug)]
93#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
94pub struct UnifiedNode<Data: Debug> {
95	token: Token<Self>,
96
97	parent: Option<Token<Self>>,
98
99	prev: Option<Token<Self>>,
100	next: Option<Token<Self>>,
101
102	first_child: Option<Token<Self>>,
103	last_child: Option<Token<Self>>,
104
105	data: Data,
106}
107
108/// The [representation] of a [unified node] after it has been removed from the [arena].
109///
110/// [representation]: BaseNode::Representation
111/// [unified node]: UnifiedNode
112/// [arena]: Arena
113#[derive(Debug, PartialEq, Eq, Hash, Clone)]
114#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
115pub struct UnifiedNodeRepresentation<Data: Debug> {
116	/// The [node]'s [children].
117	///
118	/// [node]: UnifiedNode
119	/// [children]: UnifiedNode::children
120	pub children: VecDeque<UnifiedNodeRepresentation<Data>>,
121	/// The [data] associated with the [node].
122	///
123	/// [node]: UnifiedNode
124	/// [data]: UnifiedNode::Data
125	pub data: Data,
126}
127
128impl<Data: Debug> PartialEq for UnifiedNode<Data> {
129	#[inline(always)]
130	fn eq(&self, other: &Self) -> bool {
131		self.token == other.token
132	}
133}
134
135impl<Data: Debug> Eq for UnifiedNode<Data> {}
136
137impl<Data: Debug> Hash for UnifiedNode<Data> {
138	#[inline(always)]
139	fn hash<H: Hasher>(&self, state: &mut H) {
140		self.token.hash(state);
141	}
142}
143
144impl<Data: Debug> Sealed for UnifiedNode<Data> {}
145
146impl<Data: Debug> Node for UnifiedNode<Data> {
147	type Base = Self;
148	type Token = Token<Self>;
149
150	type Data = Data;
151	type DataRef<'data> = &'data Data
152	where
153		Self: 'data;
154	type DataRefMut<'data> = &'data mut Data
155	where
156		Self: 'data;
157
158	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Self::Token {
159		Token::new(arena.0.insert_with(|idx| Self {
160			token: Token::new(idx),
161
162			parent: None,
163
164			prev: None,
165			next: None,
166
167			first_child: None,
168			last_child: None,
169
170			data,
171		}))
172	}
173
174	#[inline(always)]
175	fn token(&self) -> Self::Token {
176		self.token
177	}
178
179	#[inline(always)]
180	fn parent(&self) -> Option<Token<Self>> {
181		self.parent
182	}
183
184	#[inline(always)]
185	fn data(&self) -> &Self::Data {
186		&self.data
187	}
188
189	#[inline(always)]
190	fn data_mut(&mut self) -> &mut Self::Data {
191		&mut self.data
192	}
193}
194
195impl<Data: Debug> BaseNode for UnifiedNode<Data> {
196	type Representation = UnifiedNodeRepresentation<Data>;
197
198	type Branch = Self;
199	type Leaf = Self;
200
201	fn into_representation(self, arena: &mut Arena<Self>) -> Self::Representation {
202		UnifiedNodeRepresentation {
203			children: remove_children_linked(&self, arena),
204			data: self.data,
205		}
206	}
207}
208
209impl<Data: Debug> LinkedNode for UnifiedNode<Data> {
210	#[inline(always)]
211	fn prev(&self) -> Option<Token<Self>> {
212		self.prev
213	}
214
215	#[inline(always)]
216	fn next(&self) -> Option<Token<Self>> {
217		self.next
218	}
219}
220
221impl<Data: Debug> BranchNode for UnifiedNode<Data> {
222	type ChildrenIter<'branch> = iter::ChildrenLinked<'branch, Self> where Self: 'branch;
223
224	#[inline(always)]
225	fn first(&self) -> Option<Token<Self>> {
226		self.first_child
227	}
228
229	#[inline(always)]
230	fn last(&self) -> Option<Token<Self>> {
231		self.last_child
232	}
233
234	#[inline(always)]
235	fn children<'branch>(&'branch self, arena: &'branch Arena<Self>) -> Self::ChildrenIter<'branch> {
236		iter::ChildrenLinked::new(arena, self.first_child, self.last_child)
237	}
238
239	#[inline(always)]
240	fn is_empty(&self) -> bool {
241		// Assert that if either the first child or the last child are `None`, both are, because the
242		// if there are 1 or more children, there should always be both a first and last child.
243		debug_assert!(!(self.first_child.is_none() ^ self.last_child.is_none()));
244
245		self.first_child.is_none()
246	}
247
248	fn detach_front(token: Self::Token, arena: &mut Arena<Self>) -> Option<Token<Self>> {
249		let this = &mut arena.0[token.idx()];
250
251		match (this.first_child, this.last_child) {
252			// Just a single child.
253			(Some(first), Some(last)) if first == last => {
254				(this.first_child, this.last_child) = (None, None);
255
256				let node = &mut arena.0[first.idx()];
257
258				// Detach the node's parent and siblings.
259				node.parent = None;
260
261				node.prev = None;
262				node.next = None;
263
264				Some(first)
265			},
266
267			// Multiple children.
268			(Some(first), Some(_)) => {
269				let next = first.next(arena).expect("There are multiple children");
270
271				// Move the `next` node to the front.
272				arena.0[token.idx()].first_child = Some(next);
273				arena.0[next.idx()].prev = None;
274
275				let node = &mut arena.0[first.idx()];
276
277				// Detach the node's parent and siblings.
278				node.parent = None;
279
280				node.prev = None;
281				node.next = None;
282
283				Some(first)
284			},
285
286			// No children.
287			(..) => {
288				// If either the first child or last child is `None`, both must be `None`.
289				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
290
291				None
292			},
293		}
294	}
295
296	fn detach_back(token: Self::Token, arena: &mut Arena<Self>) -> Option<Token<Self>> {
297		let this = &mut arena.0[token.idx()];
298
299		match (this.first_child, this.last_child) {
300			// Just a single child.
301			(Some(first), Some(last)) if first == last => {
302				(this.first_child, this.last_child) = (None, None);
303
304				let node = &mut arena.0[last.idx()];
305
306				// Detach the node's parent and siblings.
307				node.parent = None;
308
309				node.prev = None;
310				node.next = None;
311
312				Some(last)
313			},
314
315			// Multiple children.
316			(Some(_), Some(last)) => {
317				let prev = last.prev(arena).expect("There are multiple children");
318
319				// Move the `prev` node to the back.
320				arena.0[token.idx()].last_child = Some(prev);
321				arena.0[prev.idx()].next = None;
322
323				let node = &mut arena.0[last.idx()];
324
325				// Detach the node's parent and siblings.
326				node.parent = None;
327
328				node.prev = None;
329				node.next = None;
330
331				Some(last)
332			},
333
334			// No children.
335			(..) => {
336				// If either the first child or last child is `None`, both must be `None`.
337				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
338
339				None
340			},
341		}
342	}
343
344	fn pop_front(token: Self::Token, arena: &mut Arena<Self>) -> Option<UnifiedNodeRepresentation<Data>> {
345		let this = &mut arena.0[token.idx()];
346
347		match (this.first_child, this.last_child) {
348			// Just a single child.
349			(Some(first), Some(last)) if first == last => {
350				(this.first_child, this.last_child) = (None, None);
351
352				Some(
353					arena
354						.0
355						.remove(first.idx())
356						.expect("tried to remove child but there was no such node in the `arena`")
357						.into_representation(arena),
358				)
359			},
360
361			// Multiple children.
362			(Some(first), Some(_)) => {
363				let next = first.next(arena).expect("There are multiple children.");
364
365				// Move the `next` node to the front.
366				arena.0[token.idx()].first_child = Some(next);
367				arena.0[next.idx()].prev = None;
368
369				Some(
370					arena
371						.0
372						.remove(first.idx())
373						.expect("tried to remove child but there was no such node in the `arena`")
374						.into_representation(arena),
375				)
376			},
377
378			// No children.
379			(..) => {
380				// If either the first child or last child is `None`, both must be `None`.
381				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
382
383				None
384			},
385		}
386	}
387
388	fn pop_back(token: Self::Token, arena: &mut Arena<Self>) -> Option<UnifiedNodeRepresentation<Data>> {
389		let this = &mut arena.0[token.idx()];
390
391		match (this.first_child, this.last_child) {
392			// Just a single child.
393			(Some(first), Some(last)) if first == last => {
394				(this.first_child, this.last_child) = (None, None);
395
396				Some(
397					arena
398						.0
399						.remove(last.idx())
400						.expect("tried to remove child but there was no such node in the `arena`")
401						.into_representation(arena),
402				)
403			},
404
405			// Multiple children.
406			(Some(_), Some(last)) => {
407				let prev = last.prev(arena).expect("There are multiple children.");
408
409				// Move the `next` node to the front.
410				arena.0[token.idx()].last_child = Some(prev);
411				arena.0[prev.idx()].next = None;
412
413				Some(
414					arena
415						.0
416						.remove(last.idx())
417						.expect("tried to remove child but there was no such node in the `arena`")
418						.into_representation(arena),
419				)
420			},
421
422			// No children.
423			(..) => {
424				// If either the first child or last child is `None`, both must be `None`.
425				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
426
427				None
428			},
429		}
430	}
431
432	fn push_front(token: Self::Token, arena: &mut Arena<Self>, new: Token<Self>) {
433		// We're not pushing our own root...
434		assert_ne!(
435			arena.0[token.idx()].root(arena),
436			new,
437			"tried to push this branch's own root as a child"
438		);
439		// And we're not pushing a child that already has a parent...
440		assert!(
441			arena.0[new.idx()].parent.is_none(),
442			"tried to push a child that already has a parent"
443		);
444
445		// Set the child's parent.
446		arena.0[new.idx()].parent = Some(token);
447
448		let this = &mut arena.0[token.idx()];
449
450		// Push the child's token.
451		match (this.first_child, this.last_child) {
452			// One or more existing children.
453			(Some(first), Some(_)) => {
454				// Move the existing first child forward.
455				this.first_child = Some(new);
456				arena.0[first.idx()].prev = Some(new);
457			},
458
459			// No existing children.
460			(..) => {
461				// If either the first child or last child is `None`, both must be `None`.
462				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
463
464				// Update the first and last child.
465				(this.first_child, this.last_child) = (Some(new), Some(new));
466			},
467		}
468	}
469
470	fn push_back(token: Self::Token, arena: &mut Arena<Self>, new: Token<Self>) {
471		// We're not pushing our own root...
472		assert_ne!(
473			arena.0[token.idx()].root(arena),
474			new,
475			"tried to push this branch's own root as a child"
476		);
477		// And we're not pushing a child that already has a parent...
478		assert!(
479			arena.0[new.idx()].parent.is_none(),
480			"tried to push a child that already has a parent"
481		);
482
483		// Set the child's parent.
484		arena.0[new.idx()].parent = Some(token);
485
486		let this = &mut arena.0[token.idx()];
487
488		// Push the child's token.
489		match (this.first_child, this.last_child) {
490			// One or more existing children.
491			(Some(_), Some(last)) => {
492				// Move the existing first child forward.
493				this.last_child = Some(new);
494				arena.0[last.idx()].next = Some(new);
495			},
496
497			// No existing children.
498			(..) => {
499				// If either the first child or last child is `None`, both must be `None`.
500				debug_assert!(this.first_child.is_none() && this.last_child.is_none());
501
502				// Update the first and last child.
503				(this.first_child, this.last_child) = (Some(new), Some(new));
504			},
505		}
506	}
507}