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
#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
)]
use std::fmt::{self, Debug, Formatter};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Tree<T> {
vec: Vec<Node<T>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeId(usize);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Node<T> {
parent: Option<NodeId>,
prev_sibling: Option<NodeId>,
next_sibling: Option<NodeId>,
children: Option<(NodeId, NodeId)>,
value: T,
}
impl<T> Node<T> {
fn new(value: T) -> Self {
Node {
parent: None,
prev_sibling: None,
next_sibling: None,
children: None,
value,
}
}
}
#[derive(Debug)]
pub struct NodeRef<'a, T: 'a> {
id: NodeId,
tree: &'a Tree<T>,
node: &'a Node<T>,
}
#[derive(Debug)]
pub struct NodeMut<'a, T: 'a> {
id: NodeId,
tree: &'a mut Tree<T>,
}
impl<'a, T: 'a> Copy for NodeRef<'a, T> { }
impl<'a, T: 'a> Clone for NodeRef<'a, T> {
fn clone(&self) -> Self { *self }
}
impl<'a, T: 'a> Eq for NodeRef<'a, T> { }
impl<'a, T: 'a> PartialEq for NodeRef<'a, T> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
&& self.tree as *const _ == other.tree as *const _
&& self.node as *const _ == other.node as *const _
}
}
impl<T> Tree<T> {
pub fn new(root: T) -> Self {
Tree { vec: vec![Node::new(root)] }
}
pub fn with_capacity(root: T, capacity: usize) -> Self {
let mut vec = Vec::with_capacity(capacity);
vec.push(Node::new(root));
Tree { vec }
}
pub fn get(&self, id: NodeId) -> Option<NodeRef<T>> {
self.vec.get(id.0).map(|node| NodeRef { id, node, tree: self })
}
pub fn get_mut(&mut self, id: NodeId) -> Option<NodeMut<T>> {
let exists = self.vec.get(id.0).map(|_| ());
exists.map(move |_| NodeMut { id, tree: self })
}
unsafe fn node(&self, id: NodeId) -> &Node<T> {
self.vec.get_unchecked(id.0)
}
unsafe fn node_mut(&mut self, id: NodeId) -> &mut Node<T> {
self.vec.get_unchecked_mut(id.0)
}
pub unsafe fn get_unchecked(&self, id: NodeId) -> NodeRef<T> {
NodeRef { id, node: self.node(id), tree: self }
}
pub unsafe fn get_unchecked_mut(&mut self, id: NodeId) -> NodeMut<T> {
NodeMut { id, tree: self }
}
pub fn root(&self) -> NodeRef<T> {
unsafe { self.get_unchecked(NodeId(0)) }
}
pub fn root_mut(&mut self) -> NodeMut<T> {
unsafe { self.get_unchecked_mut(NodeId(0)) }
}
pub fn orphan(&mut self, value: T) -> NodeMut<T> {
let id = NodeId(self.vec.len());
self.vec.push(Node::new(value));
unsafe { self.get_unchecked_mut(id) }
}
}
impl<'a, T: 'a> NodeRef<'a, T> {
pub fn id(&self) -> NodeId {
self.id
}
pub fn tree(&self) -> &'a Tree<T> {
self.tree
}
pub fn value(&self) -> &'a T {
&self.node.value
}
pub fn parent(&self) -> Option<Self> {
self.node.parent.map(|id| unsafe { self.tree.get_unchecked(id) })
}
pub fn prev_sibling(&self) -> Option<Self> {
self.node.prev_sibling.map(|id| unsafe { self.tree.get_unchecked(id) })
}
pub fn next_sibling(&self) -> Option<Self> {
self.node.next_sibling.map(|id| unsafe { self.tree.get_unchecked(id) })
}
pub fn first_child(&self) -> Option<Self> {
self.node.children.map(|(id, _)| unsafe { self.tree.get_unchecked(id) })
}
pub fn last_child(&self) -> Option<Self> {
self.node.children.map(|(_, id)| unsafe { self.tree.get_unchecked(id) })
}
pub fn has_siblings(&self) -> bool {
self.node.prev_sibling.is_some() || self.node.next_sibling.is_some()
}
pub fn has_children(&self) -> bool {
self.node.children.is_some()
}
}
impl<'a, T: 'a> NodeMut<'a, T> {
pub fn id(&self) -> NodeId {
self.id
}
pub fn tree(&mut self) -> &mut Tree<T> {
self.tree
}
fn node(&mut self) -> &mut Node<T> {
unsafe { self.tree.node_mut(self.id) }
}
pub fn value(&mut self) -> &mut T {
&mut self.node().value
}
pub fn parent(&mut self) -> Option<NodeMut<T>> {
let id = self.node().parent;
id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) })
}
pub fn prev_sibling(&mut self) -> Option<NodeMut<T>> {
let id = self.node().prev_sibling;
id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) })
}
pub fn next_sibling(&mut self) -> Option<NodeMut<T>> {
let id = self.node().next_sibling;
id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) })
}
pub fn first_child(&mut self) -> Option<NodeMut<T>> {
let ids = self.node().children;
ids.map(move |(id, _)| unsafe { self.tree.get_unchecked_mut(id) })
}
pub fn last_child(&mut self) -> Option<NodeMut<T>> {
let ids = self.node().children;
ids.map(move |(_, id)| unsafe { self.tree.get_unchecked_mut(id) })
}
pub fn has_siblings(&self) -> bool {
unsafe { self.tree.get_unchecked(self.id).has_siblings() }
}
pub fn has_children(&self) -> bool {
unsafe { self.tree.get_unchecked(self.id).has_children() }
}
pub fn append(&mut self, value: T) -> NodeMut<T> {
let id = self.tree.orphan(value).id;
self.append_id(id)
}
pub fn prepend(&mut self, value: T) -> NodeMut<T> {
let id = self.tree.orphan(value).id;
self.prepend_id(id)
}
pub fn insert_before(&mut self, value: T) -> NodeMut<T> {
let id = self.tree.orphan(value).id;
self.insert_id_before(id)
}
pub fn insert_after(&mut self, value: T) -> NodeMut<T> {
let id = self.tree.orphan(value).id;
self.insert_id_after(id)
}
pub fn detach(&mut self) {
let parent_id = match self.node().parent {
Some(id) => id,
None => return,
};
let prev_sibling_id = self.node().prev_sibling;
let next_sibling_id = self.node().next_sibling;
{
self.node().parent = None;
self.node().prev_sibling = None;
self.node().next_sibling = None;
}
if let Some(id) = prev_sibling_id {
unsafe { self.tree.node_mut(id).next_sibling = next_sibling_id; }
}
if let Some(id) = next_sibling_id {
unsafe { self.tree.node_mut(id).prev_sibling = prev_sibling_id; }
}
let parent = unsafe { self.tree.node_mut(parent_id) };
let (first_child_id, last_child_id) = parent.children.unwrap();
if first_child_id == last_child_id {
parent.children = None;
} else if first_child_id == self.id {
parent.children = Some((next_sibling_id.unwrap(), last_child_id));
} else if last_child_id == self.id {
parent.children = Some((first_child_id, prev_sibling_id.unwrap()));
}
}
pub fn append_id(&mut self, new_child_id: NodeId) -> NodeMut<T> {
let last_child_id = self.node().children.map(|(_, id)| id);
{
let mut new_child = self.tree.get_mut(new_child_id).unwrap();
new_child.detach();
new_child.node().parent = Some(self.id);
new_child.node().prev_sibling = last_child_id;
}
if let Some(id) = last_child_id {
unsafe { self.tree.node_mut(id).next_sibling = Some(new_child_id); }
}
{
if let Some((first_child_id, _)) = self.node().children {
self.node().children = Some((first_child_id, new_child_id));
} else {
self.node().children = Some((new_child_id, new_child_id));
}
}
unsafe { self.tree.get_unchecked_mut(new_child_id) }
}
pub fn prepend_id(&mut self, new_child_id: NodeId) -> NodeMut<T> {
let first_child_id = self.node().children.map(|(id, _)| id);
{
let mut new_child = self.tree.get_mut(new_child_id).unwrap();
new_child.detach();
new_child.node().parent = Some(self.id);
new_child.node().next_sibling = first_child_id;
}
if let Some(id) = first_child_id {
unsafe { self.tree.node_mut(id).prev_sibling = Some(new_child_id); }
}
{
if let Some((_, last_child_id)) = self.node().children {
self.node().children = Some((new_child_id, last_child_id));
} else {
self.node().children = Some((new_child_id, new_child_id));
}
}
unsafe { self.tree.get_unchecked_mut(new_child_id) }
}
pub fn insert_id_before(&mut self, new_sibling_id: NodeId) -> NodeMut<T> {
let parent_id = self.node().parent.unwrap();
let prev_sibling_id = self.node().prev_sibling;
{
let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
new_sibling.node().parent = Some(parent_id);
new_sibling.node().prev_sibling = prev_sibling_id;
new_sibling.node().next_sibling = Some(self.id);
}
if let Some(id) = prev_sibling_id {
unsafe { self.tree.node_mut(id).next_sibling = Some(new_sibling_id); }
}
self.node().prev_sibling = Some(new_sibling_id);
{
let parent = unsafe { self.tree.node_mut(parent_id) };
let (first_child_id, last_child_id) = parent.children.unwrap();
if first_child_id == self.id {
parent.children = Some((new_sibling_id, last_child_id));
}
}
unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
}
pub fn insert_id_after(&mut self, new_sibling_id: NodeId) -> NodeMut<T> {
let parent_id = self.node().parent.unwrap();
let next_sibling_id = self.node().next_sibling;
{
let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
new_sibling.node().parent = Some(parent_id);
new_sibling.node().prev_sibling = Some(self.id);
new_sibling.node().next_sibling = next_sibling_id;
}
if let Some(id) = next_sibling_id {
unsafe { self.tree.node_mut(id).prev_sibling = Some(new_sibling_id); }
}
self.node().next_sibling = Some(new_sibling_id);
{
let parent = unsafe { self.tree.node_mut(parent_id) };
let (first_child_id, last_child_id) = parent.children.unwrap();
if last_child_id == self.id {
parent.children = Some((first_child_id, new_sibling_id));
}
}
unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
}
pub fn reparent_from_id_append(&mut self, from_id: NodeId) {
let new_child_ids = {
let mut from = self.tree.get_mut(from_id).unwrap();
match from.node().children.take() {
Some(ids) => ids,
None => return,
}
};
unsafe {
self.tree.node_mut(new_child_ids.0).parent = Some(self.id);
self.tree.node_mut(new_child_ids.1).parent = Some(self.id);
}
if self.node().children.is_none() {
self.node().children = Some(new_child_ids);
return;
}
let old_child_ids = self.node().children.unwrap();
unsafe {
self.tree.node_mut(old_child_ids.1).next_sibling = Some(new_child_ids.0);
self.tree.node_mut(new_child_ids.0).prev_sibling = Some(old_child_ids.1);
}
self.node().children = Some((old_child_ids.0, new_child_ids.1));
}
pub fn reparent_from_id_prepend(&mut self, from_id: NodeId) {
let new_child_ids = {
let mut from = self.tree.get_mut(from_id).unwrap();
match from.node().children.take() {
Some(ids) => ids,
None => return,
}
};
unsafe {
self.tree.node_mut(new_child_ids.0).parent = Some(self.id);
self.tree.node_mut(new_child_ids.1).parent = Some(self.id);
}
if self.node().children.is_none() {
self.node().children = Some(new_child_ids);
return;
}
let old_child_ids = self.node().children.unwrap();
unsafe {
self.tree.node_mut(old_child_ids.0).prev_sibling = Some(new_child_ids.1);
self.tree.node_mut(new_child_ids.1).next_sibling = Some(old_child_ids.0);
}
self.node().children = Some((new_child_ids.0, old_child_ids.1));
}
}
impl<'a, T: 'a> From<NodeMut<'a, T>> for NodeRef<'a, T> {
fn from(node: NodeMut<'a, T>) -> Self {
unsafe { node.tree.get_unchecked(node.id) }
}
}
pub mod iter;
#[macro_export]
macro_rules! tree {
(@ $n:ident { }) => { };
(@ $n:ident { $value:expr }) => {
{ $n.append($value); }
};
(@ $n:ident { $value:expr, $($tail:tt)* }) => {
{
$n.append($value);
tree!(@ $n { $($tail)* });
}
};
(@ $n:ident { $value:expr => $children:tt }) => {
{
let mut node = $n.append($value);
tree!(@ node $children);
}
};
(@ $n:ident { $value:expr => $children:tt, $($tail:tt)* }) => {
{
{
let mut node = $n.append($value);
tree!(@ node $children);
}
tree!(@ $n { $($tail)* });
}
};
($root:expr) => { $crate::Tree::new($root) };
($root:expr => $children:tt) => {
{
let mut tree = $crate::Tree::new($root);
{
let mut node = tree.root_mut();
tree!(@ node $children);
}
tree
}
};
}
impl<T: Debug> Debug for Tree<T> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
use iter::Edge;
if f.alternate() {
write!(f, "Tree {{")?;
for edge in self.root().traverse() {
match edge {
Edge::Open(node) if node.has_children() => {
write!(f, " {:?} => {{", node.value())?;
},
Edge::Open(node) if node.next_sibling().is_some() => {
write!(f, " {:?},", node.value())?;
},
Edge::Open(node) => {
write!(f, " {:?}", node.value())?;
},
Edge::Close(node) if node.has_children() => {
if node.next_sibling().is_some() {
write!(f, " }},")?;
} else {
write!(f, " }}")?;
}
},
_ => {},
}
}
write!(f, " }}")
} else {
f.debug_struct("Tree").field("vec", &self.vec).finish()
}
}
}