Skip to content

append_id will remove the node when the new node is the last child #39

Closed
@AuTa

Description

@AuTa

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions