Made sure that cache did not over write itself.

This commit is contained in:
Jeff Baskin 2023-07-18 11:44:49 -04:00
parent e49d6f5e46
commit 49b0eaf2ec
1 changed files with 44 additions and 1 deletions

View File

@ -99,6 +99,18 @@ impl Cache {
output
}
fn next_id(&mut self) -> String {
let mut id: String;
loop {
id = self.ids.next().unwrap();
match self.get(&id) {
FromCache::Error(_) => break,
_ => (),
}
}
id
}
pub async fn listen(&mut self, listener: Receiver<ToCache>) {
loop {
match listener.recv().await.unwrap() {
@ -132,7 +144,7 @@ impl Cache {
}
};
for name in data.list() {
let id = self.ids.next().unwrap();
let id = self.next_id();
match store.add_by_id(name, &id) {
Ok(_) => {
self.data.insert(id, FromCache::DB(Database::new()));
@ -244,6 +256,37 @@ mod engine {
),
}
}
#[async_std::test]
async fn ids_are_not_overwritten() {
let ids = ["first", "first", "second"];
let names = ["barney", "fred"];
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), ids).await;
let mut store1 = Store::new();
store1.add(names[0]).unwrap();
let mut store2 = Store::new();
store2.add(names[1]).unwrap();
cache.commit(store1);
cache.commit(store2);
assert_eq!(
cache.data.len(),
3,
"cache.data had the following entries {:?}",
cache.data.keys()
);
}
#[async_std::test]
async fn no_duplicate_ids() {
let ids = ["one", "two"];
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), ids).await;
cache
.data
.insert(ids[0].to_string(), FromCache::DB(Database::new()));
assert_eq!(cache.next_id(), ids[1]);
}
}
#[cfg(test)]