From 4f5c6de8534e35455d44c55211741975aefb0e2a Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Wed, 3 Jul 2024 08:44:59 +0000 Subject: [PATCH] start rand utils suite Signed-off-by: Jason Volk --- src/core/utils/mod.rs | 6 ++++-- src/core/utils/rand.rs | 24 ++++++++++++++++++++++++ src/core/utils/string.rs | 10 ---------- 3 files changed, 28 insertions(+), 12 deletions(-) create mode 100644 src/core/utils/rand.rs diff --git a/src/core/utils/mod.rs b/src/core/utils/mod.rs index 401775f7..75f55c9a 100644 --- a/src/core/utils/mod.rs +++ b/src/core/utils/mod.rs @@ -6,6 +6,7 @@ pub mod hash; pub mod html; pub mod json; pub mod mutex_map; +pub mod rand; pub mod string; pub mod sys; mod tests; @@ -19,7 +20,8 @@ pub use hash::calculate_hash; pub use html::Escape as HtmlEscape; pub use json::{deserialize_from_str, to_canonical_object}; pub use mutex_map::MutexMap; -pub use string::{random_string, str_from_bytes, string_from_bytes}; +pub use rand::string as random_string; +pub use string::{str_from_bytes, string_from_bytes}; pub use sys::available_parallelism; pub use time::millis_since_unix_epoch; @@ -41,7 +43,7 @@ pub fn unwrap_infallible(result: Result) -> T { #[must_use] pub fn generate_keypair() -> Vec { - let mut value = random_string(8).as_bytes().to_vec(); + let mut value = rand::string(8).as_bytes().to_vec(); value.push(0xFF); value.extend_from_slice( &ruma::signatures::Ed25519KeyPair::generate().expect("Ed25519KeyPair generation always works (?)"), diff --git a/src/core/utils/rand.rs b/src/core/utils/rand.rs new file mode 100644 index 00000000..1ded8a6d --- /dev/null +++ b/src/core/utils/rand.rs @@ -0,0 +1,24 @@ +use std::{ + ops::Range, + time::{Duration, SystemTime}, +}; + +use rand::{thread_rng, Rng}; + +pub fn string(length: usize) -> String { + thread_rng() + .sample_iter(&rand::distributions::Alphanumeric) + .take(length) + .map(char::from) + .collect() +} + +#[inline] +#[must_use] +pub fn timepoint_secs(range: Range) -> SystemTime { SystemTime::now() + secs(range) } + +#[must_use] +pub fn secs(range: Range) -> Duration { + let mut rng = thread_rng(); + Duration::from_secs(rng.gen_range(range)) +} diff --git a/src/core/utils/string.rs b/src/core/utils/string.rs index 7f6f6531..84a928a0 100644 --- a/src/core/utils/string.rs +++ b/src/core/utils/string.rs @@ -1,15 +1,5 @@ -use rand::prelude::*; - use crate::Result; -pub fn random_string(length: usize) -> String { - thread_rng() - .sample_iter(&rand::distributions::Alphanumeric) - .take(length) - .map(char::from) - .collect() -} - /// Parses the bytes into a string. #[inline] pub fn string_from_bytes(bytes: &[u8]) -> Result {