Skip to content

Commit c346dbe

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

File tree

1 file changed

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

1 file changed

+18
-7
lines changed

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

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -208,20 +208,31 @@ 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.
212+
///
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!**
215219
///
216220
/// ```rust
217221
/// use std::collections::HashMap;
218222
/// use std::hash::{BuildHasherDefault, DefaultHasher};
219-
/// use std::sync::Mutex;
223+
/// use std::sync::{LazyLock, Mutex};
220224
///
221-
/// const EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> =
225+
/// // HashMaps with a fixed, non-random hasher
226+
/// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> =
222227
/// HashMap::with_hasher(BuildHasherDefault::new());
223-
/// static MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> =
228+
/// static NONRANDOM_MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> =
224229
/// Mutex::new(HashMap::with_hasher(BuildHasherDefault::new()));
230+
///
231+
/// // HashMaps using LazyLock to retain random seeding
232+
/// const RANDOM_EMPTY_MAP: LazyLock<HashMap<String, Vec<i32>>> =
233+
/// LazyLock::new(HashMap::new);
234+
/// static RANDOM_MAP: LazyLock<Mutex<HashMap<String, Vec<i32>>>> =
235+
/// LazyLock::new(|| Mutex::new(HashMap::new()));
225236
/// ```
226237
227238
#[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")]

0 commit comments

Comments
 (0)