1use std::fmt;
15use std::cell::{RefCell, Ref, RefMut};
16use std::rc::{Rc, Weak};
17
18type Link<T> = Rc<RefCell<NodeData<T>>>;
19type WeakLink<T> = Weak<RefCell<NodeData<T>>>;
20
21pub struct Node<T>(Link<T>);
28
29struct NodeData<T> {
30 root: Option<WeakLink<T>>,
31 parent: Option<WeakLink<T>>,
32 first_child: Option<Link<T>>,
33 last_child: Option<WeakLink<T>>,
34 previous_sibling: Option<WeakLink<T>>,
35 next_sibling: Option<Link<T>>,
36 data: T,
37}
38
39impl<T> Clone for Node<T> {
41 fn clone(&self) -> Self {
42 Node(Rc::clone(&self.0))
43 }
44}
45
46impl<T> PartialEq for Node<T> {
47 fn eq(&self, other: &Node<T>) -> bool {
48 Rc::ptr_eq(&self.0, &other.0)
49 }
50}
51
52impl<T: fmt::Debug> fmt::Debug for Node<T> {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 fmt::Debug::fmt(&*self.borrow(), f)
55 }
56}
57
58impl<T: fmt::Display> fmt::Display for Node<T> {
59 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60 fmt::Display::fmt(&*self.borrow(), f)
61 }
62}
63
64
65macro_rules! try_opt {
66 ($expr: expr) => {
67 match $expr {
68 Some(value) => value,
69 None => return None
70 }
71 }
72}
73
74
75impl<T> Node<T> {
76 pub(crate) fn new(data: T) -> Node<T> {
78 Node(Rc::new(RefCell::new(NodeData {
79 root: None,
80 parent: None,
81 first_child: None,
82 last_child: None,
83 previous_sibling: None,
84 next_sibling: None,
85 data,
86 })))
87 }
88
89 pub fn root(&self) -> Node<T> {
97 match self.0.borrow().root.as_ref() {
98 Some(v) => Node(v.upgrade().unwrap()),
99 None => self.clone(),
100 }
101 }
102
103 pub fn parent(&self) -> Option<Node<T>> {
109 Some(Node(try_opt!(try_opt!(self.0.borrow().parent.as_ref()).upgrade())))
110 }
111
112 pub fn first_child(&self) -> Option<Node<T>> {
118 Some(Node(try_opt!(self.0.borrow().first_child.as_ref()).clone()))
119 }
120
121 pub fn last_child(&self) -> Option<Node<T>> {
127 Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade())))
128 }
129
130 pub fn previous_sibling(&self) -> Option<Node<T>> {
136 Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade())))
137 }
138
139 pub fn next_sibling(&self) -> Option<Node<T>> {
145 Some(Node(try_opt!(self.0.borrow().next_sibling.as_ref()).clone()))
146 }
147
148 pub(crate) fn borrow(&self) -> Ref<T> {
154 Ref::map(self.0.borrow(), |v| &v.data)
155 }
156
157 pub(crate) fn borrow_mut(&mut self) -> RefMut<T> {
163 RefMut::map(self.0.borrow_mut(), |v| &mut v.data)
164 }
165
166 pub fn ancestors(&self) -> Ancestors<T> {
170 Ancestors(Some(self.clone()))
171 }
172
173 pub fn preceding_siblings(&self) -> PrecedingSiblings<T> {
177 PrecedingSiblings(Some(self.clone()))
178 }
179
180 pub fn following_siblings(&self) -> FollowingSiblings<T> {
184 FollowingSiblings(Some(self.clone()))
185 }
186
187 pub fn children(&self) -> Children<T> {
193 Children {
194 next: self.first_child(),
195 next_back: self.last_child(),
196 }
197 }
198
199 pub fn has_children(&self) -> bool {
205 self.first_child().is_some()
206 }
207
208 pub fn descendants(&self) -> Descendants<T> {
212 Descendants(self.traverse())
213 }
214
215 pub fn traverse(&self) -> Traverse<T> {
217 Traverse {
218 root: self.clone(),
219 next: Some(NodeEdge::Start(self.clone())),
220 next_back: Some(NodeEdge::End(self.clone())),
221 }
222 }
223
224 pub fn detach(&mut self) {
230 self.0.borrow_mut().detach();
231 }
232
233 pub fn append(&mut self, new_child: Node<T>) {
239 assert!(*self != new_child, "a node cannot be appended to itself");
240
241 let mut self_borrow = self.0.borrow_mut();
242 let mut last_child_opt = None;
243 {
244 let mut new_child_borrow = new_child.0.borrow_mut();
245 new_child_borrow.detach();
246 new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
247 new_child_borrow.parent = Some(Rc::downgrade(&self.0));
248 if let Some(last_child_weak) = self_borrow.last_child.take() {
249 if let Some(last_child_strong) = last_child_weak.upgrade() {
250 new_child_borrow.previous_sibling = Some(last_child_weak);
251 last_child_opt = Some(last_child_strong);
252 }
253 }
254 self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
255 }
256
257 if let Some(last_child_strong) = last_child_opt {
258 let mut last_child_borrow = last_child_strong.borrow_mut();
259 debug_assert!(last_child_borrow.next_sibling.is_none());
260 last_child_borrow.next_sibling = Some(new_child.0);
261 } else {
262 debug_assert!(self_borrow.first_child.is_none());
264 self_borrow.first_child = Some(new_child.0);
265 }
266 }
267
268 pub fn prepend(&mut self, new_child: Node<T>) {
274 assert!(*self != new_child, "a node cannot be prepended to itself");
275
276 let mut self_borrow = self.0.borrow_mut();
277 {
278 let mut new_child_borrow = new_child.0.borrow_mut();
279 new_child_borrow.detach();
280 new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
281 new_child_borrow.parent = Some(Rc::downgrade(&self.0));
282 match self_borrow.first_child.take() {
283 Some(first_child_strong) => {
284 {
285 let mut first_child_borrow = first_child_strong.borrow_mut();
286 debug_assert!(first_child_borrow.previous_sibling.is_none());
287 first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0));
288 }
289 new_child_borrow.next_sibling = Some(first_child_strong);
290 }
291 None => {
292 debug_assert!(self_borrow.first_child.is_none());
293 self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
294 }
295 }
296 }
297 self_borrow.first_child = Some(new_child.0);
298 }
299
300 pub fn insert_after(&mut self, new_sibling: Node<T>) {
306 assert!(*self != new_sibling, "a node cannot be inserted after itself");
307
308 let mut self_borrow = self.0.borrow_mut();
309 {
310 let mut new_sibling_borrow = new_sibling.0.borrow_mut();
311 new_sibling_borrow.detach();
312 new_sibling_borrow.root = self_borrow.root.clone();
313 new_sibling_borrow.parent = self_borrow.parent.clone();
314 new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0));
315 match self_borrow.next_sibling.take() {
316 Some(next_sibling_strong) => {
317 {
318 let mut next_sibling_borrow = next_sibling_strong.borrow_mut();
319 debug_assert!({
320 let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap();
321 Rc::ptr_eq(&weak.upgrade().unwrap(), &self.0)
322 });
323 next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
324 }
325 new_sibling_borrow.next_sibling = Some(next_sibling_strong);
326 }
327 None => {
328 if let Some(parent_ref) = self_borrow.parent.as_ref() {
329 if let Some(parent_strong) = parent_ref.upgrade() {
330 let mut parent_borrow = parent_strong.borrow_mut();
331 parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0));
332 }
333 }
334 }
335 }
336 }
337 self_borrow.next_sibling = Some(new_sibling.0);
338 }
339
340 pub fn insert_before(&mut self, new_sibling: Node<T>) {
346 assert!(*self != new_sibling, "a node cannot be inserted before itself");
347
348 let mut self_borrow = self.0.borrow_mut();
349 let mut previous_sibling_opt = None;
350 {
351 let mut new_sibling_borrow = new_sibling.0.borrow_mut();
352 new_sibling_borrow.detach();
353 new_sibling_borrow.root = self_borrow.root.clone();
354 new_sibling_borrow.parent = self_borrow.parent.clone();
355 new_sibling_borrow.next_sibling = Some(self.0.clone());
356 if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() {
357 if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() {
358 new_sibling_borrow.previous_sibling = Some(previous_sibling_weak);
359 previous_sibling_opt = Some(previous_sibling_strong);
360 }
361 }
362 self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
363 }
364
365 if let Some(previous_sibling_strong) = previous_sibling_opt {
366 let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
367 debug_assert!({
368 let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap();
369 Rc::ptr_eq(rc, &self.0)
370 });
371 previous_sibling_borrow.next_sibling = Some(new_sibling.0);
372 } else {
373 if let Some(parent_ref) = self_borrow.parent.as_ref() {
375 if let Some(parent_strong) = parent_ref.upgrade() {
376 let mut parent_borrow = parent_strong.borrow_mut();
377 parent_borrow.first_child = Some(new_sibling.0);
378 }
379 }
380 }
381 }
382}
383
384impl<T> NodeData<T> {
385 fn detach(&mut self) {
387 let parent_weak = self.parent.take();
388 let previous_sibling_weak = self.previous_sibling.take();
389 let next_sibling_strong = self.next_sibling.take();
390
391 let previous_sibling_opt = previous_sibling_weak.as_ref().and_then(|weak| weak.upgrade());
392
393 if let Some(next_sibling_ref) = next_sibling_strong.as_ref() {
394 let mut next_sibling_borrow = next_sibling_ref.borrow_mut();
395 next_sibling_borrow.previous_sibling = previous_sibling_weak;
396 } else if let Some(parent_ref) = parent_weak.as_ref() {
397 if let Some(parent_strong) = parent_ref.upgrade() {
398 let mut parent_borrow = parent_strong.borrow_mut();
399 parent_borrow.last_child = previous_sibling_weak;
400 }
401 }
402
403 if let Some(previous_sibling_strong) = previous_sibling_opt {
404 let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
405 previous_sibling_borrow.next_sibling = next_sibling_strong;
406 } else if let Some(parent_ref) = parent_weak.as_ref() {
407 if let Some(parent_strong) = parent_ref.upgrade() {
408 let mut parent_borrow = parent_strong.borrow_mut();
409 parent_borrow.first_child = next_sibling_strong;
410 }
411 }
412 }
413}
414
415
416pub mod iterator {
418 pub use super::Ancestors;
419 pub use super::PrecedingSiblings;
420 pub use super::FollowingSiblings;
421 pub use super::Children;
422 pub use super::Descendants;
423 pub use super::Traverse;
424 pub use super::NodeEdge;
425}
426
427macro_rules! impl_node_iterator {
428 ($name: ident, $next: expr) => {
429 impl<T> Iterator for $name<T> {
430 type Item = Node<T>;
431
432 fn next(&mut self) -> Option<Self::Item> {
436 match self.0.take() {
437 Some(node) => {
438 self.0 = $next(&node);
439 Some(node)
440 }
441 None => None
442 }
443 }
444 }
445 }
446}
447
448pub struct Ancestors<T>(Option<Node<T>>);
450impl_node_iterator!(Ancestors, |node: &Node<T>| node.parent());
451
452pub struct PrecedingSiblings<T>(Option<Node<T>>);
454impl_node_iterator!(PrecedingSiblings, |node: &Node<T>| node.previous_sibling());
455
456pub struct FollowingSiblings<T>(Option<Node<T>>);
458impl_node_iterator!(FollowingSiblings, |node: &Node<T>| node.next_sibling());
459
460pub struct Children<T> {
462 next: Option<Node<T>>,
463 next_back: Option<Node<T>>,
464}
465
466impl<T> Children<T> {
467 fn finished(&self) -> bool {
469 match self.next_back {
470 Some(ref next_back) => next_back.next_sibling() == self.next,
471 _ => true,
472 }
473 }
474}
475
476impl<T> Iterator for Children<T> {
477 type Item = Node<T>;
478
479 fn next(&mut self) -> Option<Self::Item> {
483 if self.finished() {
484 return None;
485 }
486
487 match self.next.take() {
488 Some(node) => {
489 self.next = node.next_sibling();
490 Some(node)
491 }
492 None => None
493 }
494 }
495}
496
497impl<T> DoubleEndedIterator for Children<T> {
498 fn next_back(&mut self) -> Option<Self::Item> {
502 if self.finished() {
503 return None;
504 }
505
506 match self.next_back.take() {
507 Some(node) => {
508 self.next_back = node.previous_sibling();
509 Some(node)
510 }
511 None => None
512 }
513 }
514}
515
516pub struct Descendants<T>(Traverse<T>);
518
519impl<T> Iterator for Descendants<T> {
520 type Item = Node<T>;
521
522 fn next(&mut self) -> Option<Self::Item> {
526 loop {
527 match self.0.next() {
528 Some(NodeEdge::Start(node)) => return Some(node),
529 Some(NodeEdge::End(_)) => {}
530 None => return None
531 }
532 }
533 }
534}
535
536
537#[derive(Clone, Debug)]
539pub enum NodeEdge<T> {
540 Start(Node<T>),
544
545 End(Node<T>),
549}
550
551impl<T> PartialEq for NodeEdge<T> {
553 fn eq(&self, other: &NodeEdge<T>) -> bool {
554 match (&*self, &*other) {
555 (&NodeEdge::Start(ref n1), &NodeEdge::Start(ref n2)) => *n1 == *n2,
556 (&NodeEdge::End(ref n1), &NodeEdge::End(ref n2)) => *n1 == *n2,
557 _ => false,
558 }
559 }
560}
561
562impl<T> NodeEdge<T> {
563 fn next_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
564 match *self {
565 NodeEdge::Start(ref node) => match node.first_child() {
566 Some(first_child) => Some(NodeEdge::Start(first_child)),
567 None => Some(NodeEdge::End(node.clone())),
568 },
569 NodeEdge::End(ref node) => {
570 if *node == *root {
571 None
572 } else {
573 match node.next_sibling() {
574 Some(next_sibling) => Some(NodeEdge::Start(next_sibling)),
575 None => match node.parent() {
576 Some(parent) => Some(NodeEdge::End(parent)),
577
578 None => None,
583 },
584 }
585 }
586 }
587 }
588 }
589
590 fn previous_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
591 match *self {
592 NodeEdge::End(ref node) => match node.last_child() {
593 Some(last_child) => Some(NodeEdge::End(last_child)),
594 None => Some(NodeEdge::Start(node.clone())),
595 },
596 NodeEdge::Start(ref node) => {
597 if *node == *root {
598 None
599 } else {
600 match node.previous_sibling() {
601 Some(previous_sibling) => Some(NodeEdge::End(previous_sibling)),
602 None => match node.parent() {
603 Some(parent) => Some(NodeEdge::Start(parent)),
604
605 None => None
610 }
611 }
612 }
613 }
614 }
615 }
616}
617
618pub struct Traverse<T> {
621 root: Node<T>,
622 next: Option<NodeEdge<T>>,
623 next_back: Option<NodeEdge<T>>,
624}
625
626impl<T> Traverse<T> {
627 fn finished(&self) -> bool {
629 match self.next_back {
630 Some(ref next_back) => next_back.next_item(&self.root) == self.next,
631 _ => true,
632 }
633 }
634}
635
636impl<T> Iterator for Traverse<T> {
637 type Item = NodeEdge<T>;
638
639 fn next(&mut self) -> Option<Self::Item> {
643 if self.finished() {
644 return None;
645 }
646
647 match self.next.take() {
648 Some(item) => {
649 self.next = item.next_item(&self.root);
650 Some(item)
651 }
652 None => None
653 }
654 }
655}
656
657impl<T> DoubleEndedIterator for Traverse<T> {
658 fn next_back(&mut self) -> Option<Self::Item> {
662 if self.finished() {
663 return None;
664 }
665
666 match self.next_back.take() {
667 Some(item) => {
668 self.next_back = item.previous_item(&self.root);
669 Some(item)
670 }
671 None => None
672 }
673 }
674}