use std::fmt;
use std::cell::{RefCell, Ref, RefMut};
use std::rc::{Rc, Weak};
type Link<T> = Rc<RefCell<NodeData<T>>>;
type WeakLink<T> = Weak<RefCell<NodeData<T>>>;
pub struct Node<T>(Link<T>);
struct NodeData<T> {
root: Option<WeakLink<T>>,
parent: Option<WeakLink<T>>,
first_child: Option<Link<T>>,
last_child: Option<WeakLink<T>>,
previous_sibling: Option<WeakLink<T>>,
next_sibling: Option<Link<T>>,
data: T,
}
impl<T> Clone for Node<T> {
fn clone(&self) -> Self {
Node(Rc::clone(&self.0))
}
}
impl<T> PartialEq for Node<T> {
fn eq(&self, other: &Node<T>) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl<T: fmt::Debug> fmt::Debug for Node<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&*self.borrow(), f)
}
}
impl<T: fmt::Display> fmt::Display for Node<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&*self.borrow(), f)
}
}
macro_rules! try_opt {
($expr: expr) => {
match $expr {
Some(value) => value,
None => return None
}
}
}
impl<T> Node<T> {
pub(crate) fn new(data: T) -> Node<T> {
Node(Rc::new(RefCell::new(NodeData {
root: None,
parent: None,
first_child: None,
last_child: None,
previous_sibling: None,
next_sibling: None,
data,
})))
}
pub fn root(&self) -> Node<T> {
match self.0.borrow().root.as_ref() {
Some(v) => Node(v.upgrade().unwrap()),
None => self.clone(),
}
}
pub fn parent(&self) -> Option<Node<T>> {
Some(Node(try_opt!(try_opt!(self.0.borrow().parent.as_ref()).upgrade())))
}
pub fn first_child(&self) -> Option<Node<T>> {
Some(Node(try_opt!(self.0.borrow().first_child.as_ref()).clone()))
}
pub fn last_child(&self) -> Option<Node<T>> {
Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade())))
}
pub fn previous_sibling(&self) -> Option<Node<T>> {
Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade())))
}
pub fn next_sibling(&self) -> Option<Node<T>> {
Some(Node(try_opt!(self.0.borrow().next_sibling.as_ref()).clone()))
}
pub(crate) fn borrow(&self) -> Ref<T> {
Ref::map(self.0.borrow(), |v| &v.data)
}
pub(crate) fn borrow_mut(&mut self) -> RefMut<T> {
RefMut::map(self.0.borrow_mut(), |v| &mut v.data)
}
pub fn ancestors(&self) -> Ancestors<T> {
Ancestors(Some(self.clone()))
}
pub fn preceding_siblings(&self) -> PrecedingSiblings<T> {
PrecedingSiblings(Some(self.clone()))
}
pub fn following_siblings(&self) -> FollowingSiblings<T> {
FollowingSiblings(Some(self.clone()))
}
pub fn children(&self) -> Children<T> {
Children {
next: self.first_child(),
next_back: self.last_child(),
}
}
pub fn has_children(&self) -> bool {
self.first_child().is_some()
}
pub fn descendants(&self) -> Descendants<T> {
Descendants(self.traverse())
}
pub fn traverse(&self) -> Traverse<T> {
Traverse {
root: self.clone(),
next: Some(NodeEdge::Start(self.clone())),
next_back: Some(NodeEdge::End(self.clone())),
}
}
pub fn detach(&mut self) {
self.0.borrow_mut().detach();
}
pub fn append(&mut self, new_child: Node<T>) {
assert!(*self != new_child, "a node cannot be appended to itself");
let mut self_borrow = self.0.borrow_mut();
let mut last_child_opt = None;
{
let mut new_child_borrow = new_child.0.borrow_mut();
new_child_borrow.detach();
new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
new_child_borrow.parent = Some(Rc::downgrade(&self.0));
if let Some(last_child_weak) = self_borrow.last_child.take() {
if let Some(last_child_strong) = last_child_weak.upgrade() {
new_child_borrow.previous_sibling = Some(last_child_weak);
last_child_opt = Some(last_child_strong);
}
}
self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
}
if let Some(last_child_strong) = last_child_opt {
let mut last_child_borrow = last_child_strong.borrow_mut();
debug_assert!(last_child_borrow.next_sibling.is_none());
last_child_borrow.next_sibling = Some(new_child.0);
} else {
debug_assert!(self_borrow.first_child.is_none());
self_borrow.first_child = Some(new_child.0);
}
}
pub fn prepend(&mut self, new_child: Node<T>) {
assert!(*self != new_child, "a node cannot be prepended to itself");
let mut self_borrow = self.0.borrow_mut();
{
let mut new_child_borrow = new_child.0.borrow_mut();
new_child_borrow.detach();
new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
new_child_borrow.parent = Some(Rc::downgrade(&self.0));
match self_borrow.first_child.take() {
Some(first_child_strong) => {
{
let mut first_child_borrow = first_child_strong.borrow_mut();
debug_assert!(first_child_borrow.previous_sibling.is_none());
first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0));
}
new_child_borrow.next_sibling = Some(first_child_strong);
}
None => {
debug_assert!(self_borrow.first_child.is_none());
self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
}
}
}
self_borrow.first_child = Some(new_child.0);
}
pub fn insert_after(&mut self, new_sibling: Node<T>) {
assert!(*self != new_sibling, "a node cannot be inserted after itself");
let mut self_borrow = self.0.borrow_mut();
{
let mut new_sibling_borrow = new_sibling.0.borrow_mut();
new_sibling_borrow.detach();
new_sibling_borrow.root = self_borrow.root.clone();
new_sibling_borrow.parent = self_borrow.parent.clone();
new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0));
match self_borrow.next_sibling.take() {
Some(next_sibling_strong) => {
{
let mut next_sibling_borrow = next_sibling_strong.borrow_mut();
debug_assert!({
let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap();
Rc::ptr_eq(&weak.upgrade().unwrap(), &self.0)
});
next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
}
new_sibling_borrow.next_sibling = Some(next_sibling_strong);
}
None => {
if let Some(parent_ref) = self_borrow.parent.as_ref() {
if let Some(parent_strong) = parent_ref.upgrade() {
let mut parent_borrow = parent_strong.borrow_mut();
parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0));
}
}
}
}
}
self_borrow.next_sibling = Some(new_sibling.0);
}
pub fn insert_before(&mut self, new_sibling: Node<T>) {
assert!(*self != new_sibling, "a node cannot be inserted before itself");
let mut self_borrow = self.0.borrow_mut();
let mut previous_sibling_opt = None;
{
let mut new_sibling_borrow = new_sibling.0.borrow_mut();
new_sibling_borrow.detach();
new_sibling_borrow.root = self_borrow.root.clone();
new_sibling_borrow.parent = self_borrow.parent.clone();
new_sibling_borrow.next_sibling = Some(self.0.clone());
if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() {
if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() {
new_sibling_borrow.previous_sibling = Some(previous_sibling_weak);
previous_sibling_opt = Some(previous_sibling_strong);
}
}
self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
}
if let Some(previous_sibling_strong) = previous_sibling_opt {
let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
debug_assert!({
let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap();
Rc::ptr_eq(rc, &self.0)
});
previous_sibling_borrow.next_sibling = Some(new_sibling.0);
} else {
if let Some(parent_ref) = self_borrow.parent.as_ref() {
if let Some(parent_strong) = parent_ref.upgrade() {
let mut parent_borrow = parent_strong.borrow_mut();
parent_borrow.first_child = Some(new_sibling.0);
}
}
}
}
}
impl<T> NodeData<T> {
fn detach(&mut self) {
let parent_weak = self.parent.take();
let previous_sibling_weak = self.previous_sibling.take();
let next_sibling_strong = self.next_sibling.take();
let previous_sibling_opt = previous_sibling_weak.as_ref().and_then(|weak| weak.upgrade());
if let Some(next_sibling_ref) = next_sibling_strong.as_ref() {
let mut next_sibling_borrow = next_sibling_ref.borrow_mut();
next_sibling_borrow.previous_sibling = previous_sibling_weak;
} else if let Some(parent_ref) = parent_weak.as_ref() {
if let Some(parent_strong) = parent_ref.upgrade() {
let mut parent_borrow = parent_strong.borrow_mut();
parent_borrow.last_child = previous_sibling_weak;
}
}
if let Some(previous_sibling_strong) = previous_sibling_opt {
let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
previous_sibling_borrow.next_sibling = next_sibling_strong;
} else if let Some(parent_ref) = parent_weak.as_ref() {
if let Some(parent_strong) = parent_ref.upgrade() {
let mut parent_borrow = parent_strong.borrow_mut();
parent_borrow.first_child = next_sibling_strong;
}
}
}
}
pub mod iterator {
pub use super::Ancestors;
pub use super::PrecedingSiblings;
pub use super::FollowingSiblings;
pub use super::Children;
pub use super::Descendants;
pub use super::Traverse;
pub use super::NodeEdge;
}
macro_rules! impl_node_iterator {
($name: ident, $next: expr) => {
impl<T> Iterator for $name<T> {
type Item = Node<T>;
fn next(&mut self) -> Option<Self::Item> {
match self.0.take() {
Some(node) => {
self.0 = $next(&node);
Some(node)
}
None => None
}
}
}
}
}
pub struct Ancestors<T>(Option<Node<T>>);
impl_node_iterator!(Ancestors, |node: &Node<T>| node.parent());
pub struct PrecedingSiblings<T>(Option<Node<T>>);
impl_node_iterator!(PrecedingSiblings, |node: &Node<T>| node.previous_sibling());
pub struct FollowingSiblings<T>(Option<Node<T>>);
impl_node_iterator!(FollowingSiblings, |node: &Node<T>| node.next_sibling());
pub struct Children<T> {
next: Option<Node<T>>,
next_back: Option<Node<T>>,
}
impl<T> Children<T> {
fn finished(&self) -> bool {
match self.next_back {
Some(ref next_back) => next_back.next_sibling() == self.next,
_ => true,
}
}
}
impl<T> Iterator for Children<T> {
type Item = Node<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.finished() {
return None;
}
match self.next.take() {
Some(node) => {
self.next = node.next_sibling();
Some(node)
}
None => None
}
}
}
impl<T> DoubleEndedIterator for Children<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.finished() {
return None;
}
match self.next_back.take() {
Some(node) => {
self.next_back = node.previous_sibling();
Some(node)
}
None => None
}
}
}
pub struct Descendants<T>(Traverse<T>);
impl<T> Iterator for Descendants<T> {
type Item = Node<T>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.0.next() {
Some(NodeEdge::Start(node)) => return Some(node),
Some(NodeEdge::End(_)) => {}
None => return None
}
}
}
}
#[derive(Clone, Debug)]
pub enum NodeEdge<T> {
Start(Node<T>),
End(Node<T>),
}
impl<T> PartialEq for NodeEdge<T> {
fn eq(&self, other: &NodeEdge<T>) -> bool {
match (&*self, &*other) {
(&NodeEdge::Start(ref n1), &NodeEdge::Start(ref n2)) => *n1 == *n2,
(&NodeEdge::End(ref n1), &NodeEdge::End(ref n2)) => *n1 == *n2,
_ => false,
}
}
}
impl<T> NodeEdge<T> {
fn next_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
match *self {
NodeEdge::Start(ref node) => match node.first_child() {
Some(first_child) => Some(NodeEdge::Start(first_child)),
None => Some(NodeEdge::End(node.clone())),
},
NodeEdge::End(ref node) => {
if *node == *root {
None
} else {
match node.next_sibling() {
Some(next_sibling) => Some(NodeEdge::Start(next_sibling)),
None => match node.parent() {
Some(parent) => Some(NodeEdge::End(parent)),
None => None,
},
}
}
}
}
}
fn previous_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
match *self {
NodeEdge::End(ref node) => match node.last_child() {
Some(last_child) => Some(NodeEdge::End(last_child)),
None => Some(NodeEdge::Start(node.clone())),
},
NodeEdge::Start(ref node) => {
if *node == *root {
None
} else {
match node.previous_sibling() {
Some(previous_sibling) => Some(NodeEdge::End(previous_sibling)),
None => match node.parent() {
Some(parent) => Some(NodeEdge::Start(parent)),
None => None
}
}
}
}
}
}
}
pub struct Traverse<T> {
root: Node<T>,
next: Option<NodeEdge<T>>,
next_back: Option<NodeEdge<T>>,
}
impl<T> Traverse<T> {
fn finished(&self) -> bool {
match self.next_back {
Some(ref next_back) => next_back.next_item(&self.root) == self.next,
_ => true,
}
}
}
impl<T> Iterator for Traverse<T> {
type Item = NodeEdge<T>;
fn next(&mut self) -> Option<Self::Item> {
if self.finished() {
return None;
}
match self.next.take() {
Some(item) => {
self.next = item.next_item(&self.root);
Some(item)
}
None => None
}
}
}
impl<T> DoubleEndedIterator for Traverse<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.finished() {
return None;
}
match self.next_back.take() {
Some(item) => {
self.next_back = item.previous_item(&self.root);
Some(item)
}
None => None
}
}
}