1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
//! `rsgen` is a tiny library to generate random characters string.
//! 
//! ## Usage
//! 
//! ```
//! use rsgen::{gen_random_string, OutputCharsType};
//! 
//! let output_chars_type = OutputCharsType::LatinAlphabetAndNumeric {
//!     use_upper_case: true,
//!     use_lower_case: true,
//! };
//! let _random_string = gen_random_string(32, output_chars_type);
//! ```
//! 

use rand::{self, Rng};

/// Configuration for output characters.
#[derive(Clone, Copy)]
pub enum OutputCharsType {
    /// Latin-Alphabet specifying to use upper/lower case.
    LatinAlphabet {
        use_upper_case: bool,
        use_lower_case: bool,
    },
    /// Latin-Alphabet and numeric figures specifying to use upper/lower case.
    LatinAlphabetAndNumeric {
        use_upper_case: bool,
        use_lower_case: bool,
    },
    /// Numeric figures.
    Numeric,
    /// Printable ASCII characters *without* SPACE. (0x21-0x7E)
    PrintableAsciiWithoutSpace,
    /// Printable ASCII characters *with* SPACE. (0x20-0x7E)
    PrintableAsciiWithSpace,
}

/// Generates a random characters string.
/// 
/// This function uses [ThreadRng](https://docs.rs/rand/0.6.5/rand/rngs/struct.ThreadRng.html) in [rand crate](https://docs.rs/rand) internally.
/// 
/// # Example
/// 
/// ```
/// use rsgen::{gen_random_string, OutputCharsType};
/// 
/// let output_chars_type = OutputCharsType::LatinAlphabetAndNumeric {
///     use_upper_case: true,
///     use_lower_case: true,
/// };
/// let _random_string = gen_random_string(32, output_chars_type);
/// ```
pub fn gen_random_string(number_of_characters: usize, output_char_type: OutputCharsType) -> String {
    let mut rng = rand::thread_rng();
    gen_random_string_with_rng(&mut rng, number_of_characters, output_char_type)
}

/// Generates a random characters string specifying RNG.
/// 
/// # Example
/// 
/// ```
/// use std::time::SystemTime;
/// use rand_core::SeedableRng;
/// use rand_xorshift::XorShiftRng;
/// use rsgen::{gen_random_string_with_rng, OutputCharsType};
/// 
/// let output_chars_type = OutputCharsType::LatinAlphabetAndNumeric {
///     use_upper_case: true,
///     use_lower_case: true,
/// };
/// let now = SystemTime::now();
/// let seed = now
///     .duration_since(SystemTime::UNIX_EPOCH)
///     .map(|d| d.as_secs())
///     .unwrap();
/// let mut rng = XorShiftRng::seed_from_u64(seed);
/// let _random_string = gen_random_string_with_rng(&mut rng, 32, output_chars_type);
/// ```
pub fn gen_random_string_with_rng<R>(
    rng: &mut R,
    number_of_characters: usize,
    output_chars_type: OutputCharsType,
) -> String
where
    R: Rng,
{
    match output_chars_type {
        OutputCharsType::LatinAlphabet {
            use_upper_case,
            use_lower_case,
        } => {
            let range = match (use_upper_case, use_lower_case) {
                (true, true) => 26 + 26,
                _ => 26,
            };
            let charset: &[u8] = match (use_upper_case, use_lower_case) {
                (true, true) => b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
                (true, false) => b"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                (false, true) => b"abcdefghijklmnopqrstuvwxyz",
                _ => unreachable!(),
            };
            let uniformed = rand::distributions::Uniform::from(0..range);
            rng.sample_iter(&uniformed)
                .take(number_of_characters)
                .map(|n| charset[n as usize] as char)
                .collect()
        }
        OutputCharsType::LatinAlphabetAndNumeric {
            use_upper_case,
            use_lower_case,
        } => {
            let range = match (use_upper_case, use_lower_case) {
                (true, true) => 26 + 26 + 10,
                _ => 26 + 10,
            };
            let charset: &[u8] = match (use_upper_case, use_lower_case) {
                (true, true) => b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
                (true, false) => b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
                (false, true) => b"abcdefghijklmnopqrstuvwxyz0123456789",
                _ => unreachable!(),
            };
            let uniformed = rand::distributions::Uniform::from(0..range);
            rng.sample_iter(&uniformed)
                .take(number_of_characters)
                .map(|n| charset[n] as char)
                .collect()
        }
        OutputCharsType::Numeric => {
            let uniform = rand::distributions::Uniform::from(0..=9);
            rng.sample_iter(&uniform)
                .take(number_of_characters)
                .filter_map(|n| std::char::from_digit(n as u32, 10))
                .collect()
        }
        OutputCharsType::PrintableAsciiWithoutSpace => {
            let uniform = rand::distributions::Uniform::from(0x21..=0x7e);
            rng.sample_iter(&uniform)
                .take(number_of_characters)
                .filter_map(std::char::from_u32)
                .collect()
        }
        OutputCharsType::PrintableAsciiWithSpace => {
            let uniform = rand::distributions::Uniform::from(0x20..=0x7e);
            rng.sample_iter(&uniform)
                .take(number_of_characters)
                .filter_map(std::char::from_u32)
                .collect()
        }
    }
}