vesys-bank-server/socket-server/src/commands/withdraw.rs

43 lines
1.1 KiB
Rust

use std::io::Write;
use std::net::TcpStream;
use std::sync::{Arc, RwLock};
use anyhow::Result;
use bank::bank::Bank;
use crate::commands::Command;
use crate::protocol;
pub struct Withdraw;
impl Command for Withdraw {
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!("withdrawing {} from {}...", 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::withdraw(acc.withdraw(amount)))?
}
None => stream.write(&protocol::error(2))?,
};
Ok(written)
}
}