pub mod auth;
use anyhow::{bail, Result};
pub use auth::Auth;
use std::{collections::HashMap, sync::RwLock};
pub struct Memory {
index: RwLock<HashMap<String, i64>>,
}
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, scope: String, profile_identity_id: i64) -> Result<()> {
let mut index = self.index.write().unwrap();
if index.contains_key(&scope) {
bail!("Overwrite attempt for existing record `{scope}`")
}
match index.insert(scope, profile_identity_id) {
Some(_) => bail!("Unexpected error"),
None => Ok(()),
}
}
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")
}
}
pub fn match_scope(&self, scope: &str) -> Option<Auth> {
let mut result = Vec::new();
for (value, &profile_identity_id) in self.index.read().unwrap().iter() {
if scope.starts_with(value) {
result.push(Auth {
profile_identity_id,
scope: value.clone(),
})
}
}
result.sort_by(|a, b| b.scope.len().cmp(&a.scope.len()));
result.first().cloned()
}
pub fn total(&self, profile_identity_id: i64) -> usize {
let mut total = 0;
for (_, _profile_identity_id) in self.index.read().unwrap().iter() {
if *_profile_identity_id == profile_identity_id {
total += 1
}
}
total
}
}