Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assert bounds in shift_insert and add insert_before #340

Merged
merged 4 commits into from
Aug 30, 2024

Conversation

cuviper
Copy link
Member

@cuviper cuviper commented Aug 27, 2024

The way shift_insert works is a little weird around existing entries, because it's not possible to move them to index == len() -- that only works when inserting new entries. This caveat is now documented and directly asserted, so the panic will be clearer than the deeper bounds-check panic we were throwing before.

As an alternative, I've also added insert_before which is looser about the exact index when moving entries. There's no difference for new entries, but existing entries might move to index - 1 if that keeps them right before the entry at the given index, or the end point. In this case, all indices in 0..=len() are always valid choices.

That new semantic is also a little better for the implementation of insert_sorted, although that only matters in the case where binary search didn't find a key, but it does exist in the map. That means that the keys are not properly sorted to begin with, but at least insert_before lets us try to deal with that without panicking.

The only difference compared to using `shift_insert` is when the
binary-searched key isn't *actually* new to the map, just not found in
properly sorted order. In this case we can't guarantee a sorted result
either, but it will at least behave better about the new position,
especially if that's the end.
@cuviper cuviper added this pull request to the merge queue Aug 30, 2024
Merged via the queue into indexmap-rs:master with commit 139d7ad Aug 30, 2024
16 checks passed
@cuviper cuviper deleted the insert-bounds branch August 30, 2024 17:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant