Skip to content

Commit 4e703f5

Browse files
committed
docs(std): mention LazyLock in const/static HashMap construction
1 parent 8c39296 commit 4e703f5

File tree

1 file changed

+19
-7
lines changed
  • library/std/src/collections/hash

1 file changed

+19
-7
lines changed

library/std/src/collections/hash/map.rs

+19-7
Original file line numberDiff line numberDiff line change
@@ -208,20 +208,32 @@ use crate::ops::Index;
208208
/// # Usage in `const` and `static`
209209
///
210210
/// As explained above, `HashMap` is randomly seeded: each `HashMap` instance uses a different seed,
211-
/// which means that `HashMap::new` cannot be used in const context. To construct a `HashMap` in the
212-
/// initializer of a `const` or `static` item, you will have to use a different hasher that does not
213-
/// involve a random seed, as demonstrated in the following example. **A `HashMap` constructed this
214-
/// way is not resistant against HashDoS!**
211+
/// which means that `HashMap::new` normally cannot be used in a `const` or `static` initializer.
215212
///
213+
/// However, if you need to use a `HashMap` in a `const` or `static` initializer while retaining
214+
/// random seed generation, you can wrap the `HashMap` in [`LazyLock`].
215+
///
216+
/// Alternatively, you can construct a `HashMap` in a `const` or `static` initializer using a different
217+
/// hasher that does not rely on a random seed. **Be aware that a `HashMap` created this way is not
218+
/// resistant to HashDoS attacks!**
219+
///
220+
/// [`LazyLock`]: crate::sync::LazyLock
216221
/// ```rust
217222
/// use std::collections::HashMap;
218223
/// use std::hash::{BuildHasherDefault, DefaultHasher};
219-
/// use std::sync::Mutex;
224+
/// use std::sync::{LazyLock, Mutex};
220225
///
221-
/// const EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> =
226+
/// // HashMaps with a fixed, non-random hasher
227+
/// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> =
222228
/// HashMap::with_hasher(BuildHasherDefault::new());
223-
/// static MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> =
229+
/// static NONRANDOM_MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> =
224230
/// Mutex::new(HashMap::with_hasher(BuildHasherDefault::new()));
231+
///
232+
/// // HashMaps using LazyLock to retain random seeding
233+
/// const RANDOM_EMPTY_MAP: LazyLock<HashMap<String, Vec<i32>>> =
234+
/// LazyLock::new(HashMap::new);
235+
/// static RANDOM_MAP: LazyLock<Mutex<HashMap<String, Vec<i32>>>> =
236+
/// LazyLock::new(|| Mutex::new(HashMap::new()));
225237
/// ```
226238
227239
#[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]

0 commit comments

Comments
 (0)