random_str 1.1.0

Generate random strings, chars, booleans, and integers.
Documentation
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! This crate provides a set of functions to generate random strings, numbers, letters, symbols and booleans.
pub mod random {
    use rand::{
        distr::uniform::{SampleRange, SampleUniform},
        seq::IndexedMutRandom,
    };
    use std::sync::LazyLock;

    static LOWERCASE: LazyLock<Vec<char>> =
        LazyLock::new(|| (b'a'..=b'z').map(|c| c as char).collect());
    static UPPERCASE: LazyLock<Vec<char>> =
        LazyLock::new(|| (b'A'..=b'Z').map(|c| c as char).collect());
    static NUMBERS: LazyLock<Vec<char>> =
        LazyLock::new(|| (b'0'..=b'9').map(|c| c as char).collect());
    static SYMBOLS: LazyLock<Vec<char>> = LazyLock::new(|| {
        // TODO: add more symbols
        vec!['#', '$', '%', '&', '*', '@', '^', '!']
    });

    pub trait CharBuilder {
        fn options(&mut self) -> &mut Vec<char>;

        fn with_lowercase(mut self) -> Self
        where
            Self: Sized,
        {
            self.options().extend(LOWERCASE.iter());
            self
        }

        fn with_uppercase(mut self) -> Self
        where
            Self: Sized,
        {
            self.options().extend(UPPERCASE.iter());
            self
        }

        fn with_numbers(mut self) -> Self
        where
            Self: Sized,
        {
            self.options().extend(NUMBERS.iter());
            self
        }

        fn with_symbols(mut self) -> Self
        where
            Self: Sized,
        {
            self.options().extend(SYMBOLS.iter());
            self
        }
    }

    /// A random String builder, providig fined-grained control
    /// over what a random String should contain.
    ///
    /// If no charsets are supplied, the build() step will
    /// produce a `None` value.
    ///
    /// ## Examples
    /// Random letter including from 'a' to 'z' and from 'A' to 'Z'
    /// ```
    /// use random_str::random::{RandomCharBuilder, CharBuilder};
    /// 
    /// let random_letter: Option<char> = RandomCharBuilder::new()
    ///     .with_lowercase()
    ///     .with_uppercase()
    ///     .build();
    /// println!("Random letter: {}", random_letter.unwrap());
    /// ```
    pub struct RandomCharBuilder {
        options: Vec<char>,
    }

    impl CharBuilder for RandomCharBuilder {
        fn options(&mut self) -> &mut Vec<char> {
            &mut self.options
        }
    }

    impl RandomCharBuilder {
        pub fn new() -> Self {
            RandomCharBuilder {
                options: Vec::new(),
            }
        }

        pub fn build(mut self) -> Option<char> {
            if self.options.is_empty() {
                return None;
            }

            let mut rng = rand::rng();
            self.options.choose_mut(&mut rng).copied()
        }
    }

    impl Default for RandomCharBuilder {
        fn default() -> Self {
            Self::new()
        }
    }

    /// A random String builder, providig fined-grained control
    /// over what a random String should contain.
    ///
    /// If no charsets are supplied, the build() step will
    /// produce a `None` value.
    ///
    /// ## Examples
    /// Random phone number
    /// ```
    /// use random_str::random::{RandomStringBuilder, CharBuilder};
    ///
    /// let digits: Option<String> = RandomStringBuilder::new()
    ///     .with_length(10)
    ///     .with_numbers()
    ///     .build();
    /// let random_phone_number = format!("+52 {}", digits.unwrap());
    /// println!("Random phone number: {}", random_phone_number);
    /// ```
    /// Random password
    /// ```
    /// use random_str::random::{RandomStringBuilder, CharBuilder};
    ///
    /// let random_password: Option<String> = RandomStringBuilder::new()
    ///     .with_length(32)  // Optional, 16 as default
    ///     .with_lowercase()
    ///     .with_uppercase()
    ///     .with_numbers()
    ///     .with_symbols()
    ///    .build();
    /// println!("Random password: {}", random_password.unwrap());
    /// ```
    pub struct RandomStringBuilder {
        options: Vec<char>,
        length: usize,
    }

    impl CharBuilder for RandomStringBuilder {
        fn options(&mut self) -> &mut Vec<char> {
            &mut self.options
        }
    }

    impl RandomStringBuilder {
        pub fn new() -> Self {
            RandomStringBuilder {
                options: Vec::new(),
                length: 16,
            }
        }

        pub fn with_length(mut self, length: usize) -> Self {
            self.length = length;
            self
        }

        pub fn build(mut self) -> Option<String> {
            if self.options.is_empty() {
                return None;
            }

            let mut rng = rand::rng();
            Some(
                (0..=self.length)
                    .map(|_| *self.options().choose_mut(&mut rng).unwrap())
                    .collect(),
            )
        }
    }

    impl Default for RandomStringBuilder {
        fn default() -> Self {
            Self::new()
        }
    }

    // TODO: delete
    fn get_symbols_list() -> Vec<char> {
        vec!['#', '$', '%', '&', '*', '@', '^', '!']
    }

    /// Get a random char from a-z or A-Z
    ///
    /// # Panics
    /// Panics if the function is called with both parameters set to false
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str as random;
    /// ```
    ///
    /// ```
    /// let random_letter = random::get_letter(true, false);
    /// println!("Random letter: {}", random_char);
    /// ```
    /// Possible output: Random letter: w
    /// ```
    /// let random_letter = random::get_letter(false, true);
    /// println!("Random letter: {}", random_letter);
    /// ```
    /// Possible output: Random letter: X
    /// ```
    /// let random_letter = random::get_letter(true, true);
    /// println!("Random letter: {}", random_letter);
    /// ```
    /// Possible output: Random letter: x or Random letter: Y
    #[cfg(not(doctest))]
    #[deprecated(since = "1.0.0", note = "Use RandomCharBuilder instead")]
    pub fn get_letter(lowercase: bool, uppercase: bool) -> char {
        let mut chars: Vec<char> = vec![];

        if lowercase {
            let lower_chars: Vec<char> = (b'a'..=b'z').map(|c| c as char).collect();
            chars = lower_chars;
        }

        if uppercase {
            let capital_chars: Vec<char> = (b'A'..=b'Z').map(|c| c as char).collect();
            chars.extend(capital_chars);
        }

        let mut rng = rand::rng();
        let random_char = chars.choose_mut(&mut rng).unwrap();
        *random_char
    }

    /// Get a random number (i32) from a minimum and maximum value
    ///
    /// # Panics
    /// Panics if min is greater than max
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str as random;
    /// ```
    /// ```
    /// let random_number = random::get_int(0, 9);
    /// println!("Random number: {}", random_number);
    /// ```
    /// Possible output: Random number: 3
    #[cfg(not(doctest))]
    // TODO: add number() with generic params
    pub fn get_int(min: i32, max: i32) -> i32 {
        use rand::RngExt;

        let mut rng = rand::rng();
        rng.random_range(min..=max)
    }

    /// Get a random number within a range
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str::random::{self};
    ///
    /// let random_number = random::number(0..=9);
    /// assert!((0..=9).contains(&random_number))
    /// ```
    pub fn number<T, R>(range: R) -> T
    where
        T: SampleUniform,
        R: SampleRange<T>,
    {
        use rand::RngExt;

        let mut rng = rand::rng();
        rng.random_range(range)
    }

    /// Get a random symbol from a list of symbols
    /// Possible symbols are: #, $, %, &, *, @, ^
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str as random;
    /// ```
    /// ```
    /// let random_symbol = random::get_symbol();
    /// println!("Random symbol: {}", random_symbol);
    /// ```
    #[cfg(not(doctest))]
    // TODO: add symbol()
    pub fn get_symbol() -> char {
        let mut symbols = get_symbols_list();
        let mut rng = rand::rng();
        let random_symbol = symbols.choose_mut(&mut rng).unwrap();
        *random_symbol
    }

    /// Get a random string with a given length and a set of characters
    ///
    /// # Panics
    /// Panics if the function is called with all parameters set to false
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str as random;
    /// ```
    /// ```
    /// let random_password = random::get_string(16, true, true, true, true);
    /// println!("Random password: {}", random_password);
    /// ```
    #[cfg(not(doctest))]
    #[deprecated(since = "1.0.0", note = "Use RandomStringBuilder instead")]
    pub fn get_string(
        length: usize,
        lowercase: bool,
        uppercase: bool,
        numbers: bool,
        symbols: bool,
    ) -> String {
        let symbols_list: Vec<char> = get_symbols_list();
        let numbers_list: Vec<char> = (b'0'..=b'9').map(|c| c as char).collect();
        let cap_letters_list: Vec<char> = (b'A'..=b'Z').map(|c| c as char).collect();
        let low_letters_list: Vec<char> = (b'a'..=b'z').map(|c| c as char).collect();
        let mut random_string: Vec<char> = vec![];

        if lowercase {
            random_string.extend(low_letters_list);
        }
        if uppercase {
            random_string.extend(cap_letters_list);
        }
        if numbers {
            random_string.extend(numbers_list);
        }
        if symbols {
            random_string.extend(symbols_list);
        }

        let mut rng = rand::rng();
        (0..=length)
            .map(|_| *random_string.choose_mut(&mut rng).unwrap())
            .collect()
    }

    /// Get a random boolean value
    ///
    /// # Examples
    ///
    /// ```
    /// use random_str as random;
    /// ```
    /// ```
    /// let random_bool = random::get_bool();
    /// println!("Random boolean: {}", random_bool);
    /// ```
    /// Possible output: Random boolean: true or Random boolean: false
    #[cfg(not(doctest))]
    #[deprecated(since = "1.0.0", note = "Use bool() instead")]
    pub fn get_bool() -> bool {
        bool()
    }

    /// Get a random bool value with a probability of 50%
    ///
    /// # Example
    ///
    /// ```
    /// use random_str::random::{self};
    ///
    /// let random_bool = random::bool();
    /// println!("Random bool: {}", random_bool);
    /// 
    /// assert!(random_bool == true || random_bool == false);
    /// ```
    pub fn bool() -> bool {
        use rand::RngExt;

        let mut rng = rand::rng();
        rng.random_bool(0.5)
    }

    #[deprecated(since = "1.0.0", note = "It will be removed")]
    pub fn get_char() -> char {
        let mut chars: Vec<char> = (b'!'..=b'~').map(|c| c as char).collect();
        let mut rng = rand::rng();
        *chars.choose_mut(&mut rng).unwrap()
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn test_get_random_lowercase_letter() {
            let random_letter = get_letter(true, false);
            assert!(random_letter.is_ascii_alphabetic());
            assert!(random_letter.is_ascii_lowercase());
        }

        #[test]
        fn test_get_random_uppercase_letter() {
            let random_letter = get_letter(false, true);
            assert!(random_letter.is_ascii_alphabetic());
            assert!(random_letter.is_ascii_uppercase());
        }

        #[test]
        fn test_get_random_letter() {
            let random_letter = get_letter(true, true);
            assert!(random_letter.is_ascii_alphabetic());
        }

        #[test]
        // Validate if the function panics when both parameters are false
        fn test_get_random_false_letter() {
            let result = std::panic::catch_unwind(|| get_letter(false, false));
            assert!(result.is_err());
        }
    }
}