i’m working on an application where user makes changes to files from the app ui, those changes will have a debounced temporary save (every 3 seconds) and a “hard” save (button press or cmd+s
) functionality.
in rust side, temporary save should put those items in a queue. now, if multiple changes are made to the same file, i want to update the existing entry in the queue instead of adding a new one.
when the user does a “hard” save, all pending changes would be written to the filesystem.
i’m planning to use a HashMap
for the queue. here’s a rough implementation of what i’m thinking
use std::collections::HashMap;
use std::time::SystemTime;
struct ChangeData {
content: String,
last_modified: SystemTime,
}
struct SaveQueue {
queue: HashMap<String, ChangeData>, // file path would be the key
}
impl SaveQueue {
fn new() -> Self {
SaveQueue {
queue: HashMap::new(),
}
}
fn add_or_update_change(&mut self, file_path: String, content: String) {
let now = SystemTime::now();
let change = ChangeData {
content,
last_modified: now,
};
self.queue.insert(file_path, change);
}
fn save_changes(&mut self) {
for (file_path, change_data) in &self.queue {
self.write_to_file_system(file_path, &change_data.content);
}
self.queue.clear();
}
fn write_to_file_system(&self, file_path: &str, content: &str) {
println!("Saving to {}: {}", file_path, content);
}
}
is this a good idea? are there any better approaches?
2