generational_arena_tree/unified/
deque.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::{vec_deque, VecDeque},
7	fmt::Debug,
8	hash::{Hash, Hasher},
9	iter::Copied,
10	ops::Index,
11};
12
13use cfg_attrs::cfg_attrs;
14
15use super::*;
16use crate::{
17	remove_children_deque,
18	sealed::{Idx, Sealed},
19	Arena,
20	BaseNode,
21	BranchNode,
22	BranchNodeDeque,
23	Node,
24	Token,
25};
26
27#[cfg_attrs]
28/// A [node] that is _not_ split into separate [branch] and leaf [nodes].
29///
30/// This is the [deque] version, where [children] are represented as a [`VecDeque`]. In this
31/// version, a [node]'s [previous sibling][prev][(s)][preceding] and
32/// [next sibling][next][(s)][following] are not available, but [nodes] can be [directly indexed],
33/// and [children] can be [detached], [removed], or [inserted] by index.
34///
35/// `Data` represents the [custom data] associated with the node.
36///
37/// # See also
38/// For the non-[deque] version, see [`UnifiedNode`].
39#[configure(
40	feature = "split",
41	/// For a [node] that _is_ split into separate [branch] and leaf [nodes], see [`SplitNode`]
42	/// and [`SplitNodeDeque`].
43	///
44	/// [`SplitNode`]: crate::split::SplitNode
45	/// [`SplitNodeDeque`]: crate::split::SplitNodeDeque
46	///
47)]
48/// [node]: Node
49/// [nodes]: Node
50/// [branch]: BranchNode
51/// [custom data]: UnifiedNodeDeque::Data
52///
53/// [deque]: BranchNodeDeque
54/// [children]: UnifiedNodeDeque::children
55/// [directly indexed]: UnifiedNodeDeque::index
56/// [detached]: UnifiedNodeDeque::detach
57/// [removed]: UnifiedNodeDeque::remove
58/// [inserted]: UnifiedNodeDeque::insert
59///
60/// [prev]: crate::LinkedNode::prev
61/// [preceding]: crate::LinkedNode::preceding_siblings
62/// [next]: crate::LinkedNode::next
63/// [following]: crate::LinkedNode::following_siblings
64#[derive(Debug)]
65#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
66pub struct UnifiedNodeDeque<Data: Debug> {
67	token: Token<Self>,
68
69	parent: Option<Token<Self>>,
70	children: VecDeque<Token<Self>>,
71
72	data: Data,
73}
74
75impl<Data: Debug> PartialEq for UnifiedNodeDeque<Data> {
76	#[inline(always)]
77	fn eq(&self, other: &Self) -> bool {
78		self.token == other.token
79	}
80}
81
82impl<Data: Debug> Eq for UnifiedNodeDeque<Data> {}
83
84impl<Data: Debug> Hash for UnifiedNodeDeque<Data> {
85	#[inline(always)]
86	fn hash<H: Hasher>(&self, state: &mut H) {
87		self.token.hash(state);
88	}
89}
90
91impl<Data: Debug> Sealed for UnifiedNodeDeque<Data> {}
92
93impl<Data: Debug> Node for UnifiedNodeDeque<Data> {
94	type Base = Self;
95	type Token = Token<Self>;
96
97	type Data = Data;
98	type DataRef<'data> = &'data Data
99	where
100		Self: 'data;
101	type DataRefMut<'data> = &'data mut Data
102	where
103		Self: 'data;
104
105	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Self::Token
106	where
107		Self: Sized,
108	{
109		Token::new(arena.0.insert_with(|idx| Self {
110			token: Token::new(idx),
111
112			parent: None,
113			children: VecDeque::new(),
114
115			data,
116		}))
117	}
118
119	#[inline(always)]
120	fn token(&self) -> Self::Token {
121		self.token
122	}
123
124	#[inline(always)]
125	fn parent(&self) -> Option<Token<Self>> {
126		self.parent
127	}
128
129	#[inline(always)]
130	fn data(&self) -> &Self::Data {
131		&self.data
132	}
133
134	#[inline(always)]
135	fn data_mut(&mut self) -> &mut Self::Data {
136		&mut self.data
137	}
138}
139
140impl<Data: Debug> BaseNode for UnifiedNodeDeque<Data> {
141	type Representation = UnifiedNodeRepresentation<Data>;
142
143	type Branch = Self;
144	type Leaf = Self;
145
146	fn into_representation(self, arena: &mut Arena<Self>) -> Self::Representation {
147		UnifiedNodeRepresentation {
148			children: remove_children_deque(&self, arena),
149			data: self.data,
150		}
151	}
152}
153
154impl<Data: Debug> BranchNode for UnifiedNodeDeque<Data> {
155	type ChildrenIter<'branch> = Copied<vec_deque::Iter<'branch, Token<Self>>>
156	where
157		Self: 'branch;
158
159	#[inline]
160	fn first(&self) -> Option<Token<Self>> {
161		match self.children.len() {
162			0 => None,
163			_ => Some(self.children[0]),
164		}
165	}
166
167	#[inline]
168	fn last(&self) -> Option<Token<Self>> {
169		match self.children.len() {
170			0 => None,
171			len => Some(self.children[len - 1]),
172		}
173	}
174
175	#[inline(always)]
176	fn children<'branch>(&'branch self, _arena: &'branch Arena<Self::Base>) -> Self::ChildrenIter<'branch> {
177		self.children.iter().copied()
178	}
179
180	#[inline(always)]
181	fn is_empty(&self) -> bool {
182		self.children.is_empty()
183	}
184
185	fn detach_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<Token<Self>> {
186		let child = arena.0[token.idx()].children.pop_front();
187
188		if let Some(child) = &child {
189			let node = &mut arena.0[child.idx()];
190
191			// Detach the node's parent.
192			node.parent = None;
193		}
194
195		child
196	}
197
198	fn detach_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<Token<Self>> {
199		let child = arena.0[token.idx()].children.pop_back();
200
201		if let Some(child) = &child {
202			let node = &mut arena.0[child.idx()];
203
204			// Detach the node's parent.
205			node.parent = None;
206		}
207
208		child
209	}
210
211	fn pop_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<UnifiedNodeRepresentation<Data>> {
212		let child = arena.0[token.idx()].children.pop_front();
213
214		child.map(|child| {
215			arena
216				.0
217				.remove(child.idx())
218				.expect("tried to remove child but there was no such node in the `arena`")
219				.into_representation(arena)
220		})
221	}
222
223	fn pop_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<UnifiedNodeRepresentation<Data>> {
224		let child = arena.0[token.idx()].children.pop_back();
225
226		child.map(|child| {
227			arena
228				.0
229				.remove(child.idx())
230				.expect("tried to remove child but there was no such node in the `arena`")
231				.into_representation(arena)
232		})
233	}
234
235	fn push_front(token: Self::Token, arena: &mut Arena<Self::Base>, new: Token<Self>) {
236		// We're not pushing our own root...
237		assert_ne!(
238			arena.0[token.idx()].root(arena),
239			new,
240			"tried to push this branch's own root as a child"
241		);
242		// And we're not pushing a child that already has a parent...
243		assert!(
244			arena.0[new.idx()].parent.is_none(),
245			"tried to push a child that already has a parent"
246		);
247
248		// Set the child's parent.
249		arena.0[new.idx()].parent = Some(token);
250
251		// Push the child's token.
252		arena.0[token.idx()].children.push_front(new);
253	}
254
255	fn push_back(token: Self::Token, arena: &mut Arena<Self::Base>, new: Token<Self>) {
256		// We're not pushing our own root...
257		assert_ne!(
258			arena.0[token.idx()].root(arena),
259			new,
260			"tried to push this branch's own root as a child"
261		);
262		// And we're not pushing a child that already has a parent...
263		assert!(
264			arena.0[new.idx()].parent.is_none(),
265			"tried to push a child that already has a parent"
266		);
267
268		// Set the child's parent.
269		arena.0[new.idx()].parent = Some(token);
270
271		// Push the child's token.
272		arena.0[token.idx()].children.push_back(new);
273	}
274}
275
276impl<Data: Debug> Index<usize> for UnifiedNodeDeque<Data> {
277	type Output = Token<Self>;
278
279	#[inline(always)]
280	fn index(&self, index: usize) -> &Self::Output {
281		&self.children[index]
282	}
283}
284
285impl<Data: Debug> BranchNodeDeque for UnifiedNodeDeque<Data> {
286	#[inline(always)]
287	fn len(&self) -> usize {
288		self.children.len()
289	}
290
291	fn detach(token: Self::Token, arena: &mut Arena<Self>, index: usize) -> Token<Self> {
292		let children = &mut arena.0[token.idx()].children;
293
294		let child = children.remove(index).unwrap_or_else(|| {
295			panic!(
296				"the given `index` ({index}) was out of bounds; there were only {} children",
297				children.len()
298			)
299		});
300
301		// Detach the child's parent.
302		arena.0[child.idx()].parent = None;
303
304		child
305	}
306
307	fn remove(token: Self::Token, arena: &mut Arena<Self>, index: usize) -> UnifiedNodeRepresentation<Data> {
308		let children = &mut arena.0[token.idx()].children;
309
310		let child = children.remove(index).unwrap_or_else(|| {
311			panic!(
312				"the given `index` ({index}) was out of bounds; there were only {} children",
313				children.len()
314			)
315		});
316
317		arena
318			.0
319			.remove(child.idx())
320			.expect("tried to remove child but there was no such node in `arena`")
321			.into_representation(arena)
322	}
323
324	fn insert(token: Self::Token, arena: &mut Arena<Self>, index: usize, new: Token<Self>) {
325		// We're not inserting our own root...
326		assert_ne!(
327			arena.0[token.idx()].root(arena),
328			new,
329			"tried to insert this branch's own root as a child"
330		);
331		// And we're not inserting a child that already has a parent...
332		assert!(
333			arena.0[new.idx()].parent.is_none(),
334			"tried to insert a child that already has a parent"
335		);
336
337		// Set the child's parent.
338		arena.0[new.idx()].parent = Some(token);
339
340		// Insert the child's token.
341		arena.0[token.idx()].children.insert(index, new);
342	}
343}