2022-03-12 15:19:54 +00:00
|
|
|
use std::io::Write;
|
|
|
|
use std::net::TcpStream;
|
|
|
|
use std::sync::{Arc, RwLock};
|
|
|
|
|
|
|
|
use anyhow::Result;
|
|
|
|
|
2022-03-16 08:51:29 +00:00
|
|
|
use bank::bank::Bank;
|
|
|
|
|
2022-03-12 15:19:54 +00:00
|
|
|
use crate::commands::Command;
|
|
|
|
use crate::protocol;
|
|
|
|
|
|
|
|
pub struct Deposit;
|
|
|
|
|
|
|
|
impl Command for Deposit {
|
|
|
|
fn execute(&self, bank: Arc<RwLock<Bank>>, data: &[u8], mut stream: &TcpStream) -> Result<usize> {
|
|
|
|
let value_bytes: [u8; 8] = <[u8; 8]>::try_from(data[..8].to_vec().as_slice())?;
|
|
|
|
debug!("value bytes {:?}", value_bytes);
|
|
|
|
|
|
|
|
let nr_bytes = &data[8..].to_vec();
|
|
|
|
debug!("nr bytes {:?}", nr_bytes);
|
|
|
|
|
|
|
|
let amount = f64::from_be_bytes(value_bytes);
|
|
|
|
let nr = String::from_utf8_lossy(nr_bytes).to_string();
|
|
|
|
info!("depositing {} into {}...", amount, nr);
|
|
|
|
|
|
|
|
let bank = bank.read().unwrap();
|
|
|
|
|
|
|
|
let written = match bank.accounts.get(&nr) {
|
|
|
|
Some(acc) => {
|
|
|
|
let mut acc = acc.write().unwrap();
|
|
|
|
stream.write(&protocol::deposit(acc.deposit(amount)))?
|
|
|
|
}
|
|
|
|
None => stream.write(&protocol::error(2))?
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(written)
|
|
|
|
}
|
|
|
|
}
|