mirror of
https://github.com/YGGverse/Yoda.git
synced 2026-03-31 16:45:27 +00:00
implement to_string method, prevent memory index overwrite on validation step
This commit is contained in:
parent
cda94cba2e
commit
c86dca53bd
10 changed files with 100 additions and 21 deletions
|
|
@ -23,8 +23,17 @@ impl Memory {
|
|||
/// Add new record with `request` as key and `id` as value
|
||||
/// * validate record with same key does not exist yet
|
||||
pub fn add(&self, request: String, id: i64) -> Result<(), Error> {
|
||||
match self.index.borrow_mut().insert(request, id) {
|
||||
Some(key) => Err(Error::Overwrite(key)), // @TODO prevent?
|
||||
// Borrow shared index access
|
||||
let mut index = self.index.borrow_mut();
|
||||
|
||||
// Prevent existing key overwrite
|
||||
if index.contains_key(&request) {
|
||||
return Err(Error::Overwrite(request));
|
||||
}
|
||||
|
||||
// Slot should be free, let check it twice
|
||||
match index.insert(request, id) {
|
||||
Some(_) => return Err(Error::Unexpected),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
|
@ -34,15 +43,15 @@ impl Memory {
|
|||
pub fn delete(&self, request: &str) -> Result<(), Error> {
|
||||
match self.index.borrow_mut().remove(request) {
|
||||
Some(_) => Ok(()),
|
||||
None => Err(Error::NotFound),
|
||||
None => Err(Error::Unexpected), // @TODO
|
||||
}
|
||||
}
|
||||
|
||||
/// Get `id` by `request` from memory index
|
||||
pub fn get(&self, request: &str) -> Result<i64, Error> {
|
||||
match self.index.borrow().get(request) {
|
||||
Some(&id) => Ok(id),
|
||||
None => Err(Error::NotFound),
|
||||
Some(&value) => Ok(value),
|
||||
None => Err(Error::Unexpected), // @TODO
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,16 @@
|
|||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
NotFound,
|
||||
Overwrite(i64),
|
||||
Overwrite(String),
|
||||
Unexpected,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn to_string(&self) -> String {
|
||||
match self {
|
||||
Self::Overwrite(key) => {
|
||||
format!("Overwrite attempt for existing record `{key}`")
|
||||
}
|
||||
Self::Unexpected => format!("Unexpected error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue