pub mod auth;
pub mod error;
pub use auth::Auth;
pub use error::Error;
use std::{cell::RefCell, collections::HashMap};
pub struct Memory {
index: RefCell<HashMap<String, i64>>,
}
impl Default for Memory {
fn default() -> Self {
Self::new()
}
}
impl Memory {
pub fn new() -> Self {
Self {
index: RefCell::new(HashMap::new()),
}
}
pub fn add(&self, scope: String, profile_identity_gemini_id: i64) -> Result<(), Error> {
let mut index = self.index.borrow_mut();
if index.contains_key(&scope) {
return Err(Error::Overwrite(scope));
}
match index.insert(scope, profile_identity_gemini_id) {
Some(_) => Err(Error::Unexpected),
None => Ok(()),
}
}
pub fn clear(&self) -> Result<(), Error> {
let mut index = self.index.borrow_mut();
index.clear();
if index.is_empty() {
Ok(())
} else {
Err(Error::Clear)
}
}
pub fn match_scope(&self, request: &str) -> Option<Auth> {
let mut result = Vec::new();
for (scope, &profile_identity_gemini_id) in self.index.borrow().iter() {
if request.starts_with(scope) {
result.push(Auth {
profile_identity_gemini_id,
scope: scope.clone(),
})
}
}
result.sort_by(|a, b| b.scope.len().cmp(&a.scope.len()));
result.first().cloned()
}
}