68 lines
1.9 KiB
Rust
68 lines
1.9 KiB
Rust
use std::collections::HashMap;
|
|
use std::net::TcpStream;
|
|
use std::sync::{Arc, RwLock};
|
|
|
|
use anyhow::Result;
|
|
use crate::account::AccountError;
|
|
|
|
use crate::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 pong;
|
|
mod fail;
|
|
mod close_account;
|
|
mod create_account;
|
|
mod deposit;
|
|
mod get_account;
|
|
mod get_account_nrs;
|
|
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 From<&AccountError> for u8 {
|
|
fn from(error: &AccountError) -> Self {
|
|
match error {
|
|
AccountError::Overdraw() => 11,
|
|
AccountError::Inactive() => 12,
|
|
AccountError::InvalidAmount() => 13,
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|