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
use std::str::FromStr;
use std::error::Error;
use std::fmt;

#[cfg(feature = "cereal")]
extern crate serde;

#[cfg(feature = "cereal")]
use serde::{Deserialize, Serialize};
/// Describes the set of characters or words
/// that will be used to generate a password.
#[cfg_attr(feature = "cereal", derive(Serialize, Deserialize))]
pub enum CharSet {
    Ascii,
    AsciiExtended,
    Xkcd,
    Numbers,
    Alphanumeric,
}

#[derive(Debug)]
pub struct ParseCharSetError {}
impl fmt::Display for ParseCharSetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "String did not match")
    }
}

impl Error for ParseCharSetError{}

impl FromStr for CharSet {
    type Err = ParseCharSetError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "ascii" => Ok(CharSet::Ascii),
            "asciiextended" => Ok(CharSet::AsciiExtended),
            "xkcd" => Ok(CharSet::Xkcd),
            "numbers" => Ok(CharSet::Numbers),
            "alphanumeric" => Ok(CharSet::Alphanumeric),
            _ => Err(ParseCharSetError{})
        }
    }
}

/// Describes the options that are passed into the
/// generate_password function.
#[cfg_attr(feature = "cereal", derive(Serialize, Deserialize))]
pub struct PasswordOptions {
    /// How many characters in the password. Or, how many words in the password. 
    pub min_length: u32,
    /// The set of characters or words to randmoly select from.
    pub character_set: CharSet,
}

impl PasswordOptions {
    /// Create a set of options for generating a password.
    ///
    /// ## Example
    ///
    /// ```
    /// use password_gen::{PasswordOptions, PasswordGenerator};
    /// use password_gen::password_options::CharSet;
    /// let mut generator = PasswordGenerator::new();
    /// let options = PasswordOptions::new(15, CharSet::Ascii);
    /// let password = generator.generate_password(&options);
    /// ```
    ///
    pub fn new(min_length: u32, character_set: CharSet) -> PasswordOptions {
        PasswordOptions {
            min_length,
            character_set,
        }
    }
}