// ssip-client -- Speech Dispatcher client in Rust // Copyright (c) 2022 Laurent Pelecq // // Licensed under the Apache License, Version 2.0 // or the MIT // license , at your // option. All files in the project carrying such notice may not be copied, // modified, or distributed except according to those terms. #[cfg(not(feature = "async-mio"))] mod synchronous { use std::io::{self, BufReader, BufWriter}; pub use std::net::TcpStream; use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; use std::vec; use crate::client::Client; use crate::net::StreamMode; struct Addresses(Vec); impl ToSocketAddrs for Addresses { type Iter = vec::IntoIter; fn to_socket_addrs(&self) -> io::Result { Ok(self.0.clone().into_iter()) } } pub struct Builder { addrs: Addresses, mode: StreamMode, } impl Builder { pub fn new(addrs: A) -> io::Result { Ok(Self { addrs: Addresses(addrs.to_socket_addrs()?.collect::>()), mode: StreamMode::Blocking, }) } pub fn timeout(&mut self, read_timeout: Duration) -> &mut Self { self.mode = StreamMode::TimeOut(read_timeout); self } pub fn nonblocking(&mut self) -> &mut Self { self.mode = StreamMode::NonBlocking; self } pub fn build(&self) -> io::Result> { let input = TcpStream::connect(&self.addrs)?; match self.mode { StreamMode::Blocking => input.set_nonblocking(false)?, StreamMode::NonBlocking => input.set_nonblocking(true)?, StreamMode::TimeOut(timeout) => input.set_read_timeout(Some(timeout))?, } let output = input.try_clone()?; Ok(Client::new(BufReader::new(input), BufWriter::new(output))) } } } #[cfg(not(feature = "async-mio"))] pub use synchronous::{Builder, TcpStream}; #[cfg(feature = "async-mio")] mod asynchronous { pub use mio::net::TcpStream; use std::io::{self, BufReader, BufWriter}; use std::net::SocketAddr; use std::net::TcpStream as StdTcpStream; use crate::client::Client; pub struct Builder { addr: SocketAddr, } impl Builder { pub fn new(addr: SocketAddr) -> Self { Self { addr } } pub fn build(&self) -> io::Result> { let stream = StdTcpStream::connect(self.addr)?; Ok(Client::new( BufReader::new(TcpStream::from_std(stream.try_clone()?)), BufWriter::new(TcpStream::from_std(stream)), )) } } } #[cfg(feature = "async-mio")] pub use asynchronous::{Builder, TcpStream}; #[cfg(test)] mod tests {}