From d520d22a1039cc448493d512067f6c4e7b541a60 Mon Sep 17 00:00:00 2001 From: Ishan Bhanuka Date: Thu, 14 Mar 2024 01:08:14 -0400 Subject: [PATCH] Remove callback style for reading file --- fs-storage/src/bin/cli.rs | 24 +++++++++---------- fs-storage/src/file_storage.rs | 43 ++++++++-------------------------- 2 files changed, 21 insertions(+), 46 deletions(-) diff --git a/fs-storage/src/bin/cli.rs b/fs-storage/src/bin/cli.rs index 79ec3112..798d8307 100644 --- a/fs-storage/src/bin/cli.rs +++ b/fs-storage/src/bin/cli.rs @@ -25,22 +25,20 @@ fn main() { vec![] }; let mut fs = FileStorage::new("cli".to_string(), Path::new(path)); - fs.read_file(|map: HashMap| { - if keys.is_empty() { - for (key, value) in map { + let map: HashMap = fs.read_file().unwrap(); + if keys.is_empty() { + for (key, value) in map { + println!("{}: {}", key, value); + } + } else { + for key in &keys { + if let Some(value) = map.get(key) { println!("{}: {}", key, value); - } - } else { - for key in &keys { - if let Some(value) = map.get(key) { - println!("{}: {}", key, value); - } else { - println!("Key '{}' not found", key); - } + } else { + println!("Key '{}' not found", key); } } - }) - .unwrap(); + } } "write" => { if args.len() < 4 { diff --git a/fs-storage/src/file_storage.rs b/fs-storage/src/file_storage.rs index 1973a426..85a80e03 100644 --- a/fs-storage/src/file_storage.rs +++ b/fs-storage/src/file_storage.rs @@ -31,43 +31,20 @@ impl FileStorage { } } + /// Check if underlying file has been updated + /// + /// This check can be used before reading the file. + pub fn is_file_updated(&self) -> Result { + let file_timestamp = fs::metadata(&self.path)?.modified()?; + Ok(self.timestamp < file_timestamp) + } + /// Read data from disk /// /// Data is read as a key value pairs separated by a symbol and stored /// in a [HashMap] with a generic key K and V value. A handler /// is called on the data after reading it. - pub fn read_file( - &mut self, - mut handle: impl FnMut(HashMap), - ) -> Result<()> - where - K: FromStr + std::hash::Hash + std::cmp::Eq + Debug, - V: FromStr + Debug, - ArklibError: From<::Err>, - ArklibError: From<::Err>, - { - let new_timestamp = fs::metadata(&self.path)?.modified()?; - log::info!( - "timestamp of storage file {:?} is {:?}", - self.path, - self.timestamp - ); - - if self.timestamp >= new_timestamp { - return Ok(()); - } - - log::info!("the file was modified externally, merging"); - - let value_by_id = self.read_file_from_disk()?; - if !value_by_id.is_empty() { - handle(value_by_id); - } - - Ok(()) - } - - fn read_file_from_disk(&mut self) -> Result> + pub fn read_file(&mut self) -> Result> where K: FromStr + std::hash::Hash + std::cmp::Eq + Debug, V: FromStr + Debug, @@ -214,7 +191,7 @@ mod tests { .expect("Failed to write data to disk"); let data_read: HashMap<_, _> = file_storage - .read_file_from_disk() + .read_file() .expect("Failed to read data from disk"); assert_eq!(data_read, data_to_write);