diff --git a/src/db.rs b/src/db.rs index 6f5f14a..8aec813 100644 --- a/src/db.rs +++ b/src/db.rs @@ -4,7 +4,7 @@ use std::hash::{Hash, Hasher}; use std::fs; use std::io::{self, Write, BufRead}; use std::fmt; -use std::cmp::PartialEq; +use std::cmp::{PartialEq, Ordering}; pub struct Item { @@ -12,11 +12,10 @@ pub struct Item { pub content: String } - impl Item { pub fn from(s: String) -> Item { Item { id: s, content: String::from("") } - } + } } impl PartialEq for Item { @@ -41,40 +40,34 @@ impl fmt::Display for Item { } } -pub fn test_items() { - let mut item1 = Item::from("item1".to_string()); - item1.content = "some content".to_string(); - let mut item2 = Item::from("item1".to_string()); - item2.content = "other content".to_string(); - - let mut hs = HashSet::::new(); - hs.insert(item1); - hs.insert(item2); - - for item in hs.iter() { - println!("item: {}", item) +impl PartialOrd for Item { + fn partial_cmp(&self, other: &Self) -> Option { + self.id.partial_cmp(&other.id) } - } +impl Ord for Item { + fn cmp(&self, other: &Self) -> Ordering { + self.id.cmp(&other.id) + } +} pub struct DB { - pub items: HashSet:: + pub items: HashSet:: } - impl DB { pub fn new(path: &str) -> io::Result { let file = fs::File::open(path)?; let reader = io::BufReader::new(file); - let mut items = HashSet::::new(); + let mut items = HashSet::::new(); for line in reader.lines() { match line { - Ok(content) => { - items.insert(content); + Ok(id) => { + items.insert(Item::from(id)); }, Err(e) => { - eprintln!("Error reading line , {}", e); + eprintln!("Error reading line, {}", e); } } } @@ -83,15 +76,20 @@ impl DB { }; Ok(result) } - + + pub fn contains(&self, id: &String) -> bool { + let item = Item::from(id.clone()); + self.items.contains(&item) + } + pub fn dump(&self, path: &str) -> io::Result<()> { let mut file = fs::OpenOptions::new() .write(true) .append(false) .open(path)?; - for id in self.items.iter() { - writeln!(file, "{}", id)?; + for item in self.items.iter() { + writeln!(file, "{}", item.id)?; } Ok(()) diff --git a/src/main.rs b/src/main.rs index a8c0e7b..f4d1430 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ mod db; -use db::DB; +use db::{DB, Item}; use clap::{Parser, Subcommand}; @@ -62,7 +62,7 @@ fn init() -> io::Result<()> { fn add(id: &String) -> io::Result<()> { let mut db = DB::new(STORAGE_PATH)?; - if db.items.contains(id) { + if db.contains(id) { // TODO: ask to edit existing in outer function which invoked this one return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -70,7 +70,7 @@ fn add(id: &String) -> io::Result<()> { )) } - db.items.insert(id.clone()); + db.items.insert(Item::from(id.clone())); db.dump(STORAGE_PATH)?; Ok(()) @@ -87,8 +87,6 @@ fn list() -> io:: Result<()> { } fn main() -> io::Result<()> { - db::test_items(); - return Ok(()); let cli = Cli::parse(); match &cli.command { Some(Commands::Init) => {