jogru0 / disjoint

Fast and safe implementation of the disjoint-set data structure.
https://docs.rs/disjoint/latest/disjoint/index.html
Apache License 2.0
2 stars 2 forks source link

Make `add_singleton` and `push` return the index of the new element. #10

Closed andriyDev closed 4 months ago

andriyDev commented 4 months ago

The indices of elements can be derived from the len of the set, but it is inconvenient to have to start a whole new statement just to join the element to something else.

With this, we can now add an element and assign it in one step.

My concrete case is something like this:

let mut set = DisjointSet::new();
let mut key_to_index = HashMap::new();

// ...In some loop
let index = *key_to_index.entry(my_key).or_insert_with(|| set.add_singleton());
andriyDev commented 4 months ago

I feel pretty strongly about this for DisjointSet::add_singleton. For DisjointSetVec::push, I could be convinced otherwise, since it matches Vec::push without the index and the name DisjointSetVec puts into mind that deriving it from the len is expected.

jogru0 commented 4 months ago

Thank you for the contribution, I just released 0.8.0 containing this change!

Regarding DisjointSetVec::push: I think it definitely makes sense to provide this information there as well, so for now, I added exactly your change to return usize. Maybe I want to change the type in the future, to provide even more information, so assume the API might change again (of course, that would be behind a new semantic version).