]> git.rkrishnan.org Git - pihpsdr.git/commitdiff
new create for manipulating properties
authorRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Sun, 8 Dec 2024 16:40:24 +0000 (22:10 +0530)
committerRamakrishnan Muthukrishnan <ram@rkrishnan.org>
Sun, 8 Dec 2024 16:40:24 +0000 (22:10 +0530)
rust/Cargo.toml
rust/property/Cargo.toml [new file with mode: 0644]
rust/property/src/lib.rs [new file with mode: 0644]

index 0958446ba6ea0aba1881e28ad2e947097d01a287..1f226d406c0fa0b77e2f0250d9bdf2b0fedcef38 100644 (file)
@@ -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 (file)
index 0000000..acc446a
--- /dev/null
@@ -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 (file)
index 0000000..c7be823
--- /dev/null
@@ -0,0 +1,57 @@
+use std::{collections::HashMap, io::{Read, Write}, path::Path};
+
+struct Property {
+    props: HashMap<String, String>,
+    path: String,
+}
+
+impl Property {
+    pub fn init(path: &Path) -> Result<Self, std::io::Error> {
+        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::<Vec<&str>>();
+                    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();
+    }
+}
+