iota_common/
random_util.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2026 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use iota_macros::nondeterministic;
6use rand::{Rng, seq::SliceRandom};
7
8use crate::{in_test_configuration, random::get_rng};
9
10pub fn randomize_cache_capacity_in_tests<T>(size: T) -> T
11where
12    T: Copy + PartialOrd + rand::distributions::uniform::SampleUniform + TryFrom<usize>,
13{
14    if !in_test_configuration() {
15        return size;
16    }
17
18    let mut rng = get_rng();
19
20    // Three choices for cache size
21    //
22    // 2: constant evictions
23    // size: presumably chosen to minimize evictions
24    // random: thrown in case there are weird behaviors at specific but arbitrary
25    // eviction/miss rates.
26    //
27    // We don't simply use a uniform random choice because the most interesting
28    // cases are probably a) the value that will be used in production and b) a
29    // very tiny value so we want those two cases to get picked more often.
30
31    // using unwrap() invokes all sorts of requirements on Debug impls.
32    let Ok(two) = T::try_from(2) else {
33        panic!("Failed to convert 2 to T");
34    };
35
36    let random_size = rng.gen_range(two..size);
37    let choices = [two, size, random_size];
38    *choices.choose(&mut rng).unwrap()
39}
40
41pub type TempDir = tempfile::TempDir;
42
43/// Creates a temporary directory with random name.
44/// Ensure the name is randomized even in simtests.
45pub fn tempdir() -> TempDir {
46    nondeterministic!(tempfile::tempdir())
47        .expect("temporary directory should not fail to be created")
48}