Hey I have this code, can you check it out and say something about it? use…
- User
Hey I have this code, can you check it out and say something about it? use std::collections::HashMap; use std::fmt; use std::fmt::Formatter; use std::fs::File; use std::io::{BufWriter, BufReader}; use nanoid::nanoid; use serde::{Deserialize, Serialize}; use serde_json::{json, Value};
fn main() { let mut database = Database::new("new_one!"); let collection = database.add_collection("skibidi") .expect("Could not add skibidi"); let index = collection.add(json!("Hello world!")); collection.add(json!("dop dop")); collection.add(json!("yes yes"));
let option = collection.get(index.as_str()); match option { Some(val) => println!("This is brand new publish: {:#?}", val), None => println!("There is no brand new publish"), } collection.update_document(index.as_str(), json!("Good day America!")); let option = collection.get(index.as_str()); match option { Some(val) => println!("I update it to this: {:#?}", val), None => println!("I can't update this thing :C"), } let m_collection = database.add_collection("merzost"); m_collection.unwrap().add(json!("sopmething")); database.save_database();}
#[derive(Debug)] pub enum DatabaseError { CollectionAlreadyExists(String), CollectionNotFound(String), DocumentNotFound(String), CouldNotCreateDbFile(String), CouldNotSerializeDatabase(String), CouldNotOpenDbFile(String), CouldNotOpenedReadDbFile(String), } impl fmt::Display for DatabaseError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { DatabaseError::CollectionAlreadyExists(name) => write!(f, "Collection {} already exists", name), DatabaseError::CollectionNotFound(name) => write!(f, "Collection {} not found", name), DatabaseError::DocumentNotFound(index) => write!(f, "Document {} not found", index), DatabaseError::CouldNotCreateDbFile(path) => write!(f, "Could not create db file: {}", path), DatabaseError::CouldNotSerializeDatabase(name) => write!(f, "Could not serialize database {}", name), DatabaseError::CouldNotOpenDbFile(filepath) => write!(f, "Could not open db file: {}", filepath), DatabaseError::CouldNotOpenedReadDbFile(filepath) => write!(f, "Could not open db file: {}", filepath), } } }
#[derive(Serialize, Deserialize, Debug, Clone)] pub struct Document { content: Value, } #[derive(Serialize, Deserialize, Debug)] pub struct Collection { name: String, documents: HashMap<String, Document>, }
#[derive(Serialize, Deserialize, Debug)] pub struct Database { name: String, collections: HashMap<String, Collection>, }
impl Database { pub fn new(name: &str) -> Database { Database { name: name.to_string(), collections: HashMap::new() } }
pub fn iter(&self) -> impl Iterator<Item=&Collection> { self.collections.values() } pub fn add_collection(&mut self, name: &str) -> Result<&mut Collection, DatabaseError> { if self.collections.contains_key(name) { return Err(DatabaseError::CollectionAlreadyExists(name.to_string())); } let collection = Collection::new(name); self.collections.insert(name.to_string(), collection); Ok(self.collections.get_mut(name) .expect("Something went wrong on getting new collection!")) } pub fn get_collection(&self, name: &str) -> Result<&Collection, DatabaseError> { self.collections.get(name) .ok_or_else(|| DatabaseError::DocumentNotFound(name.to_string())) } pub fn get_all_collections(&self) -> Vec<&Collection> { self.collections.values().collect() } pub fn get_all_collections_iter(&self) -> impl Iterator<Item=&Collection> { self.collections.values() } pub fn remove(&mut self, name: &str) -> Result<Collection, DatabaseError> { self.collections.remove(name) .ok_or_else(|| DatabaseError::CollectionNotFound(name.to_string())) } pub fn save_database(&mut self) -> Result<(), DatabaseError> { let path = format!("./{}.json", self.name); let file = File::create(path) .map_err(|_e| DatabaseError::CouldNotCreateDbFile(self.name.clone()))?; let buf_writer = BufWriter::new(file); serde_json::to_writer_pretty(buf_writer, &self) .map_err(|_e| DatabaseError::CouldNotSerializeDatabase(self.name.clone()))?; Ok(()) } // Load database from a file pub fn load_database(filepath: &str) -> Result<Database, DatabaseError> { let file = File::open(filepath) .map_err(|_e| DatabaseError::CouldNotOpenDbFile(filepath.to_string()))?; let reader = BufReader::new(file); let database = serde_json::from_reader(reader) .map_err(|_e| DatabaseError::CouldNotOpenedReadDbFile(filepath.to_string()))?; Ok(database) } - Assistant