Skip to content

Commit d6af4c9

Browse files
committed
Add a deterministic constructor for RandomState
1 parent d61f55d commit d6af4c9

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

library/std/src/hash/random.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,43 @@ impl RandomState {
7575
RandomState { k0, k1 }
7676
})
7777
}
78+
79+
/// Constructs a new `RandomState` that is initialized with fixed keys.
80+
///
81+
/// There are no guarantees about the returned value other than it being
82+
/// deterministic. The returned value may vary across releases.
83+
///
84+
/// This constructor is meant for testing purposes, where it is important
85+
/// that a program behaves deterministically in order to reproduce test
86+
/// failures. Although it is possible to use other deterministic hashers,
87+
/// there are libraries which have hash collections with `RandomState`
88+
/// hardcoded in their public interface.
89+
///
90+
/// # Examples
91+
///
92+
/// Rerunning the following program always produces the same output, which
93+
/// isn't the case if `s` is created with `RandomState::new`.
94+
///
95+
/// ```
96+
/// use std::collections::HashSet;
97+
/// use std::hash::RandomState;
98+
///
99+
/// let s = RandomState::deterministic();
100+
/// let mut set = HashSet::with_hasher(s);
101+
/// set.insert(0);
102+
/// set.insert(1);
103+
/// for v in set {
104+
/// println!("{v}");
105+
/// }
106+
/// ```
107+
#[inline]
108+
#[allow(deprecated)]
109+
// rand
110+
#[must_use]
111+
#[unstable(feature = "deterministic_random_state", issue = "none")]
112+
pub fn deterministic() -> RandomState {
113+
RandomState { k0: 0, k1: 0 }
114+
}
78115
}
79116

80117
#[stable(feature = "hashmap_build_hasher", since = "1.7.0")]

0 commit comments

Comments
 (0)