use anyhow::{bail, Result};
use std::{collections::HashMap, sync::RwLock};
pub struct Memory {
index: RwLock<HashMap<i64, String>>,
}
impl Default for Memory {
fn default() -> Self {
Self::new()
}
}
impl Memory {
pub fn new() -> Self {
Self {
index: RwLock::new(HashMap::new()),
}
}
pub fn add(&self, profile_identity_id: i64, pem: String) -> Result<()> {
let mut index = self.index.write().unwrap();
if index.contains_key(&profile_identity_id) {
bail!("Overwrite attempt for existing record `{profile_identity_id}`")
}
match index.insert(profile_identity_id, pem) {
Some(_) => bail!("Unexpected error"),
None => Ok(()),
}
}
pub fn get(&self, id: i64) -> Result<String> {
match self.index.read().unwrap().get(&id) {
Some(pem) => Ok(pem.clone()),
None => bail!("Record `{id}` not found in memory index"),
}
}
pub fn clear(&self) -> Result<()> {
let mut index = self.index.write().unwrap();
index.clear();
if index.is_empty() {
Ok(())
} else {
bail!("Could not cleanup memory index")
}
}
}