implement to_string method, prevent memory index overwrite on validation step

This commit is contained in:
yggverse 2024-11-23 18:04:57 +02:00
parent cda94cba2e
commit c86dca53bd
10 changed files with 100 additions and 21 deletions

View file

@ -3,3 +3,16 @@ pub enum Error {
Database(sqlite::Error),
Gemini(super::gemini::Error),
}
impl Error {
pub fn to_string(&self) -> String {
match self {
Self::Database(reason) => {
format!("Database error: {}", reason.to_string())
}
Self::Gemini(reason) => {
format!("Could not init Gemini identity: {}", reason.to_string())
}
}
}
}

View file

@ -1,7 +1,22 @@
#[derive(Debug)]
pub enum Error {
Auth(super::auth::Error),
Certificate(Box<dyn std::error::Error>), // @TODO
Certificate(Box<dyn std::error::Error>),
Database(sqlite::Error),
Memory(super::memory::Error),
}
impl Error {
pub fn to_string(&self) -> String {
match self {
Self::Auth(reason) => format!("Could not create auth: {}", reason.to_string()),
Self::Certificate(reason) => {
format!("Could not create certificate: {}", reason.to_string())
}
Self::Database(reason) => {
format!("Database error: {}", reason.to_string())
}
Self::Memory(reason) => format!("Memory error: {}", reason.to_string()),
}
}
}

View file

@ -22,9 +22,18 @@ impl Memory {
/// Add new record with `id` as key and `pem` as value
/// * validate record with same key does not exist yet
pub fn add(&self, id: i64, pem: String) -> Result<(), Error> {
match self.index.borrow_mut().insert(id, pem) {
Some(key) => Err(Error::Overwrite(key)), // @TODO prevent?
pub fn add(&self, profile_identity_gemini_id: i64, pem: String) -> Result<(), Error> {
// Borrow shared index access
let mut index = self.index.borrow_mut();
// Prevent existing key overwrite
if index.contains_key(&profile_identity_gemini_id) {
return Err(Error::Overwrite(profile_identity_gemini_id));
}
// Slot should be free, let check it twice
match index.insert(profile_identity_gemini_id, pem) {
Some(_) => return Err(Error::Unexpected),
None => Ok(()),
}
}

View file

@ -2,5 +2,21 @@
pub enum Error {
Clear,
NotFound(i64),
Overwrite(String),
Overwrite(i64),
Unexpected,
}
impl Error {
pub fn to_string(&self) -> String {
match self {
Self::Clear => format!("Could not cleanup memory index"),
Self::NotFound(key) => {
format!("Record `{key}` not found in memory index")
}
Self::Overwrite(key) => {
format!("Overwrite attempt for existing record `{key}`")
}
Self::Unexpected => format!("Unexpected error"),
}
}
}