Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ee7f783

Browse files
committedJan 16, 2025
Add a deterministic constructor for RandomState
1 parent d61f55d commit ee7f783

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
 

‎library/std/src/hash/random.rs

+38
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,44 @@ 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+
/// #![feature(deterministic_random_state)]
97+
/// use std::collections::HashSet;
98+
/// use std::hash::RandomState;
99+
///
100+
/// let s = RandomState::deterministic();
101+
/// let mut set = HashSet::with_hasher(s);
102+
/// set.insert(0);
103+
/// set.insert(1);
104+
/// for v in set {
105+
/// println!("{v}");
106+
/// }
107+
/// ```
108+
#[inline]
109+
#[allow(deprecated)]
110+
// rand
111+
#[must_use]
112+
#[unstable(feature = "deterministic_random_state", issue = "none")]
113+
pub fn deterministic() -> RandomState {
114+
RandomState { k0: 0, k1: 0 }
115+
}
78116
}
79117

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

0 commit comments

Comments
 (0)
Failed to load comments.