Skip to content

Commit

Permalink
Remove callback style for reading file
Browse files Browse the repository at this point in the history
  • Loading branch information
twitu committed Mar 14, 2024
1 parent 6c42956 commit d520d22
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 46 deletions.
24 changes: 11 additions & 13 deletions fs-storage/src/bin/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,20 @@ fn main() {
vec![]
};
let mut fs = FileStorage::new("cli".to_string(), Path::new(path));
fs.read_file(|map: HashMap<String, String>| {
if keys.is_empty() {
for (key, value) in map {
let map: HashMap<String, String> = 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 {
Expand Down
43 changes: 10 additions & 33 deletions fs-storage/src/file_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<bool> {
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<K, V>(
&mut self,
mut handle: impl FnMut(HashMap<K, V>),
) -> Result<()>
where
K: FromStr + std::hash::Hash + std::cmp::Eq + Debug,
V: FromStr + Debug,
ArklibError: From<<K as FromStr>::Err>,
ArklibError: From<<V as FromStr>::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<K, V>(&mut self) -> Result<HashMap<K, V>>
pub fn read_file<K, V>(&mut self) -> Result<HashMap<K, V>>
where
K: FromStr + std::hash::Hash + std::cmp::Eq + Debug,
V: FromStr + Debug,
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit d520d22

Please sign in to comment.