From eb97e3399a8483e7ad7b99ebece1d5f4e8fdd83f Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Sat, 10 Dec 2022 09:26:06 -0500 Subject: [PATCH] Added cache entry identifier. --- src/morethantext/mod.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/morethantext/mod.rs b/src/morethantext/mod.rs index 78d88c0..b359bf0 100644 --- a/src/morethantext/mod.rs +++ b/src/morethantext/mod.rs @@ -1,7 +1,7 @@ pub mod error; use async_std::{ - fs::create_dir, + fs::{create_dir, write}, path::Path, sync::{Arc, Mutex}, }; @@ -16,6 +16,14 @@ enum CacheEntry { Raw(String), } +impl CacheEntry { + fn entry_type(&self) -> String { + match self { + CacheEntry::Raw(_) => "raw".to_string(), + } + } +} + impl fmt::Display for CacheEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -27,13 +35,14 @@ impl fmt::Display for CacheEntry { #[derive(Clone)] pub struct MoreThanText { cache: Arc>>, + dir: String, } impl MoreThanText { pub async fn new(dir: &str) -> Result { let data_dir = Path::new(dir).join(DATA); if !data_dir.is_dir().await { - match create_dir(data_dir).await { + match create_dir(&data_dir).await { Ok(_) => (), Err(err) => { let mut error = DBError::new("failed to create data directory"); @@ -44,11 +53,14 @@ impl MoreThanText { } Ok(Self { cache: Arc::new(Mutex::new(HashMap::new())), + dir: data_dir.to_str().unwrap().to_string(), }) } async fn add_entry(&self, entry: CacheEntry) -> String { 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; cache.insert(id.clone(), entry); return id; @@ -157,6 +169,8 @@ mod cache { let id = mtt.db.add_entry(expected).await; let output = mtt.db.get_entry(&id).await.unwrap(); 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] @@ -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"); + } +}