indexmap-rs / indexmap

A hash table with consistent order and fast iteration; access items by key or sequence index

Home Page:https://docs.rs/indexmap/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: Similar method to `Vec.splice`

SeaDve opened this issue · comments

I'm trying to drain a range and then insert multiple items into that gap, where the number of remove items is not always equal to inserted item, basically similar to Vec.splice. If that is not possible, there could also be some method that could insert an item to a particular index, so the behavior of splice could be replicated.

Currently, I do the following to replicate the behavior:

let end_part = inner_index.split_off(position);
inner_index.extend(new_items.chain(end_part.into_iter().skip(n_removed)));

there could also be some method that could insert an item to a particular index, so the behavior of splice could be replicated.

That's #173 -- the core pieces are there with move_index, at least. But it would be inefficient if you are inserting many items this way.

Currently, I do the following to replicate the behavior:

let end_part = inner_index.split_off(position);
inner_index.extend(new_items.chain(end_part.into_iter().skip(n_removed)));

This is not bad, although we could avoid some extra hashing if we did this internally.

However, if new_items and end_part have any overlapping keys, the latter will replace its value. I would expect you actually want the keep the new_items value -- or maybe you're just sure there's no overlap in your scenario.

let end_part = inner_index.split_off(position);
// this may overlap the beginning keys -- should they move?
inner_index.extend(new_items); 
for (key, value) in end_part.into_iter().skip(n_removed) {
    // This will avoid clobbering any new_items, but should they be
    // in their old (shifted/relative) position or the new spliced position?
    inner_index.entry(key).or_insert(value);
}

or maybe you're just sure there's no overlap in your scenario.

Yep, in my use case, it is ensured that there are no duplicate keys.

In general, though, I would expect existing keys to stay where they are; only unique keys are put on the gap, and the non-unique ones are simply used to update existing values at both ends. But, the behavior may be unexpected and might not overlap with other use cases.

A better alternative, I think, is to insert only unique keys (i.e., keys that are not on the map) on the gap, and return the non-unique keys as an iterator, so the caller could choose to use them to update values on the map explicitly, simply ignore them, or use them to assert that all items are inserted on the gap.

If you're still interested, could you give #294 a try?

If you're still interested, could you give #294 a try?

I tested it and it works well, thanks!