mysten_common/random_util.rs
1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use rand::Rng;
5use rand::seq::SliceRandom;
6use sui_macros::nondeterministic;
7
8use crate::in_test_configuration;
9use crate::random::get_rng;
10
11pub fn randomize_cache_capacity_in_tests<T>(size: T) -> T
12where
13 T: Copy + PartialOrd + rand::distributions::uniform::SampleUniform + TryFrom<usize>,
14{
15 if !in_test_configuration() {
16 return size;
17 }
18
19 let mut rng = get_rng();
20
21 // Three choices for cache size
22 //
23 // 2: constant evictions
24 // size: presumably chosen to minimize evictions
25 // random: thrown in case there are weird behaviors at specific but arbitrary eviction/miss rates.
26 //
27 // We don't simply use a uniform random choice because the most interesting cases are probably
28 // a) the value that will be used in production and b) a very tiny value so we want those two
29 // 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() -> std::io::Result<TempDir> {
46 nondeterministic!(tempfile::tempdir())
47}