Added cache entry identifier.

This commit is contained in:
Jeff Baskin 2022-12-10 09:26:06 -05:00
parent 470c6612de
commit eb97e3399a

View File

@ -1,7 +1,7 @@
pub mod error; pub mod error;
use async_std::{ use async_std::{
fs::create_dir, fs::{create_dir, write},
path::Path, path::Path,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@ -16,6 +16,14 @@ enum CacheEntry {
Raw(String), Raw(String),
} }
impl CacheEntry {
fn entry_type(&self) -> String {
match self {
CacheEntry::Raw(_) => "raw".to_string(),
}
}
}
impl fmt::Display for CacheEntry { impl fmt::Display for CacheEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
@ -27,13 +35,14 @@ impl fmt::Display for CacheEntry {
#[derive(Clone)] #[derive(Clone)]
pub struct MoreThanText { pub struct MoreThanText {
cache: Arc<Mutex<HashMap<String, CacheEntry>>>, cache: Arc<Mutex<HashMap<String, CacheEntry>>>,
dir: String,
} }
impl MoreThanText { impl MoreThanText {
pub async fn new(dir: &str) -> Result<Self, DBError> { pub async fn new(dir: &str) -> Result<Self, DBError> {
let data_dir = Path::new(dir).join(DATA); let data_dir = Path::new(dir).join(DATA);
if !data_dir.is_dir().await { if !data_dir.is_dir().await {
match create_dir(data_dir).await { match create_dir(&data_dir).await {
Ok(_) => (), Ok(_) => (),
Err(err) => { Err(err) => {
let mut error = DBError::new("failed to create data directory"); let mut error = DBError::new("failed to create data directory");
@ -44,11 +53,14 @@ impl MoreThanText {
} }
Ok(Self { Ok(Self {
cache: Arc::new(Mutex::new(HashMap::new())), cache: Arc::new(Mutex::new(HashMap::new())),
dir: data_dir.to_str().unwrap().to_string(),
}) })
} }
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 file = Path::new(&self.dir).join(&id);
write(file, "a").await.unwrap();
let mut cache = self.cache.lock().await; let mut cache = self.cache.lock().await;
cache.insert(id.clone(), entry); cache.insert(id.clone(), entry);
return id; return id;
@ -157,6 +169,8 @@ mod cache {
let id = mtt.db.add_entry(expected).await; let id = mtt.db.add_entry(expected).await;
let output = mtt.db.get_entry(&id).await.unwrap(); let output = mtt.db.get_entry(&id).await.unwrap();
assert_eq!(output.to_string(), data); assert_eq!(output.to_string(), data);
let dfile = mtt.dir.path().join(DATA).join(&id);
assert!(dfile.is_file(), "Cache file should exist.");
} }
#[async_std::test] #[async_std::test]
@ -194,3 +208,14 @@ mod cache {
} }
} }
} }
#[cfg(test)]
mod cache_entry {
use super::*;
#[test]
fn raw_type() {
let holder = CacheEntry::Raw("nothing important".to_string());
assert_eq!(holder.entry_type(), "raw");
}
}