Skip to content

Instantly share code, notes, and snippets.

@Marmiz
Created December 26, 2020 15:35
Show Gist options
  • Select an option

  • Save Marmiz/b659c7835054d25513106e3804c4539f to your computer and use it in GitHub Desktop.

Select an option

Save Marmiz/b659c7835054d25513106e3804c4539f to your computer and use it in GitHub Desktop.
Second portion of to-do cli in Rust
use std::collections::HashMap;
use std::io::Read;
use std::str::FromStr;
fn main() {
let action = std::env::args().nth(1).expect("Please specify an action");
let item = std::env::args().nth(2).expect("Please specify an item");
let mut todo = Todo::new().expect("Initialisation of db failed");
if action == "add" {
todo.insert(item);
match todo.save() {
Ok(_) => println!("todo saved"),
Err(why) => println!("An error occurred: {}", why),
}
};
}
struct Todo {
// use rust built in HashMap to store key - val pairs
map: HashMap<String, bool>,
}
impl Todo {
fn new() -> Result<Todo, std::io::Error> {
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.read(true)
.open("db.txt")?;
let mut content = String::new();
f.read_to_string(&mut content)?;
let map: HashMap<String, bool> = content
.lines()
.map(|line| line.splitn(2, '\t').collect::<Vec<&str>>())
.map(|v| (v[0], v[1]))
.map(|(k, v)| (String::from(k), bool::from_str(v).unwrap()))
.collect();
Ok(Todo { map })
}
fn insert(&mut self, key: String) {
// insert a new item into our map.
// we pass true as value.
self.map.insert(key, true);
}
fn save(self) -> Result<(), std::io::Error> {
let mut content = String::new();
for (k, v) in self.map {
let record = format!("{}\t{}\n", k, v);
content.push_str(&record)
}
std::fs::write("db.txt", content)
}
}
@aucru
Copy link
Copy Markdown

aucru commented Jul 28, 2023

Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment