1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::{collections::vec_deque, fmt::Debug, iter::Copied, ops::Index};

use super::*;
use crate::{remove_children_deque, BranchNodeDeque};

type BranchTokenDeque<BranchData, LeafData> = Token<BranchDeque<BranchData, LeafData>>;
type LeafTokenDeque<BranchData, LeafData> = Token<LeafDeque<BranchData, LeafData>>;

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum SplitNodeDeque<BranchData: Debug, LeafData: Debug> {
	Branch(BranchDeque<BranchData, LeafData>),
	Leaf(LeafDeque<BranchData, LeafData>),
}

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum SplitTokenDeque<BranchData: Debug, LeafData: Debug> {
	Branch(BranchTokenDeque<BranchData, LeafData>),
	Leaf(LeafTokenDeque<BranchData, LeafData>),
}

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct BranchDeque<BranchData: Debug, LeafData: Debug> {
	token: Token<Self>,

	parent: Option<BranchTokenDeque<BranchData, LeafData>>,
	children: VecDeque<SplitTokenDeque<BranchData, LeafData>>,

	data: BranchData,
}

#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct LeafDeque<BranchData: Debug, LeafData: Debug> {
	token: Token<Self>,

	parent: Option<BranchTokenDeque<BranchData, LeafData>>,

	data: LeafData,
}

impl<BranchData, LeafData> Debug for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Branch(branch) => write!(f, "BranchDequeToken({:?})", branch.idx()),
			Self::Leaf(leaf) => write!(f, "LeafDequeToken({:?})", leaf.idx()),
		}
	}
}

impl<BranchData, LeafData, I: Idx> PartialEq<I> for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn eq(&self, other: &I) -> bool {
		self.idx() == other.idx()
	}
}

impl<BranchData, LeafData> Eq for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Hash for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn hash<H: Hasher>(&self, state: &mut H) {
		match self {
			Self::Branch(branch) => branch.hash(state),
			Self::Leaf(leaf) => leaf.hash(state),
		}
	}
}

impl<BranchData, LeafData> Clone for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn clone(&self) -> Self {
		*self
	}
}

impl<BranchData, LeafData> Copy for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	/// Creates a new `SplitTokenDeque` for a [branch] from the given `token`.
	///
	/// [branch]: Branch
	#[inline(always)]
	pub const fn new_branch(token: BranchTokenDeque<BranchData, LeafData>) -> Self {
		Self::Branch(token)
	}

	/// Creates a new `SplitTokenDeque` for a [leaf] from the given `token`.
	///
	/// [leaf]: Leaf
	#[inline(always)]
	pub const fn new_leaf(token: LeafTokenDeque<BranchData, LeafData>) -> Self {
		Self::Leaf(token)
	}
}

impl<BranchData, LeafData> Idx for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn idx(&self) -> generational_arena::Index {
		match self {
			Self::Branch(branch) => branch.idx(),
			Self::Leaf(leaf) => leaf.idx(),
		}
	}
}

impl<BranchData, LeafData> NodeToken<SplitNodeDeque<BranchData, LeafData>> for SplitTokenDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData, Other: Node> PartialEq<Other> for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
	<Self as Node>::Token: PartialEq<Other::Token>,
{
	fn eq(&self, other: &Other) -> bool {
		self.token == other.token()
	}
}

impl<BranchData, LeafData> Eq for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Hash for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.token.hash(state);
	}
}

impl<BranchData, LeafData, Other: Node> PartialEq<Other> for LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
	<Self as Node>::Token: PartialEq<Other::Token>,
{
	fn eq(&self, other: &Other) -> bool {
		self.token == other.token()
	}
}

impl<BranchData, LeafData> Eq for LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Hash for LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.token.hash(state);
	}
}

impl<'node, BranchData, LeafData> TryFrom<&'node SplitNodeDeque<BranchData, LeafData>>
	for &'node BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Error = &'node SplitNodeDeque<BranchData, LeafData>;

	#[inline(always)]
	fn try_from(node: &'node SplitNodeDeque<BranchData, LeafData>) -> Result<Self, Self::Error> {
		match node {
			SplitNodeDeque::Branch(branch) => Ok(branch),
			SplitNodeDeque::Leaf(_) => Err(node),
		}
	}
}

impl<'node, BranchData, LeafData> TryFrom<&'node mut SplitNodeDeque<BranchData, LeafData>>
	for &'node mut BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Error = &'node mut SplitNodeDeque<BranchData, LeafData>;

	#[inline(always)]
	fn try_from(node: &'node mut SplitNodeDeque<BranchData, LeafData>) -> Result<Self, Self::Error> {
		match node {
			SplitNodeDeque::Branch(branch) => Ok(branch),
			SplitNodeDeque::Leaf(_) => Err(node),
		}
	}
}

impl<'node, BranchData, LeafData> TryFrom<&'node SplitNodeDeque<BranchData, LeafData>>
	for &'node LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Error = &'node SplitNodeDeque<BranchData, LeafData>;

	#[inline(always)]
	fn try_from(node: &'node SplitNodeDeque<BranchData, LeafData>) -> Result<Self, Self::Error> {
		match node {
			SplitNodeDeque::Branch(_) => Err(node),
			SplitNodeDeque::Leaf(leaf) => Ok(leaf),
		}
	}
}

impl<'node, BranchData, LeafData> TryFrom<&'node mut SplitNodeDeque<BranchData, LeafData>>
	for &'node mut LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Error = &'node mut SplitNodeDeque<BranchData, LeafData>;

	#[inline(always)]
	fn try_from(node: &'node mut SplitNodeDeque<BranchData, LeafData>) -> Result<Self, Self::Error> {
		match node {
			SplitNodeDeque::Branch(_) => Err(node),
			SplitNodeDeque::Leaf(leaf) => Ok(leaf),
		}
	}
}

impl<BranchData, LeafData> SplitNodeDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn set_parent(&mut self, parent: Option<BranchTokenDeque<BranchData, LeafData>>) {
		match self {
			Self::Branch(branch) => branch.parent = parent,
			Self::Leaf(leaf) => leaf.parent = parent,
		}
	}
}

impl<BranchData, LeafData> Sealed for SplitNodeDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Node for SplitNodeDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Base = Self;
	type Token = SplitTokenDeque<BranchData, LeafData>;

	type Data = SplitData<BranchData, LeafData>;
	type DataRef<'data> = SplitData<&'data BranchData, &'data LeafData>
	where
		Self: 'data;
	type DataRefMut<'data> = SplitData<&'data mut BranchData, &'data mut LeafData>
	where
		Self: 'data;

	#[inline(always)]
	fn new(arena: &mut Arena<Self>, data: Self::Data) -> Self::Token {
		match data {
			SplitData::Branch(data) => SplitTokenDeque::Branch(BranchDeque::new(arena, data)),
			SplitData::Leaf(data) => SplitTokenDeque::Leaf(LeafDeque::new(arena, data)),
		}
	}

	#[inline(always)]
	fn token(&self) -> Self::Token {
		match self {
			Self::Branch(branch) => SplitTokenDeque::Branch(branch.token()),
			Self::Leaf(leaf) => SplitTokenDeque::Leaf(leaf.token()),
		}
	}

	#[inline(always)]
	fn parent(&self) -> Option<<<Self::Base as BaseNode>::Branch as Node>::Token> {
		match self {
			Self::Branch(branch) => branch.parent(),
			Self::Leaf(leaf) => leaf.parent(),
		}
	}

	#[inline(always)]
	fn data(&self) -> Self::DataRef<'_> {
		match self {
			Self::Branch(branch) => SplitData::Branch(branch.data()),
			Self::Leaf(leaf) => SplitData::Leaf(leaf.data()),
		}
	}

	#[inline(always)]
	fn data_mut(&mut self) -> Self::DataRefMut<'_> {
		match self {
			Self::Branch(branch) => SplitData::Branch(branch.data_mut()),
			Self::Leaf(leaf) => SplitData::Leaf(leaf.data_mut()),
		}
	}
}

impl<BranchData, LeafData> BaseNode for SplitNodeDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Representation = SplitNodeRepresentation<BranchData, LeafData>;

	type Branch = BranchDeque<BranchData, LeafData>;
	type Leaf = LeafDeque<BranchData, LeafData>;

	fn into_representation(self, arena: &mut Arena<Self>) -> Self::Representation
	where
		Self: Sized,
	{
		match self {
			Self::Branch(branch) => SplitNodeRepresentation::Branch {
				children: remove_children_deque(&branch, arena),
				data: branch.data,
			},

			Self::Leaf(leaf) => SplitNodeRepresentation::Leaf { data: leaf.data },
		}
	}
}

impl<BranchData, LeafData> Sealed for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Node for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Base = SplitNodeDeque<BranchData, LeafData>;
	type Token = Token<Self>;

	type Data = BranchData;
	type DataRef<'data> = &'data BranchData
	where
		Self: 'data;
	type DataRefMut<'data> = &'data mut BranchData
	where
		Self: 'data;

	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Token<Self> {
		Token::new(arena.0.insert_with(|idx| {
			SplitNodeDeque::Branch(Self {
				token: Token::new(idx),

				parent: None,
				children: VecDeque::new(),

				data,
			})
		}))
	}

	#[inline(always)]
	fn token(&self) -> Self::Token {
		self.token
	}

	#[inline(always)]
	fn parent(&self) -> Option<Token<Self>> {
		self.parent
	}

	#[inline(always)]
	fn data(&self) -> &BranchData {
		&self.data
	}

	#[inline(always)]
	fn data_mut(&mut self) -> &mut BranchData {
		&mut self.data
	}
}

impl<BranchData, LeafData> BranchNode for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type ChildrenIter<'branch>
	= Copied<vec_deque::Iter<'branch, <Self::Base as Node>::Token>>
	where
		Self: 'branch;

	#[inline]
	fn first(&self) -> Option<<Self::Base as Node>::Token> {
		match self.children.len() {
			0 => None,
			_ => Some(self.children[0]),
		}
	}

	#[inline]
	fn last(&self) -> Option<<Self::Base as Node>::Token> {
		match self.children.len() {
			0 => None,
			len => Some(self.children[len - 1]),
		}
	}

	#[inline(always)]
	fn children<'branch>(&'branch self, _arena: &'branch Arena<Self::Base>) -> Self::ChildrenIter<'branch> {
		self.children.iter().copied()
	}

	#[inline(always)]
	fn is_empty(&self) -> bool {
		self.children.is_empty()
	}

	fn detach_front(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token> {
		let child = token_to_node!(ref mut, Self: token, arena).children.pop_front();

		if let Some(child) = &child {
			let node = &mut arena.0[child.idx()];

			// Detach the node's parent.
			node.set_parent(None);
		}

		child
	}

	fn detach_back(token: Self::Token, arena: &mut Arena<Self::Base>) -> Option<<Self::Base as Node>::Token> {
		let child = token_to_node!(ref mut, Self: token, arena).children.pop_back();

		if let Some(child) = &child {
			let node = &mut arena.0[child.idx()];

			// Detach the node's parent.
			node.set_parent(None);
		}

		child
	}

	fn pop_front(
		token: Self::Token,
		arena: &mut Arena<Self::Base>,
	) -> Option<SplitNodeRepresentation<BranchData, LeafData>> {
		let child = token_to_node!(ref mut, Self: token, arena).children.pop_front();

		child.map(|child| {
			arena
				.0
				.remove(child.idx())
				.expect("tried to remove child but there was no such node in the `arena`")
				.into_representation(arena)
		})
	}

	fn pop_back(
		token: Self::Token,
		arena: &mut Arena<Self::Base>,
	) -> Option<SplitNodeRepresentation<BranchData, LeafData>> {
		let child = token_to_node!(ref mut, Self: token, arena).children.pop_back();

		child.map(|child| {
			arena
				.0
				.remove(child.idx())
				.expect("tried to remove child but there was no such node in the `arena`")
				.into_representation(arena)
		})
	}

	fn push_front(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token) {
		// We're not pushing our own root...
		assert_ne!(
			arena.0[token.idx()].root(arena),
			new,
			"tried to push this branch's own root as a child"
		);
		// And we're not pushing a child that already has a parent...
		assert!(
			arena.0[new.idx()].parent().is_none(),
			"tried to push a child that already has a parent"
		);

		// Set the child's parent.
		arena.0[new.idx()].set_parent(Some(token));

		// Push the child's token.
		token_to_node!(ref mut, Self: token, arena).children.push_front(new);
	}

	fn push_back(token: Self::Token, arena: &mut Arena<Self::Base>, new: <Self::Base as Node>::Token) {
		// We're not pushing our own root...
		assert_ne!(
			arena.0[token.idx()].root(arena),
			new,
			"tried to push this branch's own root as a child"
		);
		// And we're not pushing a child that already has a parent...
		assert!(
			arena.0[new.idx()].parent().is_none(),
			"tried to push a child that already has a parent"
		);

		// Set the child's parent.
		arena.0[new.idx()].set_parent(Some(token));

		// Push the child's token.
		token_to_node!(ref mut, Self: token, arena).children.push_back(new);
	}
}

impl<BranchData, LeafData> Index<usize> for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Output = <<Self as Node>::Base as Node>::Token;

	#[inline(always)]
	fn index(&self, index: usize) -> &Self::Output {
		&self.children[index]
	}
}

impl<BranchData, LeafData> BranchNodeDeque for BranchDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	#[inline(always)]
	fn len(&self) -> usize {
		self.children.len()
	}

	fn detach(token: Self::Token, arena: &mut Arena<Self::Base>, index: usize) -> <Self::Base as Node>::Token {
		let children = &mut token_to_node!(ref mut, Self: token, arena).children;

		let child = children.remove(index).unwrap_or_else(|| {
			panic!(
				"the given `index` ({index}) was out of bounds; there were only {} children",
				children.len()
			)
		});

		// Detach the child's parent.
		arena.0[child.idx()].set_parent(None);

		child
	}

	fn remove(
		token: Self::Token,
		arena: &mut Arena<Self::Base>,
		index: usize,
	) -> SplitNodeRepresentation<BranchData, LeafData> {
		let children = &mut token_to_node!(ref mut, Self: token, arena).children;

		let child = children.remove(index).unwrap_or_else(|| {
			panic!(
				"the given `index` ({index}) was out of bounds; there were only {} children",
				children.len()
			)
		});

		arena
			.0
			.remove(child.idx())
			.expect("tried to remove child but there was no such node in `arena`")
			.into_representation(arena)
	}

	fn insert(token: Self::Token, arena: &mut Arena<Self::Base>, index: usize, new: <Self::Base as Node>::Token) {
		// We're not inserting our own root...
		assert_ne!(
			arena.0[token.idx()].root(arena),
			new,
			"tried to insert this branch's own root as a child"
		);
		// And we're not inserting a child that already has a parent...
		assert!(
			arena.0[new.idx()].parent().is_none(),
			"tried to insert a child that already has a parent"
		);

		// Set the child's parent.
		arena.0[new.idx()].set_parent(Some(token));

		// Insert the child's token.
		token_to_node!(ref mut, Self: token, arena).children.insert(index, new);
	}
}

impl<BranchData, LeafData> Sealed for LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
}

impl<BranchData, LeafData> Node for LeafDeque<BranchData, LeafData>
where
	BranchData: Debug,
	LeafData: Debug,
{
	type Base = SplitNodeDeque<BranchData, LeafData>;
	type Token = Token<Self>;

	type Data = LeafData;
	type DataRef<'data> = &'data LeafData
	where
		Self: 'data;
	type DataRefMut<'data> = &'data mut LeafData
	where
		Self: 'data;

	fn new(arena: &mut Arena<Self::Base>, data: Self::Data) -> Self::Token {
		Token::new(arena.0.insert_with(|idx| {
			SplitNodeDeque::Leaf(Self {
				token: Token::new(idx),

				parent: None,

				data,
			})
		}))
	}

	#[inline(always)]
	fn token(&self) -> Self::Token {
		self.token
	}

	#[inline(always)]
	fn parent(&self) -> Option<Token<<Self::Base as BaseNode>::Branch>> {
		self.parent
	}

	#[inline(always)]
	fn data(&self) -> &LeafData {
		&self.data
	}

	#[inline(always)]
	fn data_mut(&mut self) -> &mut LeafData {
		&mut self.data
	}
}