diff --git a/src/lib.rs b/src/lib.rs index c2e7781..0a0257b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -472,6 +472,7 @@ impl<'a, T: 'a> NodeMut<'a, T> { { let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap(); + new_sibling.detach(); new_sibling.node().parent = Some(parent_id); new_sibling.node().prev_sibling = prev_sibling_id; new_sibling.node().next_sibling = Some(self.id); @@ -508,6 +509,7 @@ impl<'a, T: 'a> NodeMut<'a, T> { { let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap(); + new_sibling.detach(); new_sibling.node().parent = Some(parent_id); new_sibling.node().prev_sibling = Some(self.id); new_sibling.node().next_sibling = next_sibling_id; diff --git a/tests/tree.rs b/tests/tree.rs index a27f296..ac22561 100644 --- a/tests/tree.rs +++ b/tests/tree.rs @@ -1,6 +1,6 @@ extern crate ego_tree; -use ego_tree::Tree; +use ego_tree::{tree, Tree}; #[test] fn new() { @@ -69,3 +69,90 @@ fn neq() { let two = Tree::new('b'); assert_eq!(one, two); } + +#[test] +fn insert_id_after() { + let mut tree = tree! { + "root" => { + "a" => { + "child 1", + }, + "b" => { + "child 2", + }, + } + }; + + let a = tree.root().first_child().unwrap().id(); + let b = tree.root().last_child().unwrap().id(); + + assert_eq!(2, tree.root().children().count()); + assert_eq!(1, tree.get(a).unwrap().children().count()); + assert_eq!(1, tree.get(b).unwrap().children().count()); + + let child_1 = tree.get(a).unwrap().first_child().unwrap().id(); + tree.get_mut(b).unwrap().insert_id_after(child_1); + + assert_eq!( + 0, + tree.get(a).unwrap().children().count(), + "child 1 should be moved from a" + ); + assert_eq!( + 1, + tree.get(b).unwrap().children().count(), + "b should be unchanged" + ); + assert_eq!( + child_1, + tree.root().last_child().unwrap().id(), + "child 1 should be last child of root" + ); + assert_eq!(3, tree.root().children().count()); +} + +#[test] +fn insert_id_before() { + let mut tree = tree! { + "root" => { + "a" => { + "child 1", + }, + "b" => { + "child 2", + }, + } + }; + + let a = tree.root().first_child().unwrap().id(); + let b = tree.root().last_child().unwrap().id(); + + assert_eq!(2, tree.root().children().count()); + assert_eq!(1, tree.get(a).unwrap().children().count()); + assert_eq!(1, tree.get(b).unwrap().children().count()); + + let child_1 = tree.get(a).unwrap().first_child().unwrap().id(); + tree.get_mut(b).unwrap().insert_id_before(child_1); + + assert_eq!( + 0, + tree.get(a).unwrap().children().count(), + "child 1 should be moved from a" + ); + assert_eq!( + 1, + tree.get(b).unwrap().children().count(), + "b should be unchanged" + ); + assert_eq!( + b, + tree.root().last_child().unwrap().id(), + "b should be last child of root" + ); + assert_eq!( + child_1, + tree.get(b).unwrap().prev_sibling().unwrap().id(), + "child 1 should be between a and b" + ); + assert_eq!(3, tree.root().children().count()); +}