From 4f73a31cf073f7b0c01f274e7765994f728420a6 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Mon, 5 Dec 2022 23:21:13 -0500 Subject: [PATCH] Added random cache ids. --- src/morethantext/mod.rs | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/src/morethantext/mod.rs b/src/morethantext/mod.rs index f38b865..6b1952c 100644 --- a/src/morethantext/mod.rs +++ b/src/morethantext/mod.rs @@ -1,17 +1,29 @@ 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 rand::{distributions::Alphanumeric, thread_rng, Rng}; +use std::{collections::HashMap, fmt}; const DATA: &str = "data"; +#[derive(Clone)] enum CacheEntry { 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)] -pub struct MoreThanText; +pub struct MoreThanText { + cache: Arc>>, +} impl MoreThanText { pub async fn new(dir: &str) -> Result { @@ -26,13 +38,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 mut cache = self.cache.lock().await; + cache.insert(id.clone(), entry); return id; } + + async fn get_entry(&self, id: &str) -> CacheEntry { + let cache = self.cache.lock().await; + cache.get(id).unwrap().clone() + } } #[cfg(test)] @@ -110,4 +131,14 @@ mod cache { let id2 = mtt.db.add_entry(data2).await; 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); + } }