Browse Source

Item in collections

db-refactoring
Coin de Gamma 4 months ago
parent
commit
bf88196b40
  1. 44
      src/db.rs
  2. 8
      src/main.rs

44
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,7 +12,6 @@ pub struct Item {
pub content: String
}
impl Item {
pub fn from(s: String) -> Item {
Item { id: s, content: String::from("") }
@ -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::<Item>::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<Ordering> {
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::<String>
pub items: HashSet::<Item>
}
impl DB {
pub fn new(path: &str) -> io::Result<DB> {
let file = fs::File::open(path)?;
let reader = io::BufReader::new(file);
let mut items = HashSet::<String>::new();
let mut items = HashSet::<Item>::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);
}
}
}
@ -84,14 +77,19 @@ 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(())

8
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) => {

Loading…
Cancel
Save