Skip to content

Commit

Permalink
Merge pull request #75 from triarius/triarius/error-report
Browse files Browse the repository at this point in the history
Report error when word list is too short
  • Loading branch information
triarius authored Jul 13, 2024
2 parents 27b90ee + 35c02aa commit 696fcf6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
6 changes: 2 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,9 @@ fn main() -> Result<()> {
let mut words: Vec<String> = words::list(args.dict_path)?;
let mut rng = rand::thread_rng();

print!(
"{}",
passphrase::new(&mut rng, &mut words, args.num_words, &args.separator)
);
let passphrase = passphrase::new(&mut rng, &mut words, args.num_words, &args.separator)?;

print!("{passphrase}");
if std::io::stdout().is_terminal() {
println!();
}
Expand Down
29 changes: 17 additions & 12 deletions src/passphrase.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
use eyre::{eyre, Result};
use rand::Rng;

pub fn new<T: Rng>(mut rng: T, words: &mut [String], num_words: usize, separator: &str) -> String {
pub fn new<T: Rng>(
mut rng: T,
words: &mut [String],
num_words: usize,
separator: &str,
) -> Result<String> {
if words.len() < num_words {
eprintln!(
return Err(eyre!(
"Your dictionary only has {} suitable words, but you asked for {} words.",
words.len(),
num_words
);
return String::new();
));
}

(0..num_words).for_each(|i| {
let j = rng.gen_range(i..words.len());
words.swap(i, j);
});

(0..num_words)
Ok((0..num_words)
.map(|i| words[i].clone())
.collect::<Vec<String>>()
.join(separator)
.collect::<Vec<_>>()
.join(separator))
}

mod test {
Expand Down Expand Up @@ -66,17 +71,17 @@ mod test {
let mut rng = ChaCha8Rng::seed_from_u64(seed);
rng.set_stream(*i as u64);
let mut words = words.clone();
let s = passphrase::new(&mut rng, &mut words, W, " ");
let s = passphrase::new(&mut rng, &mut words, W, " ").unwrap();
*acc.entry(s).or_insert(0) += 1_usize;
acc
})
.collect::<Vec<HashMap<String, usize>>>()
.iter()
.fold(HashMap::new(), |mut acc, h| {
for (k, v) in h {
.fold(HashMap::new(), |acc, h| {
h.iter().fold(acc, |mut acc, (k, v)| {
*acc.entry(k.to_owned()).or_insert(0) += v;
}
acc
acc
})
});

assert_eq!(histogram.values().sum::<usize>(), N, "missing samples");
Expand Down

0 comments on commit 696fcf6

Please sign in to comment.