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
//! Low-level implementation of an AA tree. You shouldn't have to use this directly; instead, use
//! the implementations in [`AATreeSet`](crate::AATreeSet) and [`AATreeMap`](crate::AATreeMap).

use alloc::boxed::Box;
use core::mem;

mod insert;
mod remove;
mod traverse;

pub use traverse::*;

#[derive(Clone, Debug, PartialEq)]
pub struct AANode<T>(Option<Box<Node<T>>>);

#[derive(Clone, Debug, PartialEq)]
pub(super) struct Node<T> {
	pub(super) level: u8,
	pub(super) content: T,
	pub(super) left_child: AANode<T>,
	pub(super) right_child: AANode<T>
}

impl<T> From<Node<T>> for AANode<T> {
	fn from(node: Node<T>) -> Self {
		Self(Some(Box::new(node)))
	}
}

impl<T> Default for AANode<T> {
	fn default() -> Self {
		Self::new()
	}
}

impl<T> From<T> for AANode<T> {
	fn from(content: T) -> Self {
		Node {
			level: 1,
			content,
			left_child: Self(None),
			right_child: Self(None)
		}
		.into()
	}
}

impl<T> AANode<T> {
	pub(super) fn unbox(self) -> Option<Node<T>> {
		self.0.map(|this| *this)
	}

	pub(super) fn as_ref(&self) -> Option<&Node<T>> {
		self.0.as_ref().map(Box::as_ref)
	}

	fn as_mut(&mut self) -> Option<&mut Node<T>> {
		self.0.as_mut().map(Box::as_mut)
	}

	fn take(&mut self) -> Self {
		Self(self.0.take())
	}

	/// Create a new `Nil` node.
	pub const fn new() -> Self {
		Self(None)
	}

	/// Return true if this node is `Nil`.
	pub const fn is_nil(&self) -> bool {
		self.0.is_none()
	}

	/// Return true if this node is a leaf.
	pub fn is_leaf(&self) -> bool {
		match self.as_ref() {
			None => false,
			Some(Node {
				left_child,
				right_child,
				..
			}) => left_child.is_nil() && right_child.is_nil()
		}
	}

	/// Return true if this node has a left child.
	pub fn has_left_child(&self) -> bool {
		match self.as_ref() {
			None => false,
			Some(Node { left_child, .. }) => !left_child.is_nil()
		}
	}

	/// Return true if this node has a right child.
	pub fn has_right_child(&self) -> bool {
		match self.as_ref() {
			None => false,
			Some(Node { right_child, .. }) => !right_child.is_nil()
		}
	}

	fn left_child_mut(&mut self) -> Option<&mut Self> {
		self.as_mut().and_then(|Node { left_child, .. }| {
			(!left_child.is_nil()).then(|| left_child)
		})
	}

	fn right_child_mut(&mut self) -> Option<&mut Self> {
		self.as_mut().and_then(|Node { right_child, .. }| {
			(!right_child.is_nil()).then(|| right_child)
		})
	}

	fn set_right_child(&mut self, child: Self) {
		match self.as_mut() {
			None => panic!("I don't have a right child"),
			Some(Node { right_child, .. }) => {
				*right_child = child;
			}
		}
	}

	pub(super) fn level(&self) -> u8 {
		match self.as_ref() {
			None => 0,
			Some(Node { level, .. }) => *level
		}
	}

	fn content_mut(&mut self) -> Option<&mut T> {
		self.as_mut().map(|Node { content, .. }| content)
	}

	/// Update the level of this node. **Panic** if the node is [`Nil`](Self::Nil).
	fn set_level(&mut self, level: u8) {
		match self.as_mut() {
			None => panic!("Cannot change level of Nil"),
			Some(Node { level: l, .. }) => mem::replace(l, level)
		};
	}

	/// ```none
	///   L <--- S           S ---> T
	///  / \      \     =>  /      / \
	/// A   B      R       A      B   R
	/// ```
	fn skew(mut self) -> Self {
		match self.as_mut() {
			None => self,
			Some(Node {
				level,
				left_child: l,
				..
			}) => {
				// if level = l.level, remove the B node from L
				let b_node = match l.as_mut() {
					Some(Node {
						level: l_level,
						right_child: b,
						..
					}) if level == l_level => b.take(),
					_ => return self
				};

				// add the B node as our left child, removing L
				let mut l_node = mem::replace(l, b_node);

				// add our node T as the right child of L
				l_node
					.as_mut()
					.unwrap_or_else(|| unreachable!())
					.right_child = self;

				// L is our new node
				l_node
			}
		}
	}

	/// ```none
	///   S --> R --> X          R
	///  /     /          =>    / \
	/// A     B                T   X
	///                       / \
	///                      A   B
	/// ```
	fn split(mut self) -> Self {
		match self.as_mut() {
			None => self,
			Some(Node {
				level,
				right_child: r,
				..
			}) => {
				// remove the B node if R and X are not Nil
				let b_node = match r.as_mut() {
					Some(Node {
						left_child: b,
						right_child: x,
						..
					}) if &x.level() == level => b.take(),
					_ => return self
				};

				// attach the B node to our node, removing R
				let mut r_node = mem::replace(r, b_node);

				// attach our node to R and increment its level
				let r_node_mut = r_node.as_mut().unwrap_or_else(|| unreachable!());
				r_node_mut.level += 1;
				r_node_mut.left_child = self;

				// R is our new node
				r_node
			}
		}
	}
}

#[cfg(all(test, not(feature = "benchmark")))]
mod test {
	use super::*;

	macro_rules! tree {
		() => {
			AANode::new()
		};
		(Nil) => {
			AANode::new()
		};
		($content:expr) => {
			AANode::from($content)
		};
		($content:expr => [$level:expr, $left:tt, $right:tt]) => {
			{
				let _left = tree!(@internal $left);
				let _right = tree!(@internal $right);
				AANode(Some(Box::new(Node {
					level: $level,
					content: $content,
					left_child: _left,
					right_child: _right
				})))
			}
		};
		(@internal ($content:expr => [$level:expr, $left:tt, $right:tt])) => {
			tree!($content => [$level, $left, $right])
		};
		(@internal $inner:tt) => {
			tree!($inner)
		};
	}

	// ### TEST SKEW ###

	#[test]
	fn test_skew_nil() {
		let root: AANode<char> = tree!();
		println!("Input: {:?}", root);
		let skewed = root.skew();
		let expected = tree!();
		assert_eq!(skewed, expected);
	}

	#[test]
	fn test_skew_leaf() {
		let root = tree!('T');
		println!("Input: {:?}", root);
		let skewed = root.skew();
		let expected = tree!('T');
		assert_eq!(skewed, expected);
	}

	#[test]
	fn test_skew_simple() {
		let root = tree!('T' => [2, ('L' => [2, Nil, Nil]), 'R']);
		println!("Input: {:?}", root);
		let skewed = root.skew();
		let expected = tree!('L' => [2, Nil, ('T' => [2, Nil, 'R'])]);
		assert_eq!(skewed, expected);
	}

	#[test]
	fn test_skew_full() {
		let root = tree!('T' => [2, ('L' => [2, 'A', 'B']), 'R']);
		println!("Input: {:?}", root);
		let skewed = root.skew();
		let expected = tree!('L' => [2, 'A', ('T' => [2, 'B', 'R'])]);
		assert_eq!(skewed, expected);
	}

	// ### TEST SPLIT ###

	#[test]
	fn test_split_nil() {
		let root: AANode<char> = tree!();
		println!("Input: {:?}", root);
		let splitted = root.split();
		let expected = tree!();
		assert_eq!(splitted, expected);
	}

	#[test]
	fn test_split_leaf() {
		let root = tree!('T');
		println!("Input: {:?}", root);
		let splitted = root.split();
		let expected = tree!('T');
		assert_eq!(splitted, expected);
	}

	#[test]
	fn test_split_good_tree() {
		let root = tree!('T' => [2, 'A', ('R' => [2, 'B', 'X'])]);
		println!("Input: {:?}", root);
		let splitted = root.split();
		let expected = tree!('T' => [2, 'A', ('R' => [2, 'B', 'X'])]);
		assert_eq!(splitted, expected);
	}

	#[test]
	fn test_split_bad_tree() {
		let root = tree!('T' => [2, 'A', ('R' => [2, 'B', ('X' => [2, 'Y', 'Z'])])]);
		println!("Input: {:?}", root);
		let splitted = root.split();
		let expected = tree!('R' => [3, ('T' => [2, 'A', 'B']), ('X' => [2, 'Y', 'Z'])]);
		assert_eq!(splitted, expected);
	}

	// ### TEST INSERT ###

	#[test]
	fn test_insert_greater() {
		let mut root = tree!();
		for content in ['A', 'B', 'C', 'D', 'E', 'F', 'G'].iter() {
			assert!(root.insert(*content));
		}
		let expected = tree!('D' => [3, ('B' => [2, 'A', 'C']), ('F' => [2, 'E', 'G'])]);
		assert_eq!(root, expected);
	}

	#[test]
	fn test_insert_smaller() {
		let mut root = tree!();
		for content in ['Z', 'Y', 'X', 'W', 'V'].iter() {
			assert!(root.insert(*content));
		}
		let expected = tree!('W' => [2, 'V', ('Y' => [2, 'X', 'Z'])]);
		assert_eq!(root, expected);
	}

	#[test]
	fn test_insert_multiple() {
		let mut root = tree!();
		for content in ['A', 'A'].iter() {
			root.insert(*content);
		}
		let expected = tree!('A');
		assert_eq!(root, expected);
	}

	// ### TEST REMOVE ###

	#[test]
	fn test_remove_successor() {
		let mut root = tree!('B' => [1, Nil, 'C']);
		println!("Input:  `{:?}`", root);
		let removed = root.remove(&'B');
		let expected = tree!('C');
		assert_eq!(removed, Some('B'));
		assert_eq!(root, expected);
	}

	#[test]
	fn test_remove_predecessor() {
		let mut root = tree!('B' => [2, 'A', 'C']);
		println!("Input:  `{:?}`", root);
		let removed = root.remove(&'B');
		let expected = tree!('A' => [1, Nil, 'C']);
		assert_eq!(removed, Some('B'));
		assert_eq!(root, expected);
	}

	#[test]
	fn test_remove_complex() {
		// example taken from https://web.eecs.umich.edu/~sugih/courses/eecs281/f11/lectures/12-AAtrees+Treaps.pdf
		let mut root = tree!(30 => [3, (15 => [2, 5, 20]), (70 => [3, (50 => [2, 35, (60 => [2, 55, 65])]), (85 => [2, 80, 90])])]);
		println!("Input:  `{:?}`", root);
		let removed = root.remove(&5);
		let expected = tree!(50 => [3, (30 => [2, (15 => [1, Nil, 20]), 35]), (70 => [3, (60 => [2, 55, 65]), (85 => [2, 80, 90])])]);
		assert_eq!(removed, Some(5));
		assert_eq!(root, expected);
	}
}