63 lines
1.7 KiB
Rust
63 lines
1.7 KiB
Rust
use std::collections::HashMap;
|
|
use std::net::TcpStream;
|
|
use std::sync::{Arc, RwLock};
|
|
|
|
use anyhow::Result;
|
|
|
|
use bank::bank::Bank;
|
|
|
|
use crate::commands::close_account::CloseAccount;
|
|
use crate::commands::create_account::CreateAccount;
|
|
use crate::commands::deposit::Deposit;
|
|
use crate::commands::fail::Fail;
|
|
use crate::commands::get_account::GetAccount;
|
|
use crate::commands::get_account_nrs::GetAccountNrs;
|
|
use crate::commands::pong::Pong;
|
|
use crate::commands::withdraw::Withdraw;
|
|
|
|
mod close_account;
|
|
mod create_account;
|
|
mod deposit;
|
|
pub mod error;
|
|
mod fail;
|
|
mod get_account;
|
|
mod get_account_nrs;
|
|
mod pong;
|
|
mod withdraw;
|
|
|
|
pub trait Command: Sync + Send {
|
|
fn execute(&self, bank: Arc<RwLock<Bank>>, data: &[u8], stream: &TcpStream) -> Result<usize>;
|
|
}
|
|
|
|
pub struct Commands {
|
|
cmds: HashMap<u8, Box<dyn Command>>,
|
|
}
|
|
|
|
impl Commands {
|
|
pub fn new() -> Self {
|
|
let mut cmds = HashMap::new();
|
|
cmds.insert(1_u8, Box::new(Pong) as Box<dyn Command>);
|
|
cmds.insert(2_u8, Box::new(CreateAccount) as Box<dyn Command>);
|
|
cmds.insert(3_u8, Box::new(GetAccount) as Box<dyn Command>);
|
|
cmds.insert(4_u8, Box::new(GetAccountNrs) as Box<dyn Command>);
|
|
cmds.insert(5_u8, Box::new(CloseAccount) as Box<dyn Command>);
|
|
cmds.insert(6_u8, Box::new(Deposit) as Box<dyn Command>);
|
|
cmds.insert(7_u8, Box::new(Withdraw) as Box<dyn Command>);
|
|
|
|
Self { cmds }
|
|
}
|
|
|
|
pub fn run(
|
|
&self,
|
|
bank: Arc<RwLock<Bank>>,
|
|
cmd: u8,
|
|
data: &[u8],
|
|
stream: &TcpStream,
|
|
) -> Result<usize> {
|
|
match self.cmds.get(&cmd) {
|
|
None => Fail.execute(bank, &[1_u8], stream),
|
|
Some(cmd) => cmd.execute(bank, data, stream),
|
|
}
|
|
}
|
|
}
|