#![cfg(feature = "debug")]
use std::collections::HashMap;
use async_trait::async_trait;
use crate::error::generator::PersistError;
use std::sync::Mutex;
use super::DEKPersisterTrait;
#[derive(Debug)]
pub struct MemPersister(Mutex<HashMap<String, Vec<u8>>>);
impl MemPersister {
pub fn new() -> Self {
MemPersister(Mutex::new(HashMap::new()))
}
pub async fn insert(&self, context: String, dek: Vec<u8>) -> Result<Vec<u8>, PersistError> {
let data = self.0.lock();
let context = hex::encode(context);
match data {
Ok(mut data) => {
data.insert(context.clone(), dek);
data.get(&context)
.cloned()
.ok_or(PersistError::Error("Could not insert!".to_string()))
}
Err(_) => Err(PersistError::Error("Mutex error!".to_string())),
}
}
pub async fn fetch(&self, context: String) -> Result<Vec<u8>, PersistError> {
let context = hex::encode(context);
match self.0.lock() {
Ok(data) =>
data
.get(&context)
.cloned()
.ok_or(PersistError::NoKey("Could not fetch!".to_string())),
Err(_) => Err(PersistError::Error("Mutex Error!".to_string())),
}
}
}
#[async_trait]
impl DEKPersisterTrait for MemPersister {
async fn persist(&self, key: &Vec<u8>, context: String) -> Result<Vec<u8>, PersistError> {
self.insert(context, key.clone()).await
}
async fn fetch(&self, context: String) -> Result<Vec<u8>, PersistError> {
match self.fetch(context).await {
Ok(key) => Ok(key.clone()),
Err(e) => Err(e),
}
}
}