diff --git a/src/main.rs b/src/main.rs index 4bb1463..570b4a0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,10 +29,14 @@ fn main() { actions::Action::AdjectiveAdd(word) => { repository::WordList::insert_adjective(&word).unwrap() } + actions::Action::AdjectiveRm(word) => { + repository::WordList::remove_adjective(&word).unwrap() + } actions::Action::MetalList => { show_words(&repository::WordList::find_all_metals().unwrap()) } actions::Action::MetalAdd(word) => repository::WordList::insert_metal(&word).unwrap(), + actions::Action::MetalRm(word) => repository::WordList::remove_metal(&word).unwrap(), _ => unimplemented!(), }, Err(x) => println!("Error {:?}", x), diff --git a/src/repository.rs b/src/repository.rs index fdbecef..c8ea93b 100644 --- a/src/repository.rs +++ b/src/repository.rs @@ -20,6 +20,7 @@ pub enum WordListError { InvalidFormat, InvalidWord, SaveFailure, + NoSuchWord, } impl std::convert::From for WordListError { @@ -75,12 +76,6 @@ impl WordList { Ok(repo.adjectives) } - /// Get the list of all metals - pub fn find_all_metals() -> Result { - let repo = Self::load()?; - Ok(repo.metals) - } - /// Add an adjective to the word list pub fn insert_adjective(adjective: &str) -> Result<(), WordListError> { let mut repo = Self::load()?; @@ -88,6 +83,19 @@ impl WordList { repo.save() } + /// Remove an adjective + pub fn remove_adjective(adjective: &str) -> Result<(), WordListError> { + let mut repo = Self::load()?; + Self::remove_word(adjective, &mut repo.adjectives)?; + repo.save() + } + + /// Get the list of all metals + pub fn find_all_metals() -> Result { + let repo = Self::load()?; + Ok(repo.metals) + } + /// Add a metal to the word list pub fn insert_metal(metal: &str) -> Result<(), WordListError> { let mut repo = Self::load()?; @@ -95,6 +103,13 @@ impl WordList { repo.save() } + /// Remove a metal + pub fn remove_metal(metal: &str) -> Result<(), WordListError> { + let mut repo = Self::load()?; + Self::remove_word(metal, &mut repo.metals)?; + repo.save() + } + /// Generic function to insert words in the storage; the target points in which of the lists /// the word should be inserted. fn insert_word(word: &str, target: &mut WordStorage) -> Result<(), WordListError> { @@ -115,4 +130,21 @@ impl WordList { target.insert(initial, list); Ok(()) } + + /// Generic function to remove a word from the storage; follows the same logic as insert_word. + fn remove_word(word: &str, target: &mut WordStorage) -> Result<(), WordListError> { + let initial = word + .chars() + .nth(0) + .ok_or(WordListError::InvalidWord)? + .to_string() + .to_lowercase(); + let the_word = word.to_string().to_lowercase(); + let list = target.get_mut(&initial).ok_or(WordListError::NoSuchWord)?; + list.remove(&the_word); + if list.is_empty() { + target.remove(&initial); + } + Ok(()) + } }