rhai/config/
hashing.rs

1//! Fixed hashing seeds for stable hashing.
2//!
3//! Set to [`None`] to disable stable hashing.
4//!
5//! See [`rhai::config::hashing::set_hashing_seed`][set_hashing_seed].
6//!
7//! # Example
8//!
9//! ```rust
10//! // Set the hashing seed to [1, 2, 3, 4]
11//! rhai::config::hashing::set_hashing_seed(Some([1, 2, 3, 4])).unwrap();
12//! ```
13//! Alternatively, set this at compile time via the `RHAI_HASHING_SEED` environment variable.
14//!
15//! # Example
16//!
17//! ```sh
18//! env RHAI_HASHING_SEED ="[236,800,954,213]"
19//! ```
20
21use super::hashing_env;
22use crate::OnceCell;
23
24static HASHING_SEED: OnceCell<Option<[u64; 4]>> = OnceCell::new();
25
26#[allow(deprecated)]
27pub use crate::api::deprecated::config::hashing::{get_ahash_seed, set_ahash_seed};
28
29/// Set the hashing seed. This is used to hash functions etc.
30///
31/// This is a static global value and affects every Rhai instance.
32/// This should not be used _unless_ you know you need it.
33///
34/// Set the hashing seed to all zeros effectively disables stable hashing.
35///
36/// # Warning
37///
38/// * You can only call this function **ONCE** for the entire duration of program execution.
39/// * You **MUST** call this before performing **ANY** Rhai operation (e.g. creating an [`Engine`][crate::Engine]).
40///
41/// # Error
42///
43/// Returns an error containing the existing hashing seed if already set.
44///
45/// # Example
46///
47/// ```rust
48/// # use rhai::Engine;
49/// // Set the hashing seed to [1, 2, 3, 4]
50/// rhai::config::hashing::set_hashing_seed(Some([1, 2, 3, 4])).unwrap();
51///
52/// // Use Rhai AFTER setting the hashing seed
53/// let engine = Engine::new();
54/// ```
55#[inline(always)]
56pub fn set_hashing_seed(new_seed: Option<[u64; 4]>) -> Result<(), Option<[u64; 4]>> {
57    #[cfg(feature = "std")]
58    return HASHING_SEED.set(new_seed);
59
60    #[cfg(not(feature = "std"))]
61    return HASHING_SEED.set(new_seed.into()).map_err(|err| *err);
62}
63
64/// Get the current hashing Seed.
65///
66/// If the seed is not yet defined, the `RHAI_HASHING_SEED` environment variable (if any) is used.
67///
68/// Otherwise, the hashing seed is randomized to protect against DOS attacks.
69///
70/// See [`rhai::config::hashing::set_hashing_seed`][set_hashing_seed] for more.
71#[inline]
72#[must_use]
73pub fn get_hashing_seed() -> &'static Option<[u64; 4]> {
74    HASHING_SEED.get().unwrap_or(&hashing_env::HASHING_SEED)
75}