From 7ac73908b7f0e4d42a56507ade7ae7f26f5bc565 Mon Sep 17 00:00:00 2001 From: chico ferreira <36338391+chicoferreira@users.noreply.github.com> Date: Tue, 3 Dec 2024 02:07:15 +0000 Subject: [PATCH] Add `DashMap::extend_non_mut` and `DashSet::extend_non_mut` --- src/lib.rs | 24 ++++++++++++++++++++++++ src/set.rs | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index c0abb5e6..4d3ced22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -566,6 +566,27 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap { self._iter_mut() } + /// Extends the map with the key-value pairs from an iterator. + /// + /// A replacement of [`DashMap::extend`](DashMap::extend) without the need of a mutable reference to the map. + /// + /// **Locking behaviour:** May deadlock if called when holding any sort of reference into the map. + /// + /// # Examples + /// + /// ``` + /// use dashmap::DashMap; + /// + /// let map = DashMap::new(); + /// map.extend_non_mut(vec![(1, 2), (3, 4)]); + /// assert_eq!(map.len(), 2); + /// ``` + pub fn extend_non_mut(&self, it: impl IntoIterator) { + for (k, v) in it { + self.insert(k, v); + } + } + /// Get an immutable reference to an entry in the map /// /// **Locking behaviour:** May deadlock if called when holding a mutable reference into the map. @@ -1329,6 +1350,9 @@ impl<'a, K: Eq + Hash, V, S: BuildHasher + Clone> IntoIterator for &'a DashMap Extend<(K, V)> for DashMap { + /// Extends the map with the key-value pairs from an iterator. + /// + /// If you don't have a mutable reference to the map, you can use [`extend_non_mut`](DashMap::extend_non_mut) instead. fn extend>(&mut self, intoiter: I) { for pair in intoiter.into_iter() { self.insert(pair.0, pair.1); diff --git a/src/set.rs b/src/set.rs index 84c9dd16..3cb1a1f2 100644 --- a/src/set.rs +++ b/src/set.rs @@ -254,6 +254,25 @@ impl<'a, K: 'a + Eq + Hash, S: BuildHasher + Clone> DashSet { self.inner.remove_if(key, |k, _| f(k)).map(|(k, _)| k) } + /// Extends the set with the contents of an iterator. + /// + /// A replacement of [`DashSet::extend`](DashSet::extend) without the need of a mutable reference to the map. + /// + /// # Examples + /// + /// ``` + /// use dashmap::DashSet; + /// + /// let numbers = DashSet::new(); + /// numbers.extend_non_mut(vec![1, 2]); + /// assert_eq!(numbers.len(), 2); + /// ``` + pub fn extend_non_mut(&self, it: impl IntoIterator) { + for k in it { + self.insert(k); + } + } + /// Creates an iterator over a DashMap yielding immutable references. /// /// # Examples @@ -398,6 +417,9 @@ impl IntoIterator for DashSet { } impl Extend for DashSet { + /// Extends the set with the contents of an iterator. + /// + /// If you don't have a mutable reference to the set, you can use [`extend_non_mut`](DashSet::extend_non_mut) instead. fn extend>(&mut self, iter: T) { let iter = iter.into_iter().map(|k| (k, ()));