aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: a4fa2277a9eb6a1724b29305b137fb5c91c96959 (plain)
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
mod utils;

use wasm_bindgen::prelude::*;
use rand::Rng;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
extern {
    fn alert(s: &str);
}


#[wasm_bindgen]
pub fn generate(len: usize, lower: bool, upper: bool, number: bool, special: bool) -> String {
    let mut upper_charset: Vec<char> = String::from("ABCDEFGHIJKLMNOPQRSTUVWXYZ").chars().collect();
    let mut lower_charset: Vec<char> = String::from("abcdefghijklmnopqrstuvwxyz").chars().collect();
    let mut number_charset: Vec<char> = String::from("1234567890").chars().collect();
    let mut special_charset: Vec<char> = String::from("!@#$%^&*()+{}[]").chars().collect();
    let mut result: Vec<char> = Vec::new();

    let mut rng = rand::thread_rng();

    if lower {
        result.append(&mut lower_charset);
    }

    if upper {
        result.append(&mut upper_charset);
    }

    if number {
        result.append(&mut number_charset);
    }

    if special {
        result.append(&mut special_charset);
    }


    (0..len)
        .map(|_| {
            let idx = rng.gen_range(0..result.len());
            result[idx] as char
        })
        .collect()
}