cipher_utils/
character_set.rs

1/// An unordered set of characters. This is similar to an `Alphabet`, but instead of representing an ordering
2/// of the english alphabet, this represents an unordered set of any characters.
3#[derive(PartialEq, Eq, Debug, Clone)]
4pub struct CharacterSet {
5    characters: std::collections::HashSet<char>,
6}
7
8impl CharacterSet {
9    pub fn of(text: &str) -> Self {
10        CharacterSet {
11            characters: text
12                .chars()
13                .filter(|char| "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".contains(*char))
14                .collect(),
15        }
16    }
17
18    pub fn raw(text: &str) -> Self {
19        CharacterSet {
20            characters: text.chars().collect(),
21        }
22    }
23
24    pub fn contains(&self, character: char) -> bool {
25        self.characters.contains(&character)
26    }
27
28    pub fn characters(&self) -> &std::collections::HashSet<char> {
29        &self.characters
30    }
31
32    pub fn is_alphabetic(&self) -> bool {
33        self.characters.iter().all(|character| character.is_alphabetic())
34    }
35
36    pub fn is_alphanumeric(&self) -> bool {
37        self.characters.iter().all(|character| character.is_alphanumeric())
38    }
39}
40
41impl std::ops::Add for CharacterSet {
42    type Output = Self;
43
44    fn add(self, other: Self) -> Self::Output {
45        CharacterSet {
46            characters: self.characters.union(&other.characters).map(|character| character.to_owned()).collect(),
47        }
48    }
49}
50
51lazy_static::lazy_static! {
52    pub static ref LOWERCASE_ALPHABETIC: CharacterSet = CharacterSet::of("abcdefghijklmnopqrstuvwxyz");
53    pub static ref UPPERCASE_ALPHABETIC: CharacterSet = CharacterSet::of("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
54    pub static ref ALPHABETIC: CharacterSet = CharacterSet::of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
55    pub static ref BASE_64: CharacterSet = CharacterSet::raw("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/");
56    pub static ref MORSE: CharacterSet = CharacterSet::raw("-./");
57    pub static ref NUMERIC: CharacterSet = CharacterSet::of("0123456789");
58    pub static ref ALPHANUMERIC: CharacterSet = CharacterSet::of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
59    pub static ref HEX: CharacterSet = CharacterSet::of("0123456789ABCDEFabcdef");
60    pub static ref OCTAL: CharacterSet = CharacterSet::of("01234567");
61    pub static ref BINARY: CharacterSet = CharacterSet::of("01");
62}