Skip to content

fix: allow insert_at(len) when the key already exists - #81

Merged
martinohmann merged 1 commit into
martinohmann:mainfrom
youdie006:insert-at-existing-key-len
Oct 29, 2026
Merged

martinohmann merged 1 commit into
martinohmann:mainfrom
youdie006:insert-at-existing-key-len

Conversation

@youdie006

Copy link
Copy Markdown
Contributor

VecMap::insert_at documents a panic only for index > len. With an existing key and index == len, it removes the old entry first and then inserts into a vector that is one shorter, so it panics and the entry is gone:

let mut map = VecMap::from([("a", 1), ("b", 2)]);
map.insert_at(2, "a", 3);
// before: panics with "insertion index (is 2) should be <= len (is 1)";
//         if the panic is caught, the map is [("b", 2)]
// after:  Some((0, 1)), and the map is [("b", 2), ("a", 3)]

The fix checks index > len before anything is removed, and moves the entry to the end when index == len. The doc now says so. New keys and index > len behave as before. Across maps of length 1 to 4, with every existing key and every index up to len, only the 10 cases with index == len change.

If you'd rather keep the panic, like indexmap's shift_insert, which rejects index == len for an existing key, the alternative is to assert index < len before removing and adjust the doc. That would still fix the lost entry.

These pass: cargo test --workspace --all-features, cargo fmt --check, and cargo doc with -D warnings. I didn't run miri, but the change has no unsafe code.

Written with AI assistance (Claude); I have reviewed the change.

insert_at removed the existing entry before inserting at index, so
index == len was out of bounds for the shorter vector: it panicked,
which the docs only allow for index > len, and lost the entry. Move the
entry to the end instead, and check index > len before removing it.
@martinohmann
martinohmann merged commit 276d084 into martinohmann:main Oct 29, 2026
5 checks passed
@martinohmann

Copy link
Copy Markdown
Owner

Thanks for fixing this!

@github-actions github-actions Bot mentioned this pull request Oct 29, 2026
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.

2 participants