Skip to content

Commit

Permalink
Add append methods
Browse files Browse the repository at this point in the history
  • Loading branch information
cuviper committed Aug 13, 2024
1 parent 22c0b4e commit 8c0a1cd
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,35 @@ where
{
Splice::new(self, range, replace_with.into_iter())
}

/// Moves all key-value pairs from `other` into `self`, leaving `other` empty.
///
/// This is equivalent to calling [`insert`][Self::insert] for each
/// key-value pair from `other` in order, which means that for keys that
/// already exist in `self`, their value is updated in the current position.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// // Note: Key (3) is present in both maps.
/// let mut a = IndexMap::from([(3, "c"), (2, "b"), (1, "a")]);
/// let mut b = IndexMap::from([(3, "d"), (4, "e"), (5, "f")]);
/// let old_capacity = b.capacity();
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 5);
/// assert_eq!(b.len(), 0);
/// assert_eq!(b.capacity(), old_capacity);
///
/// assert!(a.keys().eq(&[3, 2, 1, 4, 5]));
/// assert_eq!(a[&3], "d"); // "c" was overwritten.
/// ```
pub fn append<S2>(&mut self, other: &mut IndexMap<K, V, S2>) {
self.extend(other.drain(..));
}
}

impl<K, V, S> IndexMap<K, V, S>
Expand Down
30 changes: 30 additions & 0 deletions src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,36 @@ where
{
Splice::new(self, range, replace_with.into_iter())
}

/// Moves all values from `other` into `self`, leaving `other` empty.
///
/// This is equivalent to calling [`insert`][Self::insert] for each value
/// from `other` in order, which means that values that already exist
/// in `self` are unchanged in their current position.
///
/// See also [`union`][Self::union] to iterate the combined values by
/// reference, without modifying `self` or `other`.
///
/// # Examples
///
/// ```
/// use indexmap::IndexSet;
///
/// let mut a = IndexSet::from([3, 2, 1]);
/// let mut b = IndexSet::from([3, 4, 5]);
/// let old_capacity = b.capacity();
///
/// a.append(&mut b);
///
/// assert_eq!(a.len(), 5);
/// assert_eq!(b.len(), 0);
/// assert_eq!(b.capacity(), old_capacity);
///
/// assert!(a.iter().eq(&[3, 2, 1, 4, 5]));
/// ```
pub fn append<S2>(&mut self, other: &mut IndexSet<T, S2>) {
self.map.append(&mut other.map);
}
}

impl<T, S> IndexSet<T, S>
Expand Down

0 comments on commit 8c0a1cd

Please sign in to comment.