gen_random/
lib.rs

1//! # Gen Random
2//!
3//! `gen_random` is a lib for generating random number by custom its length and kind.
4//! It's very easy to generate different randon number, Number/Letter/Symbol or collection of them.
5
6use rand::Rng;
7
8const NUMBER: &'static [u8] = b"0123456789";
9const SYMBOL: &'static [u8] = b"~!@#$%^&*()_+-={}[]|:;<>,.?/\"\\";
10const LETTER: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
11
12/// Custom length and kind of random number
13pub struct Custom {
14    /// Length of random number
15    length: usize,
16    /// Kind of random number
17    kind: CharSetKind,
18}
19
20/// Kinds of random number
21pub enum CharSetKind {
22    Number,
23    Letter,
24    Symbol,
25    NumberAndLetter,
26    NumberAndSymbol,
27    LetterAndSymbol,
28    NumberLetterAndSymbol,
29}
30
31impl Custom {
32    pub fn new(length: usize, kind: CharSetKind) -> Custom {
33        Custom { length, kind }
34    }
35
36    /// Generate random number by custom its length and kind
37    ///
38    /// # Examples
39    ///
40    /// ```
41    ///  let random = gen_random::Custom::new(5, gen_random::CharSetKind::Number).generate();
42    ///  assert_eq!(random, "12345".to_string())
43    /// ```
44    pub fn generate(&self) -> String {
45        let charset = match self.kind {
46            CharSetKind::Number => NUMBER.to_vec(),
47            CharSetKind::Letter => LETTER.to_vec(),
48            CharSetKind::Symbol => SYMBOL.to_vec(),
49            CharSetKind::NumberAndLetter => [NUMBER, LETTER].concat().to_vec(),
50            CharSetKind::NumberAndSymbol => [NUMBER, SYMBOL].concat().to_vec(),
51            CharSetKind::LetterAndSymbol => [LETTER, SYMBOL].concat().to_vec(),
52            CharSetKind::NumberLetterAndSymbol => [NUMBER, LETTER, SYMBOL].concat().to_vec(),
53        };
54
55        let mut rng = rand::thread_rng();
56
57        let value: String = (0..self.length)
58            .map(|_| {
59                let idx = rng.gen_range(0..charset.len());
60                charset[idx] as char
61            })
62            .collect();
63
64        value
65    }
66}
67