Compare commits

..

2 Commits

Author SHA1 Message Date
bdcee41dcf Return a cache entry. 2022-12-05 23:23:39 -05:00
4f73a31cf0 Added random cache ids. 2022-12-05 23:21:13 -05:00

View File

@ -1,17 +1,33 @@
pub mod error; pub mod error;
use async_std::{fs::create_dir, path::Path}; use async_std::{
fs::create_dir,
path::Path,
sync::{Arc, Mutex},
};
use error::DBError; use error::DBError;
use rand::{distributions::Alphanumeric, thread_rng, Rng}; use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{collections::HashMap, fmt};
const DATA: &str = "data"; const DATA: &str = "data";
#[derive(Clone)]
enum CacheEntry { enum CacheEntry {
Raw(String), Raw(String),
} }
impl fmt::Display for CacheEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CacheEntry::Raw(s) => write!(f, "{}", s),
}
}
}
#[derive(Clone)] #[derive(Clone)]
pub struct MoreThanText; pub struct MoreThanText {
cache: Arc<Mutex<HashMap<String, CacheEntry>>>,
}
impl MoreThanText { impl MoreThanText {
pub async fn new(dir: &str) -> Result<Self, DBError> { pub async fn new(dir: &str) -> Result<Self, DBError> {
@ -26,13 +42,22 @@ impl MoreThanText {
} }
} }
} }
Ok(Self {}) Ok(Self {
cache: Arc::new(Mutex::new(HashMap::new())),
})
} }
async fn add_entry(&self, _entry: CacheEntry) -> String { async fn add_entry(&self, entry: CacheEntry) -> String {
let id: String = thread_rng().sample_iter(&Alphanumeric).take(32).collect(); let id: String = thread_rng().sample_iter(&Alphanumeric).take(32).collect();
let mut cache = self.cache.lock().await;
cache.insert(id.clone(), entry);
return id; return id;
} }
async fn get_entry(&self, id: &str) -> CacheEntry {
let cache = self.cache.lock().await;
cache.get(id).unwrap().clone()
}
} }
#[cfg(test)] #[cfg(test)]
@ -110,4 +135,14 @@ mod cache {
let id2 = mtt.db.add_entry(data2).await; let id2 = mtt.db.add_entry(data2).await;
assert_ne!(id1, id2, "Ids should be unique.") assert_ne!(id1, id2, "Ids should be unique.")
} }
#[async_std::test]
async fn retrieve_cache() {
let mtt = MTT::new().await;
let data = "something";
let expected = CacheEntry::Raw(data.to_string());
let id = mtt.db.add_entry(expected).await;
let output = mtt.db.get_entry(&id).await;
assert_eq!(output.to_string(), data);
}
} }