add conditional put

This commit is contained in:
Sebastian Hugentobler 2022-03-30 09:36:59 +02:00
parent b4fcbdfef8
commit 547b7b375a
Signed by: shu
GPG key ID: BB32CF3CA052C2F0
7 changed files with 87 additions and 21 deletions

View file

@ -1,3 +1,4 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use thiserror::Error;
@ -25,6 +26,23 @@ pub struct Account {
pub is_active: bool,
}
impl Account {
pub fn hash_string(&self) -> String {
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
format!("{:x}", hasher.finish())
}
}
impl Hash for Account {
fn hash<H: Hasher>(&self, state: &mut H) {
self.number.hash(state);
self.owner.hash(state);
self.balance.to_string().hash(state);
self.is_active.hash(state);
}
}
impl Default for Account {
fn default() -> Self {
Account {
@ -42,12 +60,6 @@ impl PartialEq for Account {
}
}
impl Hash for Account {
fn hash<H: Hasher>(&self, state: &mut H) {
self.number.hash(state);
}
}
impl Account {
#[cfg(test)]
pub fn new() -> Self {

View file

@ -13,11 +13,11 @@ impl Bank {
Default::default()
}
pub fn account_action<F: Fn(&mut Account) -> Result<f64, AccountError>>(
pub fn account_action<F: Fn(&mut Account) -> Result<R, AccountError>, R>(
bank: RwLockReadGuard<'_, Bank>,
nr: &str,
action: F,
) -> Result<f64, AccountError> {
) -> Result<R, AccountError> {
match bank.accounts.get(nr) {
None => Err(AccountError::NotFound),
Some(account) => {