use std::{collections::HashMap, cell::RefCell, sync::{Mutex, Arc}};
use crate::value::Value;
pub trait Store {
type Item;
fn pipes(&self, key: &str, result: Value);
fn print(&self) ;
fn print_json(&self);
fn count(&self, key: &str) -> usize;
fn get(&self, key:&str) -> Value;
}
pub trait Item {
type Output;
fn build(x: Self::Output) -> Box<Self::Output> where Self: Sized { Box::new(x) }
}
#[derive(Clone, Debug)]
pub struct Person {
pub name: String,
pub age: u32,
}
impl Item for Person {
type Output = Person;
}
pub struct Cache {
caches: Arc<Mutex<RefCell::<HashMap<String,Value>>>>,
}
impl Cache {
pub fn new() -> Self {
Cache {
caches: Arc::new(Mutex::new(RefCell::new(HashMap::new()))),
}
}
}
impl Store for Cache {
type Item = Value;
fn pipes(&self, key: &str, result: Self::Item) {
let caches = Arc::clone(&self.caches);
let caches = caches.lock().unwrap();
(*caches).borrow_mut().insert(key.to_string(), result);
}
fn print_json(&self) {
for (k, v) in self.caches.lock().unwrap().borrow().iter() {
let data = serde_json::to_string(v).expect("not Serialize to string");
println!("Key -- {:?} Value -- {:?}", k, data);
}
}
fn print(&self) {
for (k, v) in self.caches.lock().unwrap().borrow().iter() {
println!("Key -- {:?} Value -- {:?}", k, v);
}
}
fn count(&self, key:&str) -> usize {
let mut counter = 0;
for (k, v) in self.caches.lock().unwrap().borrow().iter() {
if k == key {
match v {
Value::LIST(c) => counter = c.len(),
_ => counter = 1
};
}
}
counter
}
fn get(&self, key:&str) -> Value {
for (k, v) in self.caches.lock().unwrap().borrow().iter() {
if k == key {
let data = serde_json::to_string(v).expect("not Serialize to string");
let result = serde_json::from_str::<Value>(data.as_str()).expect("not Deserialize to string");
return result;
}
}
Value::NULL
}
}