ForgeFlux/src/utils/random_string.rs

41 lines
1 KiB
Rust

use std::sync::Arc;
use actix_web::web;
use mockall::predicate::*;
use mockall::*;
pub type WebGenerateRandomStringInterface = web::Data<Arc<dyn GenerateRandomStringInterface>>;
#[automock]
pub trait GenerateRandomStringInterface: Send + Sync {
fn get_random(&self, len: usize) -> String;
}
pub struct GenerateRandomString;
impl GenerateRandomStringInterface for GenerateRandomString {
fn get_random(&self, len: usize) -> String {
use std::iter;
use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
let mut rng: ThreadRng = thread_rng();
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(len)
.collect::<String>()
}
}
impl GenerateRandomString {
pub fn inject() -> impl FnOnce(&mut web::ServiceConfig) {
let g = WebGenerateRandomStringInterface::new(Arc::new(GenerateRandomString));
let f = move |cfg: &mut web::ServiceConfig| {
cfg.app_data(g);
};
Box::new(f)
}
}