rust-scraper / ego-tree

Vec-backed ID-tree
https://docs.rs/ego-tree
ISC License
45 stars 16 forks source link

How to insert child at index? #14

Closed jessegrosjean closed 1 month ago

jessegrosjean commented 6 years ago

I'd like to insert a child into a NodeMut at a specified index. Seems like it should be easy, but I can't figure it out. Keep running into lifetime problems.

My non-working code is:

fn insert_child_at_index<'a, T>(parent: &'a mut NodeMut<'a, T>, value: T, index: usize) -> NodeMut<'a, T> {
  if let Some(insert_before_id) = parent.tree.get(parent.id).unwrap().children().skip(index).next().map(|n| n.id) {
    parent.tree.get_mut(insert_before_id).unwrap().insert_before(value)
  } else {
    parent.append(value)
  }
}

The logic (for now) is to insert before child node at given index if child node exists, otherwise insert at end. In final API it probably makes more sense to throw error if index is beyond count, but I'm trying to keep example code simple as possible at moment.

Any tips on how to get this working?

jessegrosjean commented 6 years ago

Quite possibly there's a simple way using existing API, but I couldn't figure it out. In the meantime I've created this pull request that adds the API that I really wanted in the first place: https://github.com/programble/ego-tree/pull/15