fakes_gen/
helper.rs

1use rand::distributions::uniform::{SampleRange, SampleUniform};
2use rand::seq::SliceRandom;
3use rand::Rng;
4use std::fmt::Display;
5
6pub fn string_formatted<T: Display + ?Sized>(text: &T) -> String {
7    format!("\"{}\"", text)
8}
9
10pub fn not_string_formatted<T: Display + ?Sized>(text: &T) -> String {
11    text.to_string()
12}
13
14pub fn split(text: &str) -> (String, String) {
15    let list: Vec<&str> = text.split(':').map(|s: &str| s.trim()).collect();
16    return if list.len() == 1 {
17        (list[0].to_string(), list[0].to_string())
18    } else {
19        (list[0].to_string(), list[1].to_string())
20    };
21}
22
23pub fn select<'a, R: Rng, I: ?Sized>(rng: &'a mut R, data: &'a [&I]) -> &'a I {
24    return data
25        .choose(rng)
26        .expect("failed select data from empty list.");
27}
28
29/// minimum <= n <= maximum
30pub fn gen_range<R: Rng, T: SampleUniform, SR: SampleRange<T>>(rng: &mut R, range: SR) -> T {
31    rng.gen_range::<T, SR>(range)
32}
33
34pub fn gen_fraction_part<R: Rng>(rng: &mut R) -> f64 {
35    gen_range(rng, 0 as f64..=0 as f64)
36}
37
38pub fn select_many<'a, R: Rng, I: ?Sized>(
39    rng: &'a mut R,
40    data: &'a [&I],
41    minimum: usize,
42    maximum: usize,
43) -> Vec<&'a I> {
44    let size: usize = gen_range(rng, minimum..=maximum);
45    return data.choose_multiple(rng, size).map(|i| *i).collect();
46}
47
48const ASCII: &'static str = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
49const ALPHA_NUM: &'static str = "0123456789ABCDEFGHIJKLMNOPWRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
50const PASSWORD_CHAR: &'static str =
51    "0123456789ABCDEFGHIJKLMNOPWRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()+-={}[]:;<>,./?_~|";
52
53fn gen_chars<R: Rng>(base: &str, rng: &mut R, minimum: usize, maximum: usize) -> String {
54    let size: usize = gen_range(rng, minimum..=maximum);
55    return String::from_utf8(
56        base.as_bytes()
57            .choose_multiple(rng, size)
58            .cloned()
59            .collect(),
60    )
61    .unwrap();
62}
63
64pub fn gen_ascii_chars<R: Rng>(rng: &mut R, from: usize, to: usize) -> String {
65    gen_chars(ASCII, rng, from, to)
66}
67
68pub fn gen_alpha_num_chars<R: Rng>(gnd: &mut R, from: usize, to: usize) -> String {
69    gen_chars(ALPHA_NUM, gnd, from, to)
70}
71
72pub fn gen_password_chars<R: Rng>(rng: &mut R, from: usize, to: usize) -> String {
73    gen_chars(PASSWORD_CHAR, rng, from, to)
74}