Skip to content

Commit fc7b36b

Browse files
authored
Add into_keys and into_values to AHashMap (#136)
* Add into_keys and into_values Signed-off-by: Tom Kaitchuck <[email protected]>
1 parent 6801bf1 commit fc7b36b

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/hash_map.rs

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::borrow::Borrow;
22
use std::collections::{hash_map, HashMap};
3+
use std::collections::hash_map::{IntoKeys, IntoValues};
34
use std::fmt::{self, Debug};
45
use std::hash::{BuildHasher, Hash};
56
use std::iter::FromIterator;
@@ -181,6 +182,68 @@ where
181182
self.0.insert(k, v)
182183
}
183184

185+
/// Creates a consuming iterator visiting all the keys in arbitrary order.
186+
/// The map cannot be used after calling this.
187+
/// The iterator element type is `K`.
188+
///
189+
/// # Examples
190+
///
191+
/// ```
192+
/// use std::collections::HashMap;
193+
///
194+
/// let map = HashMap::from([
195+
/// ("a", 1),
196+
/// ("b", 2),
197+
/// ("c", 3),
198+
/// ]);
199+
///
200+
/// let mut vec: Vec<&str> = map.into_keys().collect();
201+
/// // The `IntoKeys` iterator produces keys in arbitrary order, so the
202+
/// // keys must be sorted to test them against a sorted array.
203+
/// vec.sort_unstable();
204+
/// assert_eq!(vec, ["a", "b", "c"]);
205+
/// ```
206+
///
207+
/// # Performance
208+
///
209+
/// In the current implementation, iterating over keys takes O(capacity) time
210+
/// instead of O(len) because it internally visits empty buckets too.
211+
#[inline]
212+
pub fn into_keys(self) -> IntoKeys<K, V> {
213+
self.0.into_keys()
214+
}
215+
216+
/// Creates a consuming iterator visiting all the values in arbitrary order.
217+
/// The map cannot be used after calling this.
218+
/// The iterator element type is `V`.
219+
///
220+
/// # Examples
221+
///
222+
/// ```
223+
/// use std::collections::HashMap;
224+
///
225+
/// let map = HashMap::from([
226+
/// ("a", 1),
227+
/// ("b", 2),
228+
/// ("c", 3),
229+
/// ]);
230+
///
231+
/// let mut vec: Vec<i32> = map.into_values().collect();
232+
/// // The `IntoValues` iterator produces values in arbitrary order, so
233+
/// // the values must be sorted to test them against a sorted array.
234+
/// vec.sort_unstable();
235+
/// assert_eq!(vec, [1, 2, 3]);
236+
/// ```
237+
///
238+
/// # Performance
239+
///
240+
/// In the current implementation, iterating over values takes O(capacity) time
241+
/// instead of O(len) because it internally visits empty buckets too.
242+
#[inline]
243+
pub fn into_values(self) -> IntoValues<K, V> {
244+
self.0.into_values()
245+
}
246+
184247
/// Removes a key from the map, returning the value at the key if the key
185248
/// was previously in the map.
186249
///

0 commit comments

Comments
 (0)