Added cache entry identifier.
This commit is contained in:
parent
470c6612de
commit
eb97e3399a
@ -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<Mutex<HashMap<String, CacheEntry>>>,
|
||||
dir: String,
|
||||
}
|
||||
|
||||
impl MoreThanText {
|
||||
pub async fn new(dir: &str) -> Result<Self, DBError> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user