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
#![warn(missing_docs)]
#[macro_use]
extern crate lazy_static;
extern crate itertools;
extern crate rand;
use std::fmt;
use std::collections::HashSet;
use itertools::Itertools;
use rand::{Rng, OsRng};
pub const WORDS: &'static [&'static str] = &include!("../res/wordlist.json");
pub fn random_phrase(no_of_words: usize) -> String {
let mut rng = OsRng::new().expect("Not able to operate without random source.");
(0..no_of_words).map(|_| rng.choose(WORDS).unwrap()).join(" ")
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
PhraseTooShort(usize),
WordNotFromDictionary(String),
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::PhraseTooShort(len) => writeln!(fmt, "The phrase is too short ({})", len),
Error::WordNotFromDictionary(ref word) => writeln!(fmt, "The word '{}' does not come from the dictionary.", word),
}
}
}
pub fn validate_phrase(phrase: &str, expected_no_of_words: usize) -> Result<(), Error> {
lazy_static! {
static ref WORD_SET: HashSet<&'static str> = WORDS.iter().cloned().collect();
}
let mut len = 0;
for word in phrase.split_whitespace() {
len += 1;
if !WORD_SET.contains(word) {
return Err(Error::WordNotFromDictionary(word.into()));
}
}
if len < expected_no_of_words {
return Err(Error::PhraseTooShort(len));
}
return Ok(());
}
#[cfg(test)]
mod tests {
use super::{validate_phrase, random_phrase, Error};
#[test]
fn should_produce_right_number_of_words() {
let p = random_phrase(10);
assert_eq!(p.split(" ").count(), 10);
}
#[test]
fn should_not_include_carriage_return() {
let p = random_phrase(10);
assert!(!p.contains('\r'), "Carriage return should be trimmed.");
}
#[test]
fn should_validate_the_phrase() {
let p = random_phrase(10);
assert_eq!(validate_phrase(&p, 10), Ok(()));
assert_eq!(validate_phrase(&p, 12), Err(Error::PhraseTooShort(10)));
assert_eq!(validate_phrase("xxx", 0), Err(Error::WordNotFromDictionary("xxx".into())));
}
}