Description
When I tried to sort in the tree, I used the code below which caused a panic in detach function:
use ego_tree::{tree, Tree};
fn sort<T>(tree: &mut Tree<T>)
where
T: Ord + Clone + std::fmt::Display,
{
let binding = tree.clone();
let children = binding.root().children();
let mut node_vec = children.collect::<Vec<_>>();
node_vec.sort_by_key(|node| node.value());
let mut root_mut = tree.root_mut();
node_vec.iter().for_each(|node| {
println!(
"{:?}: {}; tree: {}",
node.id(),
node.value(),
root_mut.tree()
);
// match root_mut.last_child() {
// Some(last_child) if last_child.id() != node.id() => {
root_mut.append_id(node.id());
// }
// _ => (),
// }
});
}
fn main() {
let mut tree = tree!('a' => { 'd', 'c', 'b' });
sort(&mut tree);
println!("{}", tree);
}
I found that every time I append, the last node disappears. After reviewing the code, it seems that when a node detaches, the previous node's next_sibling
is set to None
, but the parent's children still hold the original value. When only one node remains, it enters the condition first_child_id == self.id
.
The simplest way to fix this is, as I commented in the match, to directly return the Node if last_child_id == new_child_id
. The same logic applies to prepend_id
.
BTW, Is it possible to implement a sort
or sort_by_key
method? By operating directly within NodeMut
, it would eliminate the need for operations like clone to_vec that I'm currently using.