start rand utils suite
Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
parent
25c004f08c
commit
4f5c6de853
3 changed files with 28 additions and 12 deletions
|
@ -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<T>(result: Result<T, std::convert::Infallible>) -> T {
|
|||
|
||||
#[must_use]
|
||||
pub fn generate_keypair() -> Vec<u8> {
|
||||
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 (?)"),
|
||||
|
|
24
src/core/utils/rand.rs
Normal file
24
src/core/utils/rand.rs
Normal file
|
@ -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<u64>) -> SystemTime { SystemTime::now() + secs(range) }
|
||||
|
||||
#[must_use]
|
||||
pub fn secs(range: Range<u64>) -> Duration {
|
||||
let mut rng = thread_rng();
|
||||
Duration::from_secs(rng.gen_range(range))
|
||||
}
|
|
@ -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<String> {
|
||||
|
|
Loading…
Add table
Reference in a new issue