diff --git a/src/morethantext/mod.rs b/src/morethantext/mod.rs index 9e797f7..d8023e3 100644 --- a/src/morethantext/mod.rs +++ b/src/morethantext/mod.rs @@ -1,13 +1,13 @@ pub mod error; use async_std::{ - fs::{create_dir, write}, + fs::{create_dir, read, write}, path::Path, sync::{Arc, Mutex}, }; use error::DBError; use rand::{distributions::Alphanumeric, thread_rng, Rng}; -use std::{collections::HashMap, fmt}; +use std::{collections::HashMap, fmt, str}; const DATA: &str = "data"; @@ -31,6 +31,19 @@ impl CacheEntry { } return output; } + + fn from_bytes(data: Vec) -> CacheEntry { + let mut data_iter = data.iter(); + let mut holder: u8 = *data_iter.next().unwrap(); + while holder != 0 { + holder = *data_iter.next().unwrap(); + } + let mut output: Vec = Vec::new(); + for letter in data_iter { + output.push(letter.clone()); + } + CacheEntry::Raw(str::from_utf8(&output).unwrap().to_string()) + } } impl fmt::Display for CacheEntry { @@ -90,7 +103,10 @@ impl MoreThanText { let cache = self.cache.lock().await; match cache.get(id) { Some(id) => Ok(id.clone()), - None => Err(DBError::new("cache entry not found")), + None => match read(Path::new(&self.dir).join(&id)).await { + Ok(content) => Ok(CacheEntry::from_bytes(content)), + Err(_) => Err(DBError::new("cache entry not found")), + }, } } @@ -213,6 +229,18 @@ mod cache { assert_eq!(content, expected.to_bytes()); } + #[async_std::test] + async fn retrieve_from_disk() { + let mtt = MTT::new().await; + let id = "someid"; + let data = CacheEntry::Raw("stored".to_string()); + write(mtt.dir.path().join(DATA).join(id), data.to_bytes()) + .await + .unwrap(); + let output = mtt.db.get_entry(id).await.unwrap(); + assert_eq!(output.to_string(), data.to_string()); + } + #[async_std::test] async fn store_bad_file() { let mtt = MTT::new().await; @@ -314,4 +342,12 @@ mod cache_entry { let output = holder.to_bytes(); assert_eq!(output, expected); } + + #[test] + fn raw_from_bytes() { + let holder = CacheEntry::Raw("stored item".to_string()); + let data = holder.to_bytes(); + let output = CacheEntry::from_bytes(data); + assert_eq!(output.to_string(), holder.to_string()); + } }