From 390410cb44294a96b1c3b0cd20106837c162d4e2 Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Sun, 8 Dec 2024 22:10:24 +0530 Subject: [PATCH] new create for manipulating properties --- rust/Cargo.toml | 2 +- rust/property/Cargo.toml | 6 +++++ rust/property/src/lib.rs | 57 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 rust/property/Cargo.toml create mode 100644 rust/property/src/lib.rs 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(); + } +} + -- 2.45.2