feat: utility to generate random strings

This commit is contained in:
Aravinth Manivannan 2024-05-13 21:30:10 +05:30
parent 5d56cf132c
commit 5d636892a2
Signed by: realaravinth
GPG key ID: F8F50389936984FF
2 changed files with 73 additions and 0 deletions

5
src/utils/mod.rs Normal file
View file

@ -0,0 +1,5 @@
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
pub mod random_string;

View file

@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
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)
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use std::sync::Arc;
pub fn mock_generate_random_string(
times: Option<usize>,
returning: String,
) -> Arc<dyn GenerateRandomStringInterface> {
let mut m = MockGenerateRandomStringInterface::new();
if let Some(times) = times {
m.expect_get_random()
.times(times)
.return_const(returning.to_string());
} else {
m.expect_get_random().return_const(returning.to_string());
}
Arc::new(m)
}
}