Skip to content

Commit

Permalink
Document and assert index bounds in shift_insert
Browse files Browse the repository at this point in the history
  • Loading branch information
cuviper committed Aug 29, 2024
1 parent 922c6ad commit 0247a15
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
8 changes: 7 additions & 1 deletion src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,26 +448,32 @@ where
/// Insert a key-value pair in the map at the given index.
///
/// If an equivalent key already exists in the map: the key remains and
/// is moved to the new position in the map, its corresponding value is updated
/// is moved to the given index in the map, its corresponding value is updated
/// with `value`, and the older value is returned inside `Some(_)`.
/// Note that existing entries **cannot** be moved to `index == map.len()`!
///
/// If no equivalent key existed in the map: the new key-value pair is
/// inserted at the given index, and `None` is returned.
///
/// ***Panics*** if `index` is out of bounds.
/// Valid indices are `0..map.len()` (exclusive) when moving an existing entry, or
/// `0..=map.len()` (inclusive) when inserting a new key.
///
/// Computes in **O(n)** time (average).
///
/// See also [`entry`][Self::entry] if you want to insert *or* modify,
/// perhaps only using the index for new entries with [`VacantEntry::shift_insert`].
pub fn shift_insert(&mut self, index: usize, key: K, value: V) -> Option<V> {
let len = self.len();
match self.entry(key) {
Entry::Occupied(mut entry) => {
assert!(index < len, "index out of bounds");
let old = mem::replace(entry.get_mut(), value);
entry.move_index(index);
Some(old)
}
Entry::Vacant(entry) => {
assert!(index <= len, "index out of bounds");
entry.shift_insert(index, value);
None
}
Expand Down
11 changes: 7 additions & 4 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,15 @@ where

/// Insert the value into the set at the given index.
///
/// If an equivalent item already exists in the set, it returns
/// `false` leaving the original value in the set, but moving it to
/// the new position in the set. Otherwise, it inserts the new
/// item at the given index and returns `true`.
/// If an equivalent item already exists in the set, it returns `false` leaving
/// the original value in the set, but moved to the given index.
/// Note that existing values **cannot** be moved to `index == set.len()`!
///
/// Otherwise, it inserts the new value at the given index and returns `true`.
///
/// ***Panics*** if `index` is out of bounds.
/// Valid indices are `0..set.len()` (exclusive) when moving an existing value, or
/// `0..=set.len()` (inclusive) when inserting a new value.
///
/// Computes in **O(n)** time (average).
pub fn shift_insert(&mut self, index: usize, value: T) -> bool {
Expand Down

0 comments on commit 0247a15

Please sign in to comment.