Skip to content

Commit

Permalink
feat: rename Map::insert to Map::append and add proper insert impl
Browse files Browse the repository at this point in the history
  • Loading branch information
paolobarbolini committed Dec 29, 2024
1 parent cc4f137 commit 95eb54d
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ impl<'a> Map<'a> {

/// Insert a new element in this `Map`
///
/// If the `key` is already present, the `value` is appended to the existing value:
/// If the `key` is already present, the `value` overwrite the existing value:
///
/// ```
/// let mut map = rusty_s3::Map::new();
/// map.insert("k", "a");
/// assert_eq!(map.get("k"), Some("a"));
/// map.insert("k", "b");
/// assert_eq!(map.get("k"), Some("a, b"));
/// assert_eq!(map.get("k"), Some("b"));
/// ```
///
/// # Panics
Expand All @@ -59,6 +59,38 @@ impl<'a> Map<'a> {
let key = key.into();
let value = value.into();

let i = self.inner.binary_search_by(|a| a.0.cmp(&key));
match i {
Ok(i) => {
let old_value = self.inner.get_mut(i).expect("i can't be out of bounds");
*old_value = (key, value);
}
Err(i) => self.inner.insert(i, (key, value)),
}
}

/// Insert a new element in this `Map`
///
/// If the `key` is already present, the `value` is appended to the existing value:
///
/// ```
/// let mut map = rusty_s3::Map::new();
/// map.append("k", "a");
/// assert_eq!(map.get("k"), Some("a"));
/// map.append("k", "b");
/// assert_eq!(map.get("k"), Some("a, b"));
/// ```
///
/// # Panics
/// In case of out of bound inner index access
pub fn append<K, V>(&mut self, key: K, value: V)
where
K: Into<Cow<'a, str>>,
V: Into<Cow<'a, str>>,
{
let key = key.into();
let value = value.into();

let i = self.inner.binary_search_by(|a| a.0.cmp(&key));
match i {
Ok(i) => {
Expand Down

0 comments on commit 95eb54d

Please sign in to comment.