Skip to content

Commit

Permalink
clear code
Browse files Browse the repository at this point in the history
  • Loading branch information
VictoremWinbringer committed Jan 3, 2019
1 parent 33ca997 commit 85d12b2
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 58 deletions.
3 changes: 1 addition & 2 deletions examples/ping_pong_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ fn main() {
if timer.elapsed() > period {
timer = Instant::now();
id += 1;
let _ = client
.send(format!("Ping {}", id).into_bytes());
let _ = client.send(format!("Ping {}", id).into_bytes());
}
let _ = client
.recv()
Expand Down
5 changes: 1 addition & 4 deletions examples/ping_pong_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ impl victorem::Game for PingPongGame {
}

fn main() {
let mut server = victorem::GameServer::new(
PingPongGame { id: 0 },
"2222",
).unwrap();
let mut server = victorem::GameServer::new(PingPongGame { id: 0 }, "2222").unwrap();
server.run();
}
14 changes: 8 additions & 6 deletions src/business_logic_layer/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ pub struct Generator {
}

impl Generator {
pub fn new(start: u32) -> Generator { Generator { id: start } }
pub fn new(start: u32) -> Generator {
Generator { id: start }
}
pub fn generate(&mut self) -> u32 {
let result = self.id;
self.id += 1;
Expand All @@ -44,11 +46,12 @@ pub struct Filter {
}

impl Filter {
pub fn new(start: u32) -> Filter { Filter { id: start } }
pub fn new(start: u32) -> Filter {
Filter { id: start }
}

pub fn is_valid_last_recv_id(&mut self, data: &impl IWithId) -> Result<(), Exception> {
if data.get() > self.id
|| self.id - data.get() > MAX_ID_BREAK {
pub fn filter(&mut self, data: &impl IWithId) -> Result<(), Exception> {
if data.get() > self.id || self.id - data.get() > MAX_ID_BREAK {
self.id = data.get();
Ok(())
} else {
Expand All @@ -63,7 +66,6 @@ pub struct Arranger<T: IWithId> {
received: Vec<u32>,
}


const MAX_ID_BREAK: u32 = 64;
const MAX_SAVED: usize = (MAX_ID_BREAK * 2) as usize;
const MAX_RECEIVED: usize = MAX_SAVED;
Expand Down
15 changes: 8 additions & 7 deletions src/business_logic_layer/key.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::entities::{CommandPacket, Exception, StatePacket};
use std::time::{Duration, SystemTimeError, SystemTime, UNIX_EPOCH};
use crate::entities::{CommandPacket, StatePacket};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub trait IWithKey {
fn get(&self) -> Duration;
Expand Down Expand Up @@ -27,27 +27,28 @@ impl IWithKey for CommandPacket {
}

pub fn new_key() -> Duration {
match SystemTime::now()
.duration_since(UNIX_EPOCH) {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d,
Err(e) => e.duration(),
}
}

pub struct Generator {
key: Duration
key: Duration,
}

impl Generator {
pub fn new() -> Generator {
Generator { key: new_key() }
}

pub fn generate(&self) -> Duration { self.key }
pub fn generate(&self) -> Duration {
self.key
}
}

pub struct Filter {
key: Duration
key: Duration,
}

impl Filter {
Expand Down
21 changes: 8 additions & 13 deletions src/business_logic_layer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
use std::collections::HashMap;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH, SystemTimeError};

mod version;

mod protocol;
Expand All @@ -12,13 +8,13 @@ pub mod timer;

mod key;

use crate::data_access_layer::Cache;
use crate::entities::{CommandPacket, Exception, StatePacket};
use self::id::{Filter, Generator, Arranger};
use self::version::VersionChecker;
use self::id::{Arranger, Filter, Generator};
use self::key as k;
use self::protocol::ProtocolChecker;
use self::timer::SleepTimer;
use self::key as k;
use self::version::VersionChecker;
use crate::data_access_layer::Cache;
use crate::entities::{CommandPacket, Exception, StatePacket};

pub struct Client {
protocol_version: VersionChecker,
Expand Down Expand Up @@ -48,8 +44,8 @@ impl Client {

fn create_command(&mut self, command: Vec<u8>) -> CommandPacket {
CommandPacket {
protocol_id: self.protocol_id.get(),
protocol_version:self.protocol_version.get(),
protocol_id: self.protocol_id.get(),
protocol_version: self.protocol_version.get(),
id: self.id.generate(),
command,
session_key: self.key_generator.generate(),
Expand All @@ -70,7 +66,7 @@ impl Client {
self.key_filter = k::Filter::new(state.session_key);
self.id_filter = Filter::new(0);
}
self.id_filter.is_valid_last_recv_id(&state)?;
self.id_filter.filter(&state)?;
let vec = self.cache.get_range(&state.lost_ids);
Ok((state.state, vec))
}
Expand Down Expand Up @@ -98,7 +94,6 @@ impl Server {
}
}


pub fn send(&mut self, state: Vec<u8>) -> StatePacket {
StatePacket {
protocol_id: self.protocol_id.get(),
Expand Down
3 changes: 1 addition & 2 deletions src/business_logic_layer/timer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::entities::{CommandPacket, Exception, StatePacket};
use std::time::{Duration, Instant};
use std::thread;
use std::time::{Duration, Instant};

pub struct SleepTimer {
time: Duration,
Expand Down
2 changes: 1 addition & 1 deletion src/business_logic_layer/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::entities::{CommandPacket, Exception, StatePacket};

const PROTOCOL_VERSION: u8 = 1;

trait IWithVersion {
pub trait IWithVersion {
fn get(&self) -> u8;
fn set(&mut self, version: u8);
}
Expand Down
2 changes: 1 addition & 1 deletion src/entities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::io;
use std::time::{Duration, SystemTimeError};
use std::time::Duration;

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct CommandPacket {
Expand Down
27 changes: 11 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::data_access_layer::{TypedClientSocket, TypedServerSocket};
pub use crate::entities::Exception;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::Duration;

//TODO: Add Session ID for Client And Server!

Expand Down Expand Up @@ -131,19 +131,16 @@ impl ServerSocket {
}

pub fn add(&mut self, client: &SocketAddr) {
use std::net::*;
if !self.servers.contains_key(client) {
self.servers.insert(
client.clone(),
bll::Server::new(),
);
self.servers.insert(client.clone(), bll::Server::new());
}
}

pub fn send_to_all(&mut self, state: Vec<u8>) -> Vec<(SocketAddr, Exception)> {
let mut exceptions = Vec::new();
for (a, s) in &mut self.servers {
let _ = self.socket
let _ = self
.socket
.write(a, &s.send(state.clone()))
.map_err(|e| exceptions.push((*a, e)));
}
Expand Down Expand Up @@ -189,8 +186,7 @@ impl<T: Game> GameServer<T> {
let state = self.game.draw(self.draw_elapsed.elapsed());
self.game.add_client().map(|a| self.socket.add(&a));
self.game.remove_client().map(|a| self.socket.remove(&a));
self.is_running = self.is_running
& &self
self.is_running &= self
.socket
.send_to_all(state)
.into_iter()
Expand All @@ -203,21 +199,20 @@ impl<T: Game> GameServer<T> {
}

fn update(&mut self) {
let _ = self.socket
let _ = self
.socket
.recv()
.map(|(commands, from)| {
if self.game.allow_connect(&from) {
self.is_running = self.is_running
& &self
.game
.handle_command(self.update.elapsed(), commands, from);
self.is_running &=
self.game
.handle_command(self.update.elapsed(), commands, from);
} else {
self.socket.remove(&from);
}
})
.map_err(|e| {
self.is_running = self.is_running
& &self
self.is_running &= self
.game
.handle_server_event(ServerEvent::ExceptionOnRecv(e))
});
Expand Down
15 changes: 9 additions & 6 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ impl<'a> Game for GameMock<'a> {
fn add_client(&mut self) -> Option<SocketAddr> {
self.data.new_client.clone()
}
fn remove_client(&mut self) -> Option<SocketAddr> {
self.data.disconnect_this_client.clone()
}
}

fn create_server(game: GameMock, port: String) -> Result<GameServer<GameMock>, Exception> {
Expand Down Expand Up @@ -114,7 +117,7 @@ fn server_should_stop_if_handle_command_returns_false() -> Result<(), Exception>
let res = ClientSocket::new("1112", "127.0.0.1:3333")
.map(|mut c| {
for _i in 0..1000 {
c.send(vec![1u8, 3u8]);
let _ = c.send(vec![1u8, 3u8]);
}
1
})
Expand Down Expand Up @@ -153,7 +156,7 @@ fn server_should_recv_commands_from_client() -> Result<(), Exception> {
let res = ClientSocket::new("1111", "127.0.0.1:3335")
.map(|mut c| {
for _i in 0..1000 {
c.send(vec![1u8, 3u8]);
let _ = c.send(vec![1u8, 3u8]);
}
1
})
Expand Down Expand Up @@ -237,9 +240,9 @@ struct Calculator<T> {
pub result: Option<T>,
}

impl<'a, 'b: 'a, T: 'b + Add<Output=T> + Mul<Output=T> + Borrow<T>> Calculator<T>
where
&'a T: Add<Output=T> + Mul<Output=T>,
impl<'a, 'b: 'a, T: 'b + Add<Output = T> + Mul<Output = T> + Borrow<T>> Calculator<T>
where
&'a T: Add<Output = T> + Mul<Output = T>,
{
pub fn calculate_procedurally(&'b mut self) {
let res: T = match self.op {
Expand All @@ -250,7 +253,7 @@ impl<'a, 'b: 'a, T: 'b + Add<Output=T> + Mul<Output=T> + Borrow<T>> Calculator<T
}
}

impl<T: Add<Output=T> + Mul<Output=T> + Clone> Calculator<T> {
impl<T: Add<Output = T> + Mul<Output = T> + Clone> Calculator<T> {
pub fn calculate_functionally(mut self) -> Self {
self.result = Some(match self.op {
Operation::Add => self.lhs.clone() + self.rhs.clone(),
Expand Down

0 comments on commit 85d12b2

Please sign in to comment.