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 Deposit; impl Command for Deposit { fn execute(&self, bank: Arc>, data: &[u8], mut stream: &TcpStream) -> Result { 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) } }