From: Ramakrishnan Muthukrishnan Date: Sun, 8 Dec 2024 16:40:24 +0000 (+0530) Subject: new create for manipulating properties X-Git-Url: https://git.rkrishnan.org/Site/Content/simplejson/status?a=commitdiff_plain;h=390410cb44294a96b1c3b0cd20106837c162d4e2;p=pihpsdr.git new create for manipulating properties --- diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 0958446..1f226d4 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,3 +1,3 @@ [workspace] resolver = "2" -members = [ "discovery" ] +members = [ "discovery" , "property"] diff --git a/rust/property/Cargo.toml b/rust/property/Cargo.toml new file mode 100644 index 0000000..acc446a --- /dev/null +++ b/rust/property/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "property" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/rust/property/src/lib.rs b/rust/property/src/lib.rs new file mode 100644 index 0000000..c7be823 --- /dev/null +++ b/rust/property/src/lib.rs @@ -0,0 +1,57 @@ +use std::{collections::HashMap, io::{Read, Write}, path::Path}; + +struct Property { + props: HashMap, + path: String, +} + +impl Property { + pub fn init(path: &Path) -> Result { + let maybe_file = std::fs::File::open(path); + match maybe_file { + Ok(mut file) => { + // each line is of the form prop=value + let mut buf = String::new(); + let mut props = HashMap::new(); + file.read_to_string(&mut buf).unwrap(); + let words: Vec<&str> = buf.split('\n').collect(); + words.iter().for_each(|w| { + let kvs = w.split('=').collect::>(); + props.insert(kvs[0].to_string(), kvs[1].to_string()); + }); + Ok(Property{ + props: props, + path: path.to_string_lossy().to_string(), + }) + }, + Err(e) => { + println!("file path {} does not exist", path.to_str().unwrap()); + Err(e) + } + } + } + + // save the table into the resource indicated by the path + pub fn save(&self) -> Result<(), std::io::Error>{ + let mut file = std::fs::File::create(&self.path)?; + + for (key, value) in self.props.iter() { + let line = format!("{}={}", key, value); + let _ = file.write(&line.as_bytes()); + } + Ok(()) + } + + pub fn get(&self, s: &str) -> Option<&str> { + self.props.get(s).map(|x| x.as_str()) + } + + pub fn set(&mut self, k: &str, v: &str) { + self.props.insert(k.to_string(), v.to_string()); + } + + pub fn clear_all(&mut self) { + self.props = HashMap::new(); + } +} +