Skip to content

Commit

Permalink
Move erase logic to pub function
Browse files Browse the repository at this point in the history
  • Loading branch information
twitu committed Mar 14, 2024
1 parent 694194d commit 16c6450
Showing 1 changed file with 24 additions and 27 deletions.
51 changes: 24 additions & 27 deletions fs-storage/src/file_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ impl FileStorage {
let mut lines = reader.lines();

match lines.next() {
Some(Ok(header)) => {
Some(header) => {
let header = header?;
self.verify_version(&header)?;

let mut value_by_id = HashMap::new();
Expand All @@ -101,7 +102,6 @@ impl FileStorage {

Ok(value_by_id)
}
Some(Err(e)) => Err(e.into()),
None => Err(ArklibError::Storage(
self.label.clone(),
"Storage file is missing header".to_owned(),
Expand Down Expand Up @@ -149,6 +149,16 @@ impl FileStorage {
Ok(())
}

pub fn erase(&self) {
if let Err(e) = fs::remove_file(&self.path) {
log::error!(
"{} Failed to delete file because of error: {}",
self.log_prefix,
e
)
}
}

/// Verify the version stored in the file header
fn verify_version(&self, header: &str) -> Result<()> {
if !header.starts_with(STORAGE_VERSION_PREFIX) {
Expand All @@ -171,20 +181,8 @@ impl FileStorage {
),
));
}

Ok(())
}
}

impl Drop for FileStorage {
fn drop(&mut self) {
if let Err(e) = fs::remove_file(&self.path) {
log::error!(
"{} Failed to delete file because of error: {}",
self.log_prefix,
e
)
}
Ok(())
}
}

Expand Down Expand Up @@ -225,21 +223,20 @@ mod tests {
TempDir::new().expect("Failed to create temporary directory");
let storage_path = temp_dir.path().join("test_storage.txt");

// File storage should be dropped and the file deleted after this scope
{
let mut file_storage =
FileStorage::new("TestStorage".to_string(), &storage_path);
let mut file_storage =
FileStorage::new("TestStorage".to_string(), &storage_path);

let mut data_to_write = HashMap::new();
data_to_write.insert("key1".to_string(), "value1".to_string());
data_to_write.insert("key2".to_string(), "value2".to_string());
let mut data_to_write = HashMap::new();
data_to_write.insert("key1".to_string(), "value1".to_string());
data_to_write.insert("key2".to_string(), "value2".to_string());

file_storage
.write_file(&data_to_write)
.expect("Failed to write data to disk");
file_storage
.write_file(&data_to_write)
.expect("Failed to write data to disk");

assert_eq!(storage_path.exists(), true);
}
assert_eq!(storage_path.exists(), true);

file_storage.erase();

assert_eq!(storage_path.exists(), false);
}
Expand Down

0 comments on commit 16c6450

Please sign in to comment.