]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/collections/hash/set.rs
Auto merge of #36753 - srinivasreddy:hash, r=nrc
[rust.git] / src / libstd / collections / hash / set.rs
index 7b3e52e03a14b40e4fa60d649ecf9b9a253e7d96..1ec7a4a7b639b51916e9cd10c81ac6ca83a6cdd5 100644 (file)
 ///     println!("{:?}", x);
 /// }
 /// ```
+///
+/// HashSet with fixed list of elements can be initialized from an array:
+///
+/// ```
+/// use std::collections::HashSet;
+///
+/// fn main() {
+///     let viking_names: HashSet<&str> =
+///         [ "Einar", "Olaf", "Harald" ].iter().cloned().collect();
+///     // use the values stored in the set
+/// }
+/// ```
+
+
 #[derive(Clone)]
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct HashSet<T, S = RandomState> {
@@ -119,8 +133,10 @@ pub fn new() -> HashSet<T, RandomState> {
         HashSet { map: HashMap::new() }
     }
 
-    /// Creates an empty HashSet with space for at least `n` elements in
-    /// the hash table.
+    /// Creates an empty `HashSet` with the specified capacity.
+    ///
+    /// The hash set will be able to hold at least `capacity` elements without
+    /// reallocating. If `capacity` is 0, the hash set will not allocate.
     ///
     /// # Examples
     ///
@@ -165,8 +181,11 @@ pub fn with_hasher(hasher: S) -> HashSet<T, S> {
         HashSet { map: HashMap::with_hasher(hasher) }
     }
 
-    /// Creates an empty HashSet with space for at least `capacity`
-    /// elements in the hash table, using `hasher` to hash the keys.
+    /// Creates an empty HashSet with with the specified capacity, using
+    /// `hasher` to hash the keys.
+    ///
+    /// The hash set will be able to hold at least `capacity` elements without
+    /// reallocating. If `capacity` is 0, the hash set will not allocate.
     ///
     /// Warning: `hasher` is normally randomly generated, and
     /// is designed to allow `HashSet`s to be resistant to attacks that
@@ -1149,7 +1168,7 @@ mod test_set {
     use super::super::map::RandomState;
 
     #[test]
-    fn test_create_capacities() {
+    fn test_zero_capacities() {
         type HS = HashSet<i32>;
 
         let s = HS::new();
@@ -1160,6 +1179,24 @@ fn test_create_capacities() {
 
         let s = HS::with_hasher(RandomState::new());
         assert_eq!(s.capacity(), 0);
+
+        let s = HS::with_capacity(0);
+        assert_eq!(s.capacity(), 0);
+
+        let s = HS::with_capacity_and_hasher(0, RandomState::new());
+        assert_eq!(s.capacity(), 0);
+
+        let mut s = HS::new();
+        s.insert(1);
+        s.insert(2);
+        s.remove(&1);
+        s.remove(&2);
+        s.shrink_to_fit();
+        assert_eq!(s.capacity(), 0);
+
+        let mut s = HS::new();
+        s.reserve(0);
+        assert_eq!(s.capacity(), 0);
     }
 
     #[test]