|
| 1 | +use rand::{RngCore, SeedableRng}; |
| 2 | + |
| 3 | +use crate::hash::{BuildHasher, Hash, Hasher, RandomState}; |
| 4 | +use crate::panic::Location; |
| 5 | +use crate::path::{Path, PathBuf}; |
| 6 | +use crate::{env, fs, thread}; |
| 7 | + |
| 8 | +/// Test-only replacement for `rand::thread_rng()`, which is unusable for |
| 9 | +/// us, as we want to allow running stdlib tests on tier-3 targets which may |
| 10 | +/// not have `getrandom` support. |
| 11 | +/// |
| 12 | +/// Does a bit of a song and dance to ensure that the seed is different on |
| 13 | +/// each call (as some tests sadly rely on this), but doesn't try that hard. |
| 14 | +/// |
| 15 | +/// This is duplicated in the `core`, `alloc` test suites (as well as |
| 16 | +/// `std`'s integration tests), but figuring out a mechanism to share these |
| 17 | +/// seems far more painful than copy-pasting a 7 line function a couple |
| 18 | +/// times, given that even under a perma-unstable feature, I don't think we |
| 19 | +/// want to expose types from `rand` from `std`. |
| 20 | +#[track_caller] |
| 21 | +pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng { |
| 22 | + let mut hasher = RandomState::new().build_hasher(); |
| 23 | + Location::caller().hash(&mut hasher); |
| 24 | + let hc64 = hasher.finish(); |
| 25 | + let seed_vec = hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<Vec<u8>>(); |
| 26 | + let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap(); |
| 27 | + SeedableRng::from_seed(seed) |
| 28 | +} |
| 29 | + |
| 30 | +pub struct TempDir(PathBuf); |
| 31 | + |
| 32 | +impl TempDir { |
| 33 | + pub fn join(&self, path: &str) -> PathBuf { |
| 34 | + let TempDir(ref p) = *self; |
| 35 | + p.join(path) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn path(&self) -> &Path { |
| 39 | + let TempDir(ref p) = *self; |
| 40 | + p |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +impl Drop for TempDir { |
| 45 | + fn drop(&mut self) { |
| 46 | + // Gee, seeing how we're testing the fs module I sure hope that we |
| 47 | + // at least implement this correctly! |
| 48 | + let TempDir(ref p) = *self; |
| 49 | + let result = fs::remove_dir_all(p); |
| 50 | + // Avoid panicking while panicking as this causes the process to |
| 51 | + // immediately abort, without displaying test results. |
| 52 | + if !thread::panicking() { |
| 53 | + result.unwrap(); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#[track_caller] // for `test_rng` |
| 59 | +pub fn tmpdir() -> TempDir { |
| 60 | + let p = env::temp_dir(); |
| 61 | + let mut r = test_rng(); |
| 62 | + let ret = p.join(&format!("rust-{}", r.next_u32())); |
| 63 | + fs::create_dir(&ret).unwrap(); |
| 64 | + TempDir(ret) |
| 65 | +} |
0 commit comments