Add networking #4

merged
opened by pebloop.dev targeting main from feat-network

Add networking as player constructor

Changed files
+44 -4
src
+2
src/main.rs
··· 1 1 use std::process::ExitCode; 2 2 3 3 mod cli; 4 + mod network; 5 + mod parser; 4 6 5 7 fn main() -> ExitCode { 6 8 let mut args = std::env::args();
+38
src/network.rs
··· 1 + use std::net::{SocketAddr, TcpListener, TcpStream}; 2 + 3 + pub enum NetworkError { 4 + IO(std::io::Error), 5 + NoIncomingConnexionError, 6 + } 7 + 8 + impl From<std::io::Error> for NetworkError { 9 + fn from(value: std::io::Error) -> Self { 10 + NetworkError::IO(value) 11 + } 12 + } 13 + 14 + struct TcpPlayer { 15 + connexion_stream: TcpStream, 16 + } 17 + 18 + impl TcpPlayer { 19 + pub fn host(addr: SocketAddr) -> Result<TcpPlayer, NetworkError> { 20 + let listener = TcpListener::bind(addr)?; 21 + let mut streams = listener.incoming(); 22 + let stream = streams 23 + .next() 24 + .ok_or(NetworkError::NoIncomingConnexionError)??; 25 + 26 + Ok(TcpPlayer { 27 + connexion_stream: stream, 28 + }) 29 + } 30 + 31 + pub fn join(addr: SocketAddr) -> Result<TcpPlayer, NetworkError> { 32 + let stream = TcpStream::connect(addr)?; 33 + 34 + Ok(TcpPlayer { 35 + connexion_stream: stream, 36 + }) 37 + } 38 + }
+4 -4
src/parser.rs
··· 22 22 23 23 impl Vector2u16 { 24 24 pub fn new(x: u16, y: u16) -> Self { 25 - Vector2u16 { x: x, y: y } 25 + Vector2u16 { x, y } 26 26 } 27 27 } 28 28 ··· 35 35 impl Boat { 36 36 pub fn new(first_pos: Vector2u16, last_pos: Vector2u16) -> Self { 37 37 Boat { 38 - first_pos: first_pos, 39 - last_pos: last_pos, 38 + first_pos, 39 + last_pos, 40 40 } 41 41 } 42 42 } 43 43 44 44 pub fn parse_file(file_path: &Path) -> Result<[Boat; 4], ParserError> { 45 45 let mut file = File::open(file_path)?; 46 - Ok(parse_ships(&mut file)?) 46 + parse_ships(&mut file) 47 47 } 48 48 49 49 pub fn parse_ships<T: Read>(file: &mut T) -> Result<[Boat; 4], ParserError> {