atree/token.rs
1#![allow(clippy::match_bool)]
2use std::collections::VecDeque;
3use std::marker::PhantomData;
4use std::num::NonZeroUsize;
5use std::mem::MaybeUninit;
6
7use crate::Error;
8use crate::iter::*;
9use crate::node::Node;
10use crate::arena::Arena;
11
12/// A `Token` is a handle to a node in the arena.
13#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
14pub struct Token {
15 pub (crate) index: NonZeroUsize
16}
17
18fn node_operation<T>(
19 self_token: Token,
20 arena: &mut Arena<T>,
21 other_token: Token,
22 func: fn(Token, &mut Arena<T>, T) -> Token
23) -> Result<(), Error> {
24 // only a placeholder to get around some trait requirements so I can
25 // reuse code. The uninitialized data will be removed so no risk here.
26 let dummy_data: T = unsafe { MaybeUninit::zeroed().assume_init() };
27 let token = func(self_token, arena, dummy_data);
28 token.replace_node(arena, other_token)?;
29 arena.remove(token); // remove uninitialized data
30 Ok(())
31}
32
33impl Token {
34 /// Checks whether a given node is actually a leaf.
35 ///
36 /// # Panics:
37 ///
38 /// Panics if the token does not correspond to a node in the arena.
39 pub fn is_leaf<T>(self, arena: &Arena<T>) -> bool {
40 match arena.get(self) {
41 None => panic!("Invalid token"),
42 Some(node) => node.is_leaf()
43 }
44 }
45
46 /// Creates a new node with the given data and append to the given node.
47 ///
48 /// # Panics:
49 ///
50 /// Panics if the token does not correspond to a node in the arena.
51 ///
52 /// # Examples:
53 ///
54 /// ```
55 /// use atree::Arena;
56 /// use atree::iter::TraversalOrder;
57 ///
58 /// let root_data = "Indo-European";
59 /// let (mut arena, root_token) = Arena::with_data(root_data);
60 ///
61 /// let next_node_token = root_token.append(&mut arena, "Germanic");
62 /// next_node_token.append(&mut arena, "Romance");
63 /// let mut subtree = root_token.subtree(&arena, TraversalOrder::Pre);
64 ///
65 /// assert_eq!(subtree.next().unwrap().data, "Indo-European");
66 /// assert_eq!(subtree.next().unwrap().data, "Germanic");
67 /// assert_eq!(subtree.next().unwrap().data, "Romance");
68 /// ```
69 pub fn append<T>(self, arena: &mut Arena<T>, data: T) -> Token {
70 let new_node_token = arena.allocator.head();
71 let previous_sibling = match self.children_mut(arena).last() {
72 None => {
73 // children_mut will have checked indexability so this will not
74 // fail
75 arena[self].first_child = Some(new_node_token);
76 None
77 },
78 Some(last_child) => {
79 last_child.next_sibling = Some(new_node_token);
80 Some(last_child.token)
81 }
82 };
83
84 let node = Node {
85 data,
86 token: new_node_token,
87 parent: Some(self),
88 previous_sibling,
89 next_sibling: None,
90 first_child: None
91 };
92 arena.set(new_node_token, node);
93 new_node_token
94 }
95
96 /// Creates a new node with the given data and sets as the previous sibling
97 /// of the current node.
98 ///
99 /// # Panics:
100 ///
101 /// Panics if the token does not correspond to a node in the arena.
102 ///
103 /// # Examples:
104 ///
105 /// ```
106 /// use atree::Arena;
107 /// use atree::iter::TraversalOrder;
108 ///
109 /// let root_data = "Indo-European";
110 /// let (mut arena, root_token) = Arena::with_data(root_data);
111 ///
112 /// let child2 = root_token.append(&mut arena, "Germanic");
113 /// let child4 = root_token.append(&mut arena, "Slavic");
114 /// child2.append(&mut arena, "English");
115 /// // insert in between children 2 and 4
116 /// let child3 = child4.insert_before(&mut arena, "Romance");
117 /// // insert before child 2
118 /// let child1 = child2.insert_before(&mut arena, "Celtic");
119 ///
120 /// let subtree: Vec<_> = root_token.subtree(&arena, TraversalOrder::Pre)
121 /// .map(|x| x.data)
122 /// .collect();
123 /// assert_eq!(&["Indo-European", "Celtic", "Germanic", "English", "Romance", "Slavic"],
124 /// &subtree[..]);
125 /// ```
126 pub fn insert_before<T>(self, arena: &mut Arena<T>, data: T) -> Token {
127 let new_node_token = arena.allocator.head();
128 let (self_parent, self_previous_sibling) = match arena.get(self) {
129 None => panic!("Invalid token"),
130 Some(node) => (node.parent, node.previous_sibling)
131 };
132 arena[self].previous_sibling = Some(new_node_token); // already checked
133 let previous_sibling = match self_previous_sibling {
134 Some(sibling) => match arena.get_mut(sibling) {
135 None => panic!("Corrupt arena"),
136 Some(ref mut node) => {
137 node.next_sibling = Some(new_node_token);
138 Some(sibling)
139 }
140 },
141 None => match self_parent {
142 None => panic!("Cannot insert as the previous sibling of the \
143 root node"),
144 Some(p) => match arena.get_mut(p) {
145 None => panic!("Corrupt arena"),
146 Some(ref mut node) => {
147 node.first_child = Some(new_node_token);
148 None
149 }
150 }
151 }
152 };
153
154 let node = Node {
155 data,
156 token: new_node_token,
157 parent: self_parent,
158 previous_sibling,
159 next_sibling: Some(self),
160 first_child: None
161 };
162 arena.set(new_node_token, node);
163 new_node_token
164 }
165
166 /// Set a node in the arena as the next sibling of the given node. Returns
167 /// error if the "other node" is not a root node of a tree (as in it already
168 /// has a parent and/or siblings).
169 ///
170 /// **Note**: for performance reasons, this operation does not check whether
171 /// the "self" node is in fact a descendant of the other tree. A cyclic
172 /// graph may result.
173 ///
174 /// # Panics:
175 ///
176 /// Panics if the token does not correspond to a node in the arena.
177 ///
178 /// # Examples:
179 /// ```
180 /// use atree::Arena;
181 /// use atree::iter::TraversalOrder;
182 ///
183 /// // root node that we will attach subtrees to
184 /// let root_data = "Indo-European";
185 /// let (mut arena, root) = Arena::with_data(root_data);
186 ///
187 /// let germanic = root.append(&mut arena, "Germanic");
188 /// let scots = germanic.append(&mut arena, "German");
189 /// let english = germanic.append(&mut arena, "English");
190 ///
191 /// let romance = arena.new_node("Romance");
192 /// let french = romance.append(&mut arena, "French");
193 /// let spanish = romance.append(&mut arena, "Spanish");
194 ///
195 /// germanic.insert_node_after(&mut arena, romance);
196 ///
197 /// let mut iter = root.subtree(&arena, TraversalOrder::Pre)
198 /// .map(|x| x.data);
199 /// assert_eq!(iter.next(), Some("Indo-European"));
200 /// assert_eq!(iter.next(), Some("Germanic"));
201 /// assert_eq!(iter.next(), Some("German"));
202 /// assert_eq!(iter.next(), Some("English"));
203 /// assert_eq!(iter.next(), Some("Romance"));
204 /// assert_eq!(iter.next(), Some("French"));
205 /// assert_eq!(iter.next(), Some("Spanish"));
206 /// assert!(iter.next().is_none())
207 /// ```
208 pub fn insert_node_after<T>(self, arena: &mut Arena<T>, other: Token)
209 -> Result<(), Error> {
210 node_operation(self, arena, other, Token::insert_after)
211 }
212
213 /// Set a node in the arena as the previous sibling of the given node.
214 /// Returns error if the "other node" is not a root node of a tree (as in it
215 /// already has a parent and/or siblings).
216 ///
217 /// **Note**: for performance reasons, this operation does not check whether
218 /// the "self" node is in fact a descendant of the other tree. A cyclic
219 /// graph may result.
220 ///
221 /// # Panics:
222 ///
223 /// Panics if the token does not correspond to a node in the arena.
224 ///
225 /// # Examples:
226 /// ```
227 /// use atree::Arena;
228 /// use atree::iter::TraversalOrder;
229 ///
230 /// // root node that we will attach subtrees to
231 /// let root_data = "Indo-European";
232 /// let (mut arena, root) = Arena::with_data(root_data);
233 ///
234 /// let germanic = root.append(&mut arena, "Germanic");
235 /// let scots = germanic.append(&mut arena, "German");
236 /// let english = germanic.append(&mut arena, "English");
237 ///
238 /// let romance = arena.new_node("Romance");
239 /// let french = romance.append(&mut arena, "French");
240 /// let spanish = romance.append(&mut arena, "Spanish");
241 ///
242 /// germanic.insert_node_before(&mut arena, romance);
243 ///
244 /// let mut iter = root.subtree(&arena, TraversalOrder::Pre)
245 /// .map(|x| x.data);
246 /// assert_eq!(iter.next(), Some("Indo-European"));
247 /// assert_eq!(iter.next(), Some("Romance"));
248 /// assert_eq!(iter.next(), Some("French"));
249 /// assert_eq!(iter.next(), Some("Spanish"));
250 /// assert_eq!(iter.next(), Some("Germanic"));
251 /// assert_eq!(iter.next(), Some("German"));
252 /// assert_eq!(iter.next(), Some("English"));
253 /// assert!(iter.next().is_none())
254 /// ```
255 pub fn insert_node_before<T>(self, arena: &mut Arena<T>, other: Token)
256 -> Result<(), Error> {
257 node_operation(self, arena, other, Token::insert_before)
258 }
259
260 /// Creates a new node with the given data and sets as the next sibling of
261 /// the current node.
262 ///
263 /// # Panics:
264 ///
265 /// Panics if the token does not correspond to a node in the arena.
266 ///
267 /// # Examples:
268 ///
269 /// ```
270 /// use atree::Arena;
271 /// use atree::iter::TraversalOrder;
272 ///
273 /// let root_data = "Indo-European";
274 /// let (mut arena, root_token) = Arena::with_data(root_data);
275 ///
276 /// let child1 = root_token.append(&mut arena, "Romance");
277 /// let child3 = root_token.append(&mut arena, "Germanic");
278 /// child1.append(&mut arena, "French");
279 /// // insert betwern children 1 and 4
280 /// let child2 = child1.insert_after(&mut arena, "Celtic");
281 /// // insert after child 3
282 /// child3.insert_after(&mut arena, "Slavic");
283 ///
284 /// let subtree: Vec<_> = root_token.subtree(&arena, TraversalOrder::Pre)
285 /// .map(|x| x.data)
286 /// .collect();
287 /// assert_eq!(&["Indo-European", "Romance", "French", "Celtic", "Germanic", "Slavic"],
288 /// &subtree[..]);
289 /// ```
290 pub fn insert_after<T>(self, arena: &mut Arena<T>, data: T) -> Token {
291 let new_node_token = arena.allocator.head();
292 let (self_parent, self_next_sibling) = match arena.get(self) {
293 None => panic!("Invalid token"),
294 Some(node) => (node.parent, node.next_sibling)
295 };
296 arena[self].next_sibling = Some(new_node_token); // already checked
297 let next_sibling = match self_next_sibling {
298 None => None,
299 Some(sibling) => match arena.get_mut(sibling) {
300 None => panic!("Corrupt arena"),
301 Some(ref mut node) => {
302 node.previous_sibling = Some(new_node_token);
303 Some(sibling)
304 }
305 },
306 };
307
308 let node = Node {
309 data,
310 token: new_node_token,
311 parent: self_parent,
312 previous_sibling: Some(self),
313 next_sibling,
314 first_child: None
315 };
316 arena.set(new_node_token, node);
317 new_node_token
318 }
319
320 /// Attaches a different tree in the arena to a node. Returns error if the
321 /// "root node" of the other tree is not really a root node (as in it
322 /// already has a parent and/or siblings). To attach a tree from a different
323 /// arena, use [`copy_and_append_subtree`] instead.
324 ///
325 /// **Note**: for performance reasons, this operation does not check whether
326 /// the "self" node is in fact a descendant of the other tree. A cyclic
327 /// graph may result.
328 ///
329 /// # Panics:
330 ///
331 /// Panics if the token does not correspond to a node in the arena.
332 ///
333 /// # Examples:
334 /// ```
335 /// use atree::Arena;
336 /// use atree::iter::TraversalOrder;
337 ///
338 /// // root node that we will attach subtrees to
339 /// let root_data = "Indo-European";
340 /// let (mut arena, root) = Arena::with_data(root_data);
341 ///
342 /// // the Germanic branch
343 /// let germanic = arena.new_node("Germanic");
344 /// let west = germanic.append(&mut arena, "West");
345 /// let scots = west.append(&mut arena, "Scots");
346 /// let english = west.append(&mut arena, "English");
347 ///
348 /// // the Romance branch
349 /// let romance = arena.new_node("Romance");
350 /// let french = romance.append(&mut arena, "French");
351 /// let italian = romance.append(&mut arena, "Italian");
352 ///
353 /// // attach subtrees
354 /// root.append_node(&mut arena, romance).unwrap();
355 /// root.append_node(&mut arena, germanic).unwrap();
356 ///
357 /// let mut iter = root.subtree(&arena, TraversalOrder::Pre)
358 /// .map(|x| x.data);
359 /// assert_eq!(iter.next(), Some("Indo-European"));
360 /// assert_eq!(iter.next(), Some("Romance"));
361 /// assert_eq!(iter.next(), Some("French"));
362 /// assert_eq!(iter.next(), Some("Italian"));
363 /// assert_eq!(iter.next(), Some("Germanic"));
364 /// assert_eq!(iter.next(), Some("West"));
365 /// assert_eq!(iter.next(), Some("Scots"));
366 /// assert_eq!(iter.next(), Some("English"));
367 /// assert!(iter.next().is_none())
368 /// ```
369 ///
370 /// [`copy_and_append_subtree`]: struct.Arena.html#method.copy_and_append_subtree
371 pub fn append_node<T>(self, arena: &mut Arena<T>, other: Self)
372 -> Result<(), Error> {
373 node_operation(self, arena, other, Token::append)
374 }
375
376 /// Detaches the given node and its descendants into its own tree while
377 /// keeping it in the same arena. To detach and allocate the subtree into its
378 /// own arena, use [`split_at`] instead.
379 ///
380 /// # Panics:
381 ///
382 /// Panics if the token does not correspond to a node in the arena.
383 ///
384 /// # Examples:
385 /// ```
386 /// use atree::Arena;
387 /// use atree::iter::TraversalOrder;
388 ///
389 /// // root node that we will attach subtrees to
390 /// let root_data = "Indo-European";
391 /// let (mut arena, root) = Arena::with_data(root_data);
392 ///
393 /// // the Germanic branch
394 /// let germanic = root.append(&mut arena, "Germanic");
395 /// let west = germanic.append(&mut arena, "West");
396 /// let scots = west.append(&mut arena, "Scots");
397 /// let english = west.append(&mut arena, "English");
398 ///
399 /// // detach the west branch from the main tree
400 /// west.detach(&mut arena);
401 ///
402 /// // the west branch is gone from the original tree
403 /// let mut iter = root.subtree(&arena, TraversalOrder::Pre)
404 /// .map(|x| x.data);
405 /// assert_eq!(iter.next(), Some("Indo-European"));
406 /// assert_eq!(iter.next(), Some("Germanic"));
407 /// assert!(iter.next().is_none());
408 ///
409 /// // it exists on its own
410 /// let mut iter = west.subtree(&arena, TraversalOrder::Pre)
411 /// .map(|x| x.data);
412 /// assert_eq!(iter.next(), Some("West"));
413 /// assert_eq!(iter.next(), Some("Scots"));
414 /// assert_eq!(iter.next(), Some("English"));
415 /// assert!(iter.next().is_none());
416 /// ```
417 ///
418 /// [`split_at`]: struct.Arena.html#method.split_at
419 pub fn detach<T>(self, arena: &mut Arena<T>) {
420 let (parent, previous_sibling, next_sibling) = match arena.get_mut(self) {
421 None => panic!("Invalid token"),
422 Some(node) => {
423 let parent = node.parent;
424 let previous_sibling = node.previous_sibling;
425 let next_sibling = node.next_sibling;
426 node.parent = None;
427 node.previous_sibling = None;
428 node.next_sibling = None;
429 (parent, previous_sibling, next_sibling)
430 }
431 };
432
433 match previous_sibling {
434 Some(token) => match arena.get_mut(token) {
435 None => panic!("Corrupt arena"),
436 Some(node) => node.next_sibling = next_sibling
437 },
438 None => if let Some(token) = parent {
439 match arena.get_mut(token) {
440 None => panic!("Corrupt arena"),
441 Some(n) => n.first_child = next_sibling
442 }
443 }
444 }
445
446 if let Some(token) = next_sibling {
447 match arena.get_mut(token) {
448 None => panic!("Corrupt arena"),
449 Some(node) => node.previous_sibling = previous_sibling
450 }
451 }
452 }
453
454 /// Replace the subtree of self with the subtree of other. Does not remove
455 /// self or its descendants but simply makes it a standalone tree within the
456 /// arena.
457 ///
458 /// **Note**: for performance reasons, this operation does not check whether
459 /// the "other" node is in fact a descendant of the parent tree of self. A
460 /// cyclic graph may result.
461 ///
462 /// # Panics:
463 ///
464 /// Panics if the token does not correspond to a node in the arena.
465 ///
466 /// # Examples:
467 /// ```
468 /// use atree::Arena;
469 /// use atree::iter::TraversalOrder;
470 ///
471 /// // root node that we will attach subtrees to
472 /// let root_data = "Indo-European";
473 /// let (mut arena, root) = Arena::with_data(root_data);
474 ///
475 /// // the Germanic branch
476 /// let germanic = root.append(&mut arena, "Germanic");
477 /// let west = germanic.append(&mut arena, "West");
478 /// let scots = west.append(&mut arena, "Scots");
479 /// let english = west.append(&mut arena, "English");
480 ///
481 /// // the slavic branch
482 /// let slavic = root.append(&mut arena, "Slavic");
483 /// let polish = slavic.append(&mut arena, "Polish");
484 /// let russian = slavic.append(&mut arena, "Russian");
485 ///
486 /// // the Romance branch
487 /// let romance = arena.new_node("Romance");
488 /// let french = romance.append(&mut arena, "French");
489 /// let italian = romance.append(&mut arena, "Italian");
490 ///
491 /// // replace_node germanic with romance
492 /// germanic.replace_node(&mut arena, romance).unwrap();
493 ///
494 /// let mut iter = root.subtree(&arena, TraversalOrder::Pre)
495 /// .map(|x| x.data);
496 /// assert_eq!(iter.next(), Some("Indo-European"));
497 /// assert_eq!(iter.next(), Some("Romance"));
498 /// assert_eq!(iter.next(), Some("French"));
499 /// assert_eq!(iter.next(), Some("Italian"));
500 /// assert_eq!(iter.next(), Some("Slavic"));
501 /// assert_eq!(iter.next(), Some("Polish"));
502 /// assert_eq!(iter.next(), Some("Russian"));
503 /// assert!(iter.next().is_none());
504 /// ```
505 pub fn replace_node<T>(self, arena: &mut Arena<T>, other: Token)
506 -> Result<(), Error> {
507 let self_node = match arena.get(self) {
508 None => panic!("Invalid token"),
509 Some(n) => n
510 };
511 let parent = self_node.parent;
512 let previous_sibling = self_node.previous_sibling;
513 let next_sibling = self_node.next_sibling;
514
515 let other_node = match arena.get_mut(other) {
516 None => panic!("Invalid token"),
517 Some(n) => n
518 };
519
520 // check that the other node is really a root node of its own
521 match (other_node.previous_sibling,
522 other_node.next_sibling,
523 other_node.parent) {
524 (None, None, None) => (),
525 _ => return Err(Error::NotARootNode)
526 }
527
528 // replace_node the self node with the other node
529 other_node.parent = parent;
530 other_node.next_sibling = next_sibling;
531 other_node.previous_sibling = previous_sibling;
532
533 let self_node = &mut arena[self]; // indexability has been checked
534 self_node.parent = None;
535 self_node.previous_sibling = None;
536 self_node.next_sibling = None;
537
538 // update previous_sibling, next_sibling and parent of the self node
539 match previous_sibling {
540 Some(sibling) => match arena.get_mut(sibling) {
541 None => panic!("Corrupt arena"),
542 Some(node) => node.next_sibling = Some(other)
543 },
544 None => if let Some(p) = parent {
545 match arena.get_mut(p) {
546 None => panic!("Corrupt arena"),
547 Some(node) => node.first_child = Some(other)
548 }
549 }
550 }
551
552 if let Some(sibling) = next_sibling {
553 match arena.get_mut(sibling) {
554 None => panic!("Corrupt arena"),
555 Some(node) => node.previous_sibling = Some(other)
556 }
557 }
558
559 Ok(())
560 }
561
562 /// Returns an iterator of tokens of ancestor nodes.
563 ///
564 /// # Panics:
565 ///
566 /// Panics if the token does not correspond to a node in the arena.
567 ///
568 /// # Examples:
569 ///
570 /// ```
571 /// use atree::Arena;
572 ///
573 /// let root_data = "Indo-European";
574 /// let (mut arena, root_token) = Arena::with_data(root_data);
575 ///
576 /// let child_token = root_token.append(&mut arena, "Germanic");
577 /// let grandchild_token = child_token.append(&mut arena, "English");
578 /// let mut ancestors_tokens = grandchild_token.ancestors_tokens(&arena);
579 ///
580 /// assert_eq!(ancestors_tokens.next(), Some(child_token));
581 /// assert_eq!(ancestors_tokens.next(), Some(root_token));
582 /// assert!(ancestors_tokens.next().is_none());
583 /// ```
584 pub fn ancestors_tokens<'a, T>(self, arena: &'a Arena<T>)
585 -> AncestorTokens<'a, T> {
586 let parent = match arena.get(self) {
587 Some(n) => n.parent,
588 None => panic!("Invalid token")
589 };
590 AncestorTokens { arena, node_token: parent }
591 }
592
593 /// Returns an iterator of tokens of siblings preceding the current node.
594 ///
595 /// # Panics:
596 ///
597 /// Panics if the token does not correspond to a node in the arena.
598 ///
599 /// # Examples:
600 ///
601 /// ```
602 /// use atree::Arena;
603 ///
604 /// let root_data = "Indo-European";
605 /// let (mut arena, root_token) = Arena::with_data(root_data);
606 ///
607 /// let first_child_token = root_token.append(&mut arena, "Germanic");
608 /// let second_child_token = root_token.append(&mut arena, "Romance");
609 /// let third_child_token = root_token.append(&mut arena, "Slavic");
610 /// root_token.append(&mut arena, "Hellenic");
611 ///
612 /// let mut sibling_tokens = third_child_token.preceding_siblings_tokens(&arena);
613 /// assert_eq!(sibling_tokens.next(), Some(second_child_token));
614 /// assert_eq!(sibling_tokens.next(), Some(first_child_token));
615 /// assert!(sibling_tokens.next().is_none());
616 /// ```
617 pub fn preceding_siblings_tokens<'a, T>(self, arena: &'a Arena<T>)
618 -> PrecedingSiblingTokens<'a, T> {
619 let previous_sibling = match arena.get(self) {
620 Some(n) => n.previous_sibling,
621 None => panic!("Invalid token")
622 };
623 PrecedingSiblingTokens { arena, node_token: previous_sibling }
624 }
625
626 /// Returns an iterator of tokens of siblings following the current node.
627 ///
628 /// # Panics:
629 ///
630 /// Panics if the token does not correspond to a node in the arena.
631 ///
632 /// # Examples:
633 ///
634 /// ```
635 /// use atree::Arena;
636 ///
637 /// let root_data = "Indo-European";
638 /// let (mut arena, root_token) = Arena::with_data(root_data);
639 ///
640 /// root_token.append(&mut arena, "Romance");
641 /// let second_child_token = root_token.append(&mut arena, "Germanic");
642 /// let third_child_token = root_token.append(&mut arena, "Slavic");
643 /// let fourth_child_token = root_token.append(&mut arena, "Hellenic");
644 ///
645 /// let mut sibling_tokens = second_child_token.following_siblings_tokens(&arena);
646 /// assert_eq!(sibling_tokens.next(), Some(third_child_token));
647 /// assert_eq!(sibling_tokens.next(), Some(fourth_child_token));
648 /// assert!(sibling_tokens.next().is_none());
649 /// ```
650 pub fn following_siblings_tokens<'a, T>(self, arena: &'a Arena<T>)
651 -> FollowingSiblingTokens<'a, T> {
652 let next_sibling = match arena.get(self) {
653 Some(n) => n.next_sibling,
654 None => panic!("Invalid token")
655 };
656 FollowingSiblingTokens { arena, node_token: next_sibling }
657 }
658
659 /// Returns an iterator of tokens of child nodes in the order of insertion.
660 ///
661 /// # Panics:
662 ///
663 /// Panics if the token does not correspond to a node in the arena.
664 ///
665 /// # Examples:
666 ///
667 /// ```
668 /// use atree::Arena;
669 ///
670 /// let root_data = "Indo-European";
671 /// let (mut arena, root_token) = Arena::with_data(root_data);
672 ///
673 /// let first_child_token = root_token.append(&mut arena, "Romance");
674 /// let second_child_token = root_token.append(&mut arena, "Germanic");
675 /// let third_child_token = root_token.append(&mut arena, "Slavic");
676 /// let fourth_child_token = root_token.append(&mut arena, "Hellenic");
677 ///
678 /// let mut children_tokens = root_token.children_tokens(&arena);
679 /// assert_eq!(children_tokens.next(), Some(first_child_token));
680 /// assert_eq!(children_tokens.next(), Some(second_child_token));
681 /// assert_eq!(children_tokens.next(), Some(third_child_token));
682 /// assert_eq!(children_tokens.next(), Some(fourth_child_token));
683 /// assert!(children_tokens.next().is_none());
684 /// ```
685 pub fn children_tokens<'a, T>(self, arena: &'a Arena<T>)
686 -> ChildrenTokens<'a, T> {
687 let first_child = match arena.get(self) {
688 Some(n) => n.first_child,
689 None => panic!("Invalid token")
690 };
691 ChildrenTokens { arena, node_token: first_child }
692 }
693
694 /// Returns an iterator of references of ancestor nodes.
695 ///
696 /// # Panics:
697 ///
698 /// Panics if the token does not correspond to a node in the arena.
699 ///
700 /// # Examples:
701 ///
702 /// ```
703 /// use atree::Arena;
704 ///
705 /// let root_data = "Indo-European";
706 /// let (mut arena, root_token) = Arena::with_data(root_data);
707 ///
708 /// let child_token = root_token.append(&mut arena, "Germanic");
709 /// let grandchild_token = child_token.append(&mut arena, "Swedish");
710 /// let mut ancestors = grandchild_token.ancestors(&arena);
711 ///
712 /// assert_eq!(ancestors.next().unwrap().data, "Germanic");
713 /// assert_eq!(ancestors.next().unwrap().data, "Indo-European");
714 /// assert!(ancestors.next().is_none());
715 /// ```
716 pub fn ancestors<'a, T>(self, arena: &'a Arena<T>) -> Ancestors<'a, T> {
717 Ancestors { token_iter: self.ancestors_tokens(arena) }
718 }
719
720 /// Returns an iterator of references of sibling nodes preceding the current
721 /// node.
722 ///
723 /// # Panics:
724 ///
725 /// Panics if the token does not correspond to a node in the arena.
726 ///
727 /// # Examples:
728 ///
729 /// ```
730 /// use atree::Arena;
731 ///
732 /// let root_data = "Indo-European";
733 /// let (mut arena, root_token) = Arena::with_data(root_data);
734 ///
735 /// root_token.append(&mut arena, "Romance");
736 /// root_token.append(&mut arena, "Germanic");
737 /// let third_child_token = root_token.append(&mut arena, "Slavic");
738 /// root_token.append(&mut arena, "Celtic");
739 ///
740 /// let mut siblings = third_child_token.preceding_siblings(&arena);
741 /// assert_eq!(siblings.next().unwrap().data, "Germanic");
742 /// assert_eq!(siblings.next().unwrap().data, "Romance");
743 /// assert!(siblings.next().is_none());
744 /// ```
745 pub fn preceding_siblings<'a, T>(self, arena: &'a Arena<T>)
746 -> PrecedingSiblings<'a, T> {
747 PrecedingSiblings { token_iter: self.preceding_siblings_tokens(arena) }
748 }
749
750 /// Returns an iterator of references of sibling nodes following the current
751 /// node.
752 ///
753 /// # Panics:
754 ///
755 /// Panics if the token does not correspond to a node in the arena.
756 ///
757 /// # Examples:
758 ///
759 /// ```
760 /// use atree::Arena;
761 ///
762 /// let root_data = "Indo-European";
763 /// let (mut arena, root_token) = Arena::with_data(root_data);
764 ///
765 /// root_token.append(&mut arena, "Romance");
766 /// let second_child_token = root_token.append(&mut arena, "Germanic");
767 /// root_token.append(&mut arena, "Slavic");
768 /// root_token.append(&mut arena, "Hellenic");
769 ///
770 /// let mut siblings = second_child_token.following_siblings(&arena);
771 /// assert_eq!(siblings.next().unwrap().data, "Slavic");
772 /// assert_eq!(siblings.next().unwrap().data, "Hellenic");
773 /// assert!(siblings.next().is_none());
774 /// ```
775 pub fn following_siblings<'a, T>(self, arena: &'a Arena<T>)
776 -> FollowingSiblings<'a, T> {
777 FollowingSiblings { token_iter: self.following_siblings_tokens(arena) }
778 }
779
780 /// Returns an iterator of child node references in the order of insertion.
781 ///
782 /// # Panics:
783 ///
784 /// Panics if the token does not correspond to a node in the arena.
785 ///
786 /// # Examples:
787 ///
788 /// ```
789 /// use atree::Arena;
790 ///
791 /// let root_data = "Indo-European";
792 /// let (mut arena, root_token) = Arena::with_data(root_data);
793 ///
794 /// let first_child_token = root_token.append(&mut arena, "Germanic");
795 /// let second_child_token = root_token.append(&mut arena, "Romance");
796 /// let third_child_token = root_token.append(&mut arena, "Slavic");
797 /// let fourth_child_token = root_token.append(&mut arena, "Celtic");
798 ///
799 /// let mut children = root_token.children(&arena);
800 /// assert_eq!(children.next().unwrap().data, "Germanic");
801 /// assert_eq!(children.next().unwrap().data, "Romance");
802 /// assert_eq!(children.next().unwrap().data, "Slavic");
803 /// assert_eq!(children.next().unwrap().data, "Celtic");
804 /// assert!(children.next().is_none());
805 /// ```
806 pub fn children<'a, T>(self, arena: &'a Arena<T>) -> Children<'a, T> {
807 Children { token_iter: self.children_tokens(arena) }
808 }
809
810 /// Returns an iterator of mutable ancestor node references.
811 ///
812 /// # Panics:
813 ///
814 /// Panics if the token does not correspond to a node in the arena.
815 ///
816 /// # Examples:
817 ///
818 /// ```
819 /// use atree::Arena;
820 ///
821 /// let root_data = 1usize;
822 /// let (mut arena, root_token) = Arena::with_data(root_data);
823 ///
824 /// let child_token = root_token.append(&mut arena, 2usize);
825 /// let grandchild_token = child_token.append(&mut arena, 3usize);
826 /// let great_grandchild_token = grandchild_token.append(&mut arena, 4usize);
827 /// let ggreat_grandchild_token = great_grandchild_token.append(&mut arena, 5usize);
828 ///
829 /// for x in ggreat_grandchild_token.ancestors_mut(&mut arena) {
830 /// x.data += 2;
831 /// }
832 ///
833 /// let mut ancestors = ggreat_grandchild_token.ancestors(&arena);
834 /// assert_eq!(ancestors.next().unwrap().data, 6usize);
835 /// assert_eq!(ancestors.next().unwrap().data, 5usize);
836 /// assert_eq!(ancestors.next().unwrap().data, 4usize);
837 /// assert_eq!(ancestors.next().unwrap().data, 3usize);
838 /// assert!(ancestors.next().is_none());
839 /// ```
840 pub fn ancestors_mut<'a, T>(self, arena: &'a mut Arena<T>)
841 -> AncestorsMut<'a, T> {
842 AncestorsMut {
843 arena: arena as *mut Arena<T>,
844 node_token: Some(self),
845 marker: PhantomData::default()
846 }
847 }
848
849 /// Returns an iterator of mutable references of sibling nodes that follow
850 /// the current node.
851 ///
852 /// # Panics:
853 ///
854 /// Panics if the token does not correspond to a node in the arena.
855 ///
856 /// # Examples:
857 ///
858 /// ```
859 /// use atree::Arena;
860 ///
861 /// let root_data = 1usize;
862 /// let (mut arena, root_token) = Arena::with_data(root_data);
863 ///
864 /// root_token.append(&mut arena, 2usize);
865 /// let second_child_token = root_token.append(&mut arena, 3usize);
866 /// root_token.append(&mut arena, 4usize);
867 /// root_token.append(&mut arena, 5usize);
868 ///
869 /// for x in second_child_token.following_siblings_mut(&mut arena) {
870 /// x.data += 2;
871 /// }
872 ///
873 /// let mut children = root_token.children(&arena);
874 /// assert_eq!(children.next().unwrap().data, 2usize);
875 /// assert_eq!(children.next().unwrap().data, 3usize);
876 /// assert_eq!(children.next().unwrap().data, 6usize);
877 /// assert_eq!(children.next().unwrap().data, 7usize);
878 /// assert!(children.next().is_none());
879 /// ```
880 pub fn following_siblings_mut<'a, T>(self, arena: &'a mut Arena<T>)
881 -> FollowingSiblingsMut<'a, T> {
882 let next_sibling = match arena.get(self) {
883 Some(n) => n.next_sibling,
884 None => panic!("Invalid token")
885 };
886 FollowingSiblingsMut {
887 arena: arena as *mut Arena<T>,
888 node_token: next_sibling,
889 marker: PhantomData::default()
890 }
891 }
892
893 /// Returns an iterator of mutable references of sibling nodes that precede
894 /// the current node.
895 ///
896 /// # Panics:
897 ///
898 /// Panics if the token does not correspond to a node in the arena.
899 ///
900 /// # Examples:
901 ///
902 /// ```
903 /// use atree::Arena;
904 ///
905 /// let root_data = 1usize;
906 /// let (mut arena, root_token) = Arena::with_data(root_data);
907 ///
908 /// root_token.append(&mut arena, 2usize);
909 /// root_token.append(&mut arena, 3usize);
910 /// root_token.append(&mut arena, 4usize);
911 /// let fourth_child_token = root_token.append(&mut arena, 5usize);
912 ///
913 /// for x in fourth_child_token.preceding_siblings_mut(&mut arena) {
914 /// x.data += 5;
915 /// }
916 ///
917 /// let mut children = root_token.children(&arena);
918 /// assert_eq!(children.next().unwrap().data, 7usize);
919 /// assert_eq!(children.next().unwrap().data, 8usize);
920 /// assert_eq!(children.next().unwrap().data, 9usize);
921 /// assert_eq!(children.next().unwrap().data, 5usize);
922 /// assert!(children.next().is_none());
923 /// ```
924 pub fn preceding_siblings_mut<'a, T>(self, arena: &'a mut Arena<T>)
925 -> PrecedingSiblingsMut<'a, T> {
926 let previous_sibling = match arena.get(self) {
927 Some(n) => n.previous_sibling,
928 None => panic!("Invalid token")
929 };
930 PrecedingSiblingsMut {
931 arena: arena as *mut Arena<T>,
932 node_token: previous_sibling,
933 marker: PhantomData::default()
934 }
935 }
936
937 /// Returns an iterator of mutable references of child nodes in the order of
938 /// insertion.
939 ///
940 /// # Panics:
941 ///
942 /// Panics if the token does not correspond to a node in the arena.
943 ///
944 /// # Examples:
945 ///
946 /// ```
947 /// use atree::Arena;
948 ///
949 /// let root_data = 1usize;
950 /// let (mut arena, root_token) = Arena::with_data(root_data);
951 ///
952 /// root_token.append(&mut arena, 2usize);
953 /// root_token.append(&mut arena, 3usize);
954 /// let third_child_token = root_token.append(&mut arena, 4usize);
955 /// root_token.append(&mut arena, 5usize);
956 /// let grandchild = third_child_token.append(&mut arena, 10usize);
957 ///
958 /// for x in root_token.children_mut(&mut arena) {
959 /// x.data += 10;
960 /// }
961 ///
962 /// let mut children = root_token.children(&arena);
963 /// assert_eq!(children.next().unwrap().data, 12);
964 /// assert_eq!(children.next().unwrap().data, 13);
965 /// assert_eq!(children.next().unwrap().data, 14);
966 /// assert_eq!(children.next().unwrap().data, 15);
967 /// assert_eq!(arena.get(grandchild).unwrap().data, 10);
968 /// assert!(children.next().is_none());
969 /// ```
970 pub fn children_mut<'a, T>(self, arena: &'a mut Arena<T>)
971 -> ChildrenMut<'a, T> {
972 let first_child = match arena.get(self) {
973 Some(n) => n.first_child,
974 None => panic!("Invalid token")
975 };
976 ChildrenMut {
977 arena: arena as *mut Arena<T>,
978 node_token: first_child,
979 marker: PhantomData::default()
980 }
981 }
982
983 /// Returns an iterator of tokens of subtree nodes of the given node.
984 ///
985 /// # Panics:
986 ///
987 /// Panics if the token does not correspond to a node in the arena.
988 ///
989 /// # Examples:
990 ///
991 /// ```
992 /// use atree::Arena;
993 /// use atree::iter::TraversalOrder;
994 ///
995 /// let root_data = "Indo-European";
996 /// let (mut arena, root_token) = Arena::with_data(root_data);
997 ///
998 /// let first_child = root_token.append(&mut arena, "Romance");
999 /// let second_child = root_token.append(&mut arena, "Germanic");
1000 /// let third_child = root_token.append(&mut arena, "Slavic");
1001 /// let first_grandchild = second_child.append(&mut arena, "English");
1002 /// let second_grandchild = second_child.append(&mut arena, "Icelandic");
1003 /// let fourth_child = root_token.append(&mut arena, "Celtic");
1004 ///
1005 /// let mut subtree = root_token.subtree_tokens(&arena, TraversalOrder::Pre);
1006 /// assert_eq!(subtree.next(), Some(root_token));
1007 /// assert_eq!(subtree.next(), Some(first_child));
1008 /// assert_eq!(subtree.next(), Some(second_child));
1009 /// assert_eq!(subtree.next(), Some(first_grandchild));
1010 /// assert_eq!(subtree.next(), Some(second_grandchild));
1011 /// assert_eq!(subtree.next(), Some(third_child));
1012 /// assert_eq!(subtree.next(), Some(fourth_child));
1013 /// assert!(subtree.next().is_none());
1014 ///
1015 /// let mut subtree = second_grandchild.subtree_tokens(&arena, TraversalOrder::Pre);
1016 /// assert_eq!(subtree.next(), Some(second_grandchild));
1017 /// assert!(subtree.next().is_none());
1018 /// ```
1019 pub fn subtree_tokens<'a, T>(self, arena: &'a Arena<T>, order: TraversalOrder)
1020 -> SubtreeTokens<'a, T> {
1021 let preord_tokens_next = |iter: &mut SubtreeTokens<T>|
1022 depth_first_tokens_next(iter, preorder_next);
1023 let postord_tokens_next = |iter: &mut SubtreeTokens<T>|
1024 depth_first_tokens_next(iter, postorder_next);
1025 match order {
1026 TraversalOrder::Pre => SubtreeTokens {
1027 arena,
1028 subtree_root: self,
1029 node_token: Some(self),
1030 branch: Branch::Child,
1031 curr_level: VecDeque::new(), // unused field
1032 next_level: VecDeque::new(), // unused field
1033 next: preord_tokens_next
1034 },
1035 TraversalOrder::Post => {
1036 let (node_token, branch) =
1037 postorder_next(self, self, Branch::Child, arena);
1038 SubtreeTokens {
1039 arena,
1040 subtree_root: self,
1041 node_token,
1042 branch,
1043 curr_level: VecDeque::new(), // unused field
1044 next_level: VecDeque::new(), // unused field
1045 next: postord_tokens_next
1046 }
1047 },
1048 TraversalOrder::Level => {
1049 SubtreeTokens {
1050 arena,
1051 subtree_root: self, // unused field
1052 node_token: None, // unused field
1053 branch: Branch::None, // unused field
1054 curr_level: std::iter::once(self).collect(),
1055 next_level: VecDeque::new(),
1056 next: breadth_first_tokens_next
1057 }
1058 }
1059 }
1060 }
1061
1062 /// Returns an iterator of references of subtree nodes of the given node.
1063 ///
1064 /// # Panics:
1065 ///
1066 /// Panics if the token does not correspond to a node in the arena.
1067 ///
1068 /// # Examples:
1069 ///
1070 /// ```
1071 /// use atree::Arena;
1072 /// use atree::iter::TraversalOrder;
1073 ///
1074 /// let root_data = "Indo-European";
1075 /// let (mut arena, root_token) = Arena::with_data(root_data);
1076 ///
1077 /// root_token.append(&mut arena, "Romance");
1078 /// root_token.append(&mut arena, "Germanic");
1079 /// let third_child = root_token.append(&mut arena, "Slavic");
1080 /// root_token.append(&mut arena, "Celtic");
1081 /// third_child.append(&mut arena, "Polish");
1082 /// third_child.append(&mut arena, "Slovakian");
1083 ///
1084 /// let mut subtree = root_token.subtree(&arena, TraversalOrder::Pre);
1085 /// assert_eq!(subtree.next().unwrap().data, "Indo-European");
1086 /// assert_eq!(subtree.next().unwrap().data, "Romance");
1087 /// assert_eq!(subtree.next().unwrap().data, "Germanic");
1088 /// assert_eq!(subtree.next().unwrap().data, "Slavic");
1089 /// assert_eq!(subtree.next().unwrap().data, "Polish");
1090 /// assert_eq!(subtree.next().unwrap().data, "Slovakian");
1091 /// assert_eq!(subtree.next().unwrap().data, "Celtic");
1092 /// assert!(subtree.next().is_none());
1093 /// ```
1094 pub fn subtree<'a, T>(self, arena: &'a Arena<T>, order: TraversalOrder)
1095 -> Subtree<'a, T> {
1096 Subtree {
1097 arena,
1098 iter: self.subtree_tokens(arena, order)
1099 }
1100 }
1101
1102 /// Returns an iterator of mutable references of subtree nodes of the given
1103 /// node.
1104 ///
1105 /// # Panics:
1106 ///
1107 /// Panics if the token does not correspond to a node in the arena.
1108 ///
1109 /// # Examples:
1110 ///
1111 /// ```
1112 /// use atree::Arena;
1113 /// use atree::iter::TraversalOrder;
1114 ///
1115 /// let root_data = 1usize;
1116 /// let (mut arena, root_token) = Arena::with_data(root_data);
1117 ///
1118 /// root_token.append(&mut arena, 2usize);
1119 /// root_token.append(&mut arena, 3usize);
1120 /// let third_child = root_token.append(&mut arena, 4usize);
1121 /// root_token.append(&mut arena, 5usize);
1122 /// third_child.append(&mut arena, 10usize);
1123 /// third_child.append(&mut arena, 20usize);
1124 ///
1125 /// for x in root_token.subtree_mut(&mut arena, TraversalOrder::Pre) {
1126 /// x.data += 100;
1127 /// }
1128 ///
1129 /// let mut subtree = root_token.subtree(&arena, TraversalOrder::Pre);
1130 /// assert_eq!(subtree.next().unwrap().data, 101);
1131 /// assert_eq!(subtree.next().unwrap().data, 102);
1132 /// assert_eq!(subtree.next().unwrap().data, 103);
1133 /// assert_eq!(subtree.next().unwrap().data, 104);
1134 /// assert_eq!(subtree.next().unwrap().data, 110);
1135 /// assert_eq!(subtree.next().unwrap().data, 120);
1136 /// assert_eq!(subtree.next().unwrap().data, 105);
1137 /// assert!(subtree.next().is_none());
1138 /// ```
1139 pub fn subtree_mut<'a, T>(self, arena: &'a mut Arena<T>, order: TraversalOrder)
1140 -> SubtreeMut<'a, T> {
1141 SubtreeMut {
1142 arena: arena as *mut Arena<T>,
1143 iter: self.subtree_tokens(arena, order),
1144 marker: PhantomData::default()
1145 }
1146 }
1147
1148 /// Removes all descendants of the current node.
1149 pub (crate) fn remove_descendants<T>(self, arena: &mut Arena<T>) {
1150 // This will not silently fail since postorder_next will panic if self
1151 // isn't valid. This won't do anything if self has no descendants, but
1152 // that's the intended behavior.
1153 if let (Some(mut token), mut branch) =
1154 postorder_next(self, self, Branch::Child, arena) {
1155 while branch != Branch::None {
1156 let (t, b) = postorder_next(token, self, branch, arena);
1157 arena.allocator.remove(token); // should not fail (not here anyway)
1158 token = t.unwrap();
1159 branch = b;
1160 }
1161 arena[self].first_child = None;
1162 }
1163 }
1164}
1165
1166#[cfg(test)]
1167mod test {
1168 use super::*;
1169
1170 #[test]
1171 #[allow(clippy::cognitive_complexity)]
1172 fn replace_node() {
1173 // root node that we will attach subtrees to
1174 let root_data = "Indo-European";
1175 let (mut arena, root) = Arena::with_data(root_data);
1176
1177 // the Germanic branch
1178 let germanic = root.append(&mut arena, "Germanic");
1179 let west = germanic.append(&mut arena, "West");
1180 west.append(&mut arena, "Scots");
1181 west.append(&mut arena, "English");
1182
1183 // the slavic branch
1184 let slavic = root.append(&mut arena, "Slavic");
1185 slavic.append(&mut arena, "Polish");
1186 slavic.append(&mut arena, "Russian");
1187
1188 let mut iter = root.subtree(&arena, TraversalOrder::Pre)
1189 .map(|x| x.data);
1190 assert_eq!(iter.next(), Some("Indo-European"));
1191 assert_eq!(iter.next(), Some("Germanic"));
1192 assert_eq!(iter.next(), Some("West"));
1193 assert_eq!(iter.next(), Some("Scots"));
1194 assert_eq!(iter.next(), Some("English"));
1195 assert_eq!(iter.next(), Some("Slavic"));
1196 assert_eq!(iter.next(), Some("Polish"));
1197 assert_eq!(iter.next(), Some("Russian"));
1198 assert!(iter.next().is_none());
1199
1200 // the Romance branch
1201 let romance = arena.new_node("Romance");
1202 romance.append(&mut arena, "French");
1203 romance.append(&mut arena, "Italian");
1204
1205 // replace_node germanic with romance
1206 germanic.replace_node(&mut arena, romance).unwrap();
1207
1208 let mut iter = root.subtree(&arena, TraversalOrder::Pre)
1209 .map(|x| x.data);
1210 assert_eq!(iter.next(), Some("Indo-European"));
1211 assert_eq!(iter.next(), Some("Romance"));
1212 assert_eq!(iter.next(), Some("French"));
1213 assert_eq!(iter.next(), Some("Italian"));
1214 assert_eq!(iter.next(), Some("Slavic"));
1215 assert_eq!(iter.next(), Some("Polish"));
1216 assert_eq!(iter.next(), Some("Russian"));
1217 assert!(iter.next().is_none());
1218
1219 // How about the other way around (replacing the slavic branch instead
1220 slavic.replace_node(&mut arena, germanic).unwrap();
1221
1222 let mut iter = root.subtree(&arena, TraversalOrder::Pre)
1223 .map(|x| x.data);
1224 assert_eq!(iter.next(), Some("Indo-European"));
1225 assert_eq!(iter.next(), Some("Romance"));
1226 assert_eq!(iter.next(), Some("French"));
1227 assert_eq!(iter.next(), Some("Italian"));
1228 assert_eq!(iter.next(), Some("Germanic"));
1229 assert_eq!(iter.next(), Some("West"));
1230 assert_eq!(iter.next(), Some("Scots"));
1231 assert_eq!(iter.next(), Some("English"));
1232 assert!(iter.next().is_none());
1233 }
1234
1235 #[test]
1236 fn subtree_tokens_postord() {
1237 let root_data = 1usize;
1238 let (mut arena, root_token) = Arena::with_data(root_data);
1239
1240 let first_child = root_token.append(&mut arena, 2usize);
1241 let second_child = root_token.append(&mut arena, 3usize);
1242 let third_child = root_token.append(&mut arena, 4usize);
1243 let first_grandchild = first_child.append(&mut arena, 0usize);
1244 let fourth_child = root_token.append(&mut arena, 5usize);
1245 let second_grandchild = second_child.append(&mut arena, 10usize);
1246 let third_grandchild = second_child.append(&mut arena, 20usize);
1247 let great_grandchild = third_grandchild.append(&mut arena, 20usize);
1248
1249 let mut subtree = root_token.subtree_tokens(&arena, TraversalOrder::Post);
1250 assert_eq!(subtree.next(), Some(first_grandchild));
1251 assert_eq!(subtree.next(), Some(first_child));
1252 assert_eq!(subtree.next(), Some(second_grandchild));
1253 assert_eq!(subtree.next(), Some(great_grandchild));
1254 assert_eq!(subtree.next(), Some(third_grandchild));
1255 assert_eq!(subtree.next(), Some(second_child));
1256 assert_eq!(subtree.next(), Some(third_child));
1257 assert_eq!(subtree.next(), Some(fourth_child));
1258 assert_eq!(subtree.next(), Some(root_token));
1259 assert!(subtree.next().is_none());
1260
1261 let mut subtree = great_grandchild.subtree_tokens(&arena, TraversalOrder::Post);
1262 assert_eq!(subtree.next(), Some(great_grandchild));
1263 assert!(subtree.next().is_none());
1264 }
1265
1266 #[test]
1267 fn subtree_tokens_levelord() {
1268 let root_data = 1usize;
1269 let (mut arena, root_token) = Arena::with_data(root_data);
1270
1271 let first_child = root_token.append(&mut arena, 2usize);
1272 let second_child = root_token.append(&mut arena, 3usize);
1273 let third_child = root_token.append(&mut arena, 4usize);
1274 let first_grandchild = second_child.append(&mut arena, 10usize);
1275 let second_grandchild = second_child.append(&mut arena, 20usize);
1276 let fourth_child = root_token.append(&mut arena, 5usize);
1277
1278 let mut subtree = root_token.subtree_tokens(&arena, TraversalOrder::Level);
1279 assert_eq!(subtree.next(), Some(root_token));
1280 assert_eq!(subtree.next(), Some(first_child));
1281 assert_eq!(subtree.next(), Some(second_child));
1282 assert_eq!(subtree.next(), Some(third_child));
1283 assert_eq!(subtree.next(), Some(fourth_child));
1284 assert_eq!(subtree.next(), Some(first_grandchild));
1285 assert_eq!(subtree.next(), Some(second_grandchild));
1286 assert!(subtree.next().is_none());
1287
1288 let mut subtree = second_grandchild.subtree_tokens(&arena, TraversalOrder::Level);
1289 assert_eq!(subtree.next(), Some(second_grandchild));
1290 assert!(subtree.next().is_none());
1291 }
1292
1293 #[test]
1294 fn subtree_postord() {
1295 let root_data = "Indo-European";
1296 let (mut arena, root_token) = Arena::with_data(root_data);
1297
1298 root_token.append(&mut arena, "Romance");
1299 root_token.append(&mut arena, "Germanic");
1300 let third_child = root_token.append(&mut arena, "Celtic");
1301 root_token.append(&mut arena, "Slavic");
1302 third_child.append(&mut arena, "Ulster");
1303 third_child.append(&mut arena, "Gaulish");
1304
1305 let mut subtree = root_token.subtree(&arena, TraversalOrder::Post);
1306 assert_eq!(subtree.next().unwrap().data, "Romance");
1307 assert_eq!(subtree.next().unwrap().data, "Germanic");
1308 assert_eq!(subtree.next().unwrap().data, "Ulster");
1309 assert_eq!(subtree.next().unwrap().data, "Gaulish");
1310 assert_eq!(subtree.next().unwrap().data, "Celtic");
1311 assert_eq!(subtree.next().unwrap().data, "Slavic");
1312 assert_eq!(subtree.next().unwrap().data, "Indo-European");
1313 assert!(subtree.next().is_none());
1314 }
1315
1316 #[test]
1317 fn subtree_levelord() {
1318 let root_data = "Indo-European";
1319 let (mut arena, root_token) = Arena::with_data(root_data);
1320
1321 root_token.append(&mut arena, "Romance");
1322 root_token.append(&mut arena, "Germanic");
1323 let third_child = root_token.append(&mut arena, "Slavic");
1324 root_token.append(&mut arena, "Hellenic");
1325 third_child.append(&mut arena, "Russian");
1326 third_child.append(&mut arena, "Ukrainian");
1327
1328 let mut subtree = root_token.subtree(&arena, TraversalOrder::Level);
1329 assert_eq!(subtree.next().unwrap().data, "Indo-European");
1330 assert_eq!(subtree.next().unwrap().data, "Romance");
1331 assert_eq!(subtree.next().unwrap().data, "Germanic");
1332 assert_eq!(subtree.next().unwrap().data, "Slavic");
1333 assert_eq!(subtree.next().unwrap().data, "Hellenic");
1334 assert_eq!(subtree.next().unwrap().data, "Russian");
1335 assert_eq!(subtree.next().unwrap().data, "Ukrainian");
1336 assert!(subtree.next().is_none());
1337 }
1338
1339 #[test]
1340 fn subtree_postord_mut() {
1341 let root_data = 1usize;
1342 let (mut arena, root_token) = Arena::with_data(root_data);
1343
1344 root_token.append(&mut arena, 2usize);
1345 root_token.append(&mut arena, 3usize);
1346 let third_child = root_token.append(&mut arena, 4usize);
1347 root_token.append(&mut arena, 5usize);
1348 third_child.append(&mut arena, 10usize);
1349 third_child.append(&mut arena, 20usize);
1350
1351 for x in root_token.subtree_mut(&mut arena, TraversalOrder::Post) {
1352 x.data += 100;
1353 }
1354
1355 let mut subtree = root_token.subtree(&arena, TraversalOrder::Post);
1356 assert_eq!(subtree.next().unwrap().data, 102);
1357 assert_eq!(subtree.next().unwrap().data, 103);
1358 assert_eq!(subtree.next().unwrap().data, 110);
1359 assert_eq!(subtree.next().unwrap().data, 120);
1360 assert_eq!(subtree.next().unwrap().data, 104);
1361 assert_eq!(subtree.next().unwrap().data, 105);
1362 assert_eq!(subtree.next().unwrap().data, 101);
1363 assert!(subtree.next().is_none());
1364 }
1365
1366 #[test]
1367 fn subtree_levelord_mut() {
1368 let root_data = 1usize;
1369 let (mut arena, root_token) = Arena::with_data(root_data);
1370
1371 root_token.append(&mut arena, 2usize);
1372 root_token.append(&mut arena, 3usize);
1373 let third_child = root_token.append(&mut arena, 4usize);
1374 root_token.append(&mut arena, 5usize);
1375 third_child.append(&mut arena, 10usize);
1376 third_child.append(&mut arena, 20usize);
1377
1378 for x in root_token.subtree_mut(&mut arena, TraversalOrder::Level) {
1379 x.data += 100;
1380 }
1381
1382 let mut subtree = root_token.subtree(&arena, TraversalOrder::Level);
1383 assert_eq!(subtree.next().unwrap().data, 101);
1384 assert_eq!(subtree.next().unwrap().data, 102);
1385 assert_eq!(subtree.next().unwrap().data, 103);
1386 assert_eq!(subtree.next().unwrap().data, 104);
1387 assert_eq!(subtree.next().unwrap().data, 105);
1388 assert_eq!(subtree.next().unwrap().data, 110);
1389 assert_eq!(subtree.next().unwrap().data, 120);
1390 assert!(subtree.next().is_none());
1391 }
1392
1393 #[test]
1394 fn remove_descendants() {
1395 let root_data = 1usize;
1396 let (mut arena, root_token) = Arena::with_data(root_data);
1397
1398 let first_child = root_token.append(&mut arena, 2usize);
1399 let second_child = root_token.append(&mut arena, 3usize);
1400 let third_child = root_token.append(&mut arena, 4usize);
1401 let fourth_child = root_token.append(&mut arena, 5usize);
1402 let grandchild_1 = third_child.append(&mut arena, 10usize);
1403 third_child.append(&mut arena, 20usize);
1404 grandchild_1.append(&mut arena, 100usize);
1405
1406 assert_eq!(arena.node_count(), 8);
1407
1408 third_child.remove_descendants(&mut arena);
1409
1410 let mut subtree = root_token.subtree_tokens(&arena, TraversalOrder::Pre);
1411 assert_eq!(subtree.next(), Some(root_token));
1412 assert_eq!(subtree.next(), Some(first_child));
1413 assert_eq!(subtree.next(), Some(second_child));
1414 assert_eq!(subtree.next(), Some(third_child));
1415 assert_eq!(subtree.next(), Some(fourth_child));
1416 assert!(subtree.next().is_none());
1417
1418 println!("{:?}", arena.allocator);
1419 assert_eq!(arena.node_count(), 5);
1420 }
1421}