Skip to content

Instantly share code, notes, and snippets.

@chgeuer
Created September 14, 2021 09:43
Show Gist options
  • Save chgeuer/e0eb3ae6e6d0810e926e4c873893a7f2 to your computer and use it in GitHub Desktop.
Save chgeuer/e0eb3ae6e6d0810e926e4c873893a7f2 to your computer and use it in GitHub Desktop.
Strike Training Solution
// My solution to https://strikecommunity.azurewebsites.net/articles/8612/course-introduction-to-the-rust-programming-langua-1.html
use std::collections::HashMap;
fn main() -> Result<(), std::io::Error> {
let mut arguments = std::env::args().skip(1);
let k = arguments.next().unwrap();
let v = arguments.next().unwrap();
let mut db = Database::from_disk("kv.db")?;
println!("Key: {} Value: {}", k, v);
db.insert(k, v);
db.insert("tuu".to_string(), "ni".to_string());
db.flush()?;
Ok(())
}
struct Database {
path: String,
hashmap: HashMap<String, String>,
}
impl Database {
fn from_disk(path: &str) -> std::io::Result<Database> {
let hashmap = std::fs::read_to_string(path)?
.lines()
.map(|line| {
let mut chunks = line.split('\t');
let k = chunks.next().unwrap().to_string();
let v = chunks.next().unwrap().to_string();
(k, v)
})
.into_iter()
.collect();
Ok(Database {
path: path.to_string(),
hashmap,
})
}
fn insert(&mut self, k: String, v: String) {
self.hashmap.insert(k, v);
}
fn flush(&self) -> std::io::Result<()> {
let contents = self
.hashmap
.iter()
.map(|(k, v)| format!("{}\t{}", k, v))
.collect::<Vec<String>>()
.join("\n");
std::fs::write(&self.path, contents)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment