use std::{
collections::BTreeMap,
fs::File,
io::{prelude::*, BufReader},
path::Path,
};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("io error")]
Io(#[from] std::io::Error),
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Wordlist {
words: BTreeMap<String, usize>,
total: usize,
}
impl Wordlist {
pub fn load(path: &Path) -> Result<Self, Error> {
let f = File::open(path)?;
let reader = BufReader::new(f);
let mut list = Self::default();
for line in reader.lines() {
list.insert(line?, 1);
}
Ok(list)
}
pub fn total(&self) -> usize {
self.total
}
pub fn iter(&self) -> impl Iterator<Item = (&str, usize)> {
self.words
.iter()
.map(|(word, count)| (word.as_str(), *count))
}
pub fn insert(&mut self, word: String, count: usize) {
let current = self.words.entry(word).or_default();
*current += count;
self.total += count;
}
}