From e30f839a7f4267884961315436800ec857526b80 Mon Sep 17 00:00:00 2001 From: Peter Wischer Date: Sun, 18 Aug 2019 11:35:58 +0200 Subject: [PATCH 1/4] cargo fmt (nightly) --- examples/autobahn-client.rs | 3 +- examples/autobahn-server.rs | 7 +- examples/channel.rs | 8 +- examples/cli.rs | 5 +- examples/peer2peer.rs | 3 +- examples/pong.rs | 8 +- examples/router.rs | 2 +- examples/shared.rs | 3 +- examples/threaded.rs | 3 +- src/communication.rs | 5 +- src/connection.rs | 15 ++-- src/deflate/extension.rs | 13 ++-- src/handler.rs | 3 +- src/handshake.rs | 21 +++-- src/io.rs | 151 +++++++++++++++++++----------------- src/lib.rs | 13 +++- src/result.rs | 4 +- src/util.rs | 6 +- tests/deflate.rs | 3 +- 19 files changed, 157 insertions(+), 119 deletions(-) diff --git a/examples/autobahn-client.rs b/examples/autobahn-client.rs index 110592d..4a32d16 100644 --- a/examples/autobahn-client.rs +++ b/examples/autobahn-client.rs @@ -42,7 +42,8 @@ fn main() { connect(case_url, |out| { DeflateHandler::new(move |msg| out.send(msg)) - }).unwrap(); + }) + .unwrap(); case_id += 1 } diff --git a/examples/autobahn-server.rs b/examples/autobahn-server.rs index c0a9a00..159fab5 100644 --- a/examples/autobahn-server.rs +++ b/examples/autobahn-server.rs @@ -10,9 +10,7 @@ use ws::deflate::DeflateHandler; fn main() { env_logger::init(); - ws::listen("127.0.0.1:3012", |out| { - move |msg| out.send(msg) - }).unwrap() + ws::listen("127.0.0.1:3012", |out| move |msg| out.send(msg)).unwrap() } #[cfg(feature = "permessage-deflate")] @@ -21,5 +19,6 @@ fn main() { ws::listen("127.0.0.1:3012", |out| { DeflateHandler::new(move |msg| out.send(msg)) - }).unwrap(); + }) + .unwrap(); } diff --git a/examples/channel.rs b/examples/channel.rs index fb21901..59a92a9 100644 --- a/examples/channel.rs +++ b/examples/channel.rs @@ -10,8 +10,8 @@ extern crate env_logger; /// complex system from simple, composable parts. extern crate ws; -use std::sync::mpsc::Sender as ThreadOut; use std::sync::mpsc::channel; +use std::sync::mpsc::Sender as ThreadOut; use std::thread; use std::thread::sleep; use std::time::Duration; @@ -60,7 +60,8 @@ fn main() { // in theory, there could be many active connections log: log_in.clone(), } - }).unwrap() + }) + .unwrap() }) .unwrap(); @@ -117,7 +118,8 @@ fn main() { // in theory, there could be many client connections sending off the data data: client_data.clone(), } - }).unwrap() + }) + .unwrap() }) .unwrap(); diff --git a/examples/cli.rs b/examples/cli.rs index 80ebf8c..9bbc2db 100644 --- a/examples/cli.rs +++ b/examples/cli.rs @@ -8,8 +8,8 @@ extern crate ws; use std::io; use std::io::prelude::*; -use std::sync::mpsc::Sender as TSender; use std::sync::mpsc::channel; +use std::sync::mpsc::Sender as TSender; use std::thread; use clap::{App, Arg}; @@ -42,7 +42,8 @@ fn main() { connect(url, |sender| Client { ws_out: sender, thread_out: tx.clone(), - }).unwrap(); + }) + .unwrap(); }); if let Ok(Event::Connect(sender)) = rx.recv() { diff --git a/examples/peer2peer.rs b/examples/peer2peer.rs index 076c3ac..c16a4b1 100644 --- a/examples/peer2peer.rs +++ b/examples/peer2peer.rs @@ -68,7 +68,8 @@ fn main() { info!("Peer {} got message: {}", my_addr, msg); Ok(()) } - }).unwrap(); + }) + .unwrap(); // Get a sender for ALL connections to the websocket let broacaster = me.broadcaster(); diff --git a/examples/pong.rs b/examples/pong.rs index 5c9c62c..6a0984e 100644 --- a/examples/pong.rs +++ b/examples/pong.rs @@ -9,8 +9,9 @@ use std::str::from_utf8; use mio_extras::timer::Timeout; use ws::util::Token; -use ws::{listen, CloseCode, Error, ErrorKind, Frame, Handler, Handshake, Message, OpCode, Result, - Sender}; +use ws::{ + listen, CloseCode, Error, ErrorKind, Frame, Handler, Handshake, Message, OpCode, Result, Sender, +}; const PING: Token = Token(1); const EXPIRE: Token = Token(2); @@ -24,7 +25,8 @@ fn main() { out, ping_timeout: None, expire_timeout: None, - }).unwrap(); + }) + .unwrap(); } // Server WebSocket handler diff --git a/examples/router.rs b/examples/router.rs index 8e69929..d6c2d4d 100644 --- a/examples/router.rs +++ b/examples/router.rs @@ -6,7 +6,7 @@ extern crate ws; // A WebSocket handler that routes connections to different boxed handlers by resource struct Router { sender: ws::Sender, - inner: Box, + inner: Box, } impl ws::Handler for Router { diff --git a/examples/shared.rs b/examples/shared.rs index e466f5e..697e732 100644 --- a/examples/shared.rs +++ b/examples/shared.rs @@ -42,7 +42,8 @@ fn main() { // We must return the handler handler - }).unwrap(); + }) + .unwrap(); // Url for the client let url = url::Url::parse("ws://127.0.0.1:3012").unwrap(); diff --git a/examples/threaded.rs b/examples/threaded.rs index 35cf000..2dbc290 100644 --- a/examples/threaded.rs +++ b/examples/threaded.rs @@ -46,7 +46,8 @@ fn main() { println!("Client got message '{}'. ", msg); out.close(CloseCode::Normal) } - }).unwrap() + }) + .unwrap() }); let _ = server.join(); diff --git a/src/communication.rs b/src/communication.rs index 2b2822f..069ad5e 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -11,8 +11,8 @@ use message; use protocol::CloseCode; use result::{Error, Result}; use std::cmp::PartialEq; -use std::hash::{Hash, Hasher}; use std::fmt; +use std::hash::{Hash, Hasher}; #[derive(Debug, Clone)] pub enum Signal { @@ -70,7 +70,7 @@ impl PartialEq for Sender { } } -impl Eq for Sender { } +impl Eq for Sender {} impl Hash for Sender { fn hash(&self, state: &mut H) { @@ -79,7 +79,6 @@ impl Hash for Sender { } } - impl Sender { #[doc(hidden)] #[inline] diff --git a/src/connection.rs b/src/connection.rs index b639695..1b669ef 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -598,7 +598,8 @@ where // TODO: see if this can be optimized with drain let end = { let data = res.get_ref(); - let end = data.iter() + let end = data + .iter() .enumerate() .take_while(|&(ind, _)| !data[..ind].ends_with(b"\r\n\r\n")) .count(); @@ -757,8 +758,10 @@ where if !self.fragments.is_empty() { return Err(Error::new(Kind::Protocol, "Received unfragmented text frame while processing fragmented message.")); } - let msg = Message::text(String::from_utf8(frame.into_data()) - .map_err(|err| err.utf8_error())?); + let msg = Message::text( + String::from_utf8(frame.into_data()) + .map_err(|err| err.utf8_error())?, + ); self.handler.on_message(msg)?; } OpCode::Binary => { @@ -1027,7 +1030,8 @@ where trace!("Message opcode {:?}", opcode); let data = msg.into_data(); - if let Some(frame) = self.handler + if let Some(frame) = self + .handler .on_send_frame(Frame::message(data, opcode, true))? { if frame.payload().len() > self.settings.fragment_size { @@ -1145,7 +1149,8 @@ where self.peer_addr() ); - if let Some(frame) = self.handler + if let Some(frame) = self + .handler .on_send_frame(Frame::close(code, reason.borrow()))? { self.buffer_frame(frame)?; diff --git a/src/deflate/extension.rs b/src/deflate/extension.rs index 712e11f..f712695 100644 --- a/src/deflate/extension.rs +++ b/src/deflate/extension.rs @@ -1,9 +1,9 @@ use std::mem::replace; -#[cfg(feature = "ssl")] -use openssl::ssl::SslStream; #[cfg(feature = "nativetls")] use native_tls::TlsStream as SslStream; +#[cfg(feature = "ssl")] +use openssl::ssl::SslStream; use url; use frame::Frame; @@ -160,7 +160,8 @@ impl Handler for DeflateHandler { fn on_request(&mut self, req: &Request) -> Result { let mut res = self.inner.on_request(req)?; - 'ext: for req_ext in req.extensions()? + 'ext: for req_ext in req + .extensions()? .iter() .filter(|&&ext| ext.contains("permessage-deflate")) { @@ -282,7 +283,8 @@ impl Handler for DeflateHandler { } fn on_response(&mut self, res: &Response) -> Result<()> { - if let Some(res_ext) = res.extensions()? + if let Some(res_ext) = res + .extensions()? .iter() .find(|&&ext| ext.contains("permessage-deflate")) { @@ -449,7 +451,8 @@ impl Handler for DeflateHandler { // it's safe to unwrap because of the above check for empty let opcode = self.fragments.first().unwrap().opcode(); - let size = self.fragments + let size = self + .fragments .iter() .fold(0, |len, frame| len + frame.payload().len()); let mut compressed = Vec::with_capacity(size); diff --git a/src/handler.rs b/src/handler.rs index 7c1ef21..1a62a75 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -403,7 +403,8 @@ mod test { response: res, peer_addr: None, local_addr: None, - }).unwrap(); + }) + .unwrap(); h.on_message(message::Message::Text("testme".to_owned())) .unwrap(); h.on_close(CloseCode::Normal, ""); diff --git a/src/handshake.rs b/src/handshake.rs index b7520bd..001090c 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -333,7 +333,8 @@ impl Request { Ok(Some(Request { path: req.path.unwrap().into(), method: req.method.unwrap().into(), - headers: req.headers + headers: req + .headers .iter() .map(|h| (h.name.into(), h.value.into())) .collect(), @@ -362,7 +363,8 @@ impl Request { "No host passed for WebSocket connection.", ))?, url.port_or_known_default().unwrap_or(80) - ).into(), + ) + .into(), ), ("Sec-WebSocket-Version".into(), "13".into()), ("Sec-WebSocket-Key".into(), generate_key().into()), @@ -370,7 +372,9 @@ impl Request { ]; if url.password().is_some() || url.username() != "" { - let basic = encode_base64(format!("{}:{}", url.username(), url.password().unwrap_or("")).as_bytes()); + let basic = encode_base64( + format!("{}:{}", url.username(), url.password().unwrap_or("")).as_bytes(), + ); headers.push(("Authorization".into(), format!("Basic {}", basic).into())) } @@ -596,7 +600,8 @@ impl Response { Ok(Some(Response { status: res.code.unwrap(), reason: res.reason.unwrap().into(), - headers: res.headers + headers: res + .headers .iter() .map(|h| (h.name.into(), h.value.into())) .collect(), @@ -678,7 +683,8 @@ mod test { Upgrade: websocket\r\n\ Sec-WebSocket-Version: 13\r\n\ Sec-WebSocket-Key: q16eN37NCfVwUChPvBdk4g==\r\n\r\n" - ).unwrap(); + ) + .unwrap(); let req = Request::parse(&buf).unwrap().unwrap(); let res = Response::from_request(&req).unwrap(); @@ -702,7 +708,8 @@ mod test { X-Forwarded-For: 192.168.1.1, 192.168.1.2, 192.168.1.3\r\n\ Sec-WebSocket-Version: 13\r\n\ Sec-WebSocket-Key: q16eN37NCfVwUChPvBdk4g==\r\n\r\n" - ).unwrap(); + ) + .unwrap(); let req = Request::parse(&buf).unwrap().unwrap(); let res = Response::from_request(&req).unwrap(); @@ -726,7 +733,7 @@ mod test { Forwarded: by=192.168.1.1; for=192.0.2.43, for=\"[2001:db8:cafe::17]\", for=unknown\r\n\ Sec-WebSocket-Version: 13\r\n\ Sec-WebSocket-Key: q16eN37NCfVwUChPvBdk4g==\r\n\r\n") - .unwrap(); + .unwrap(); let req = Request::parse(&buf).unwrap().unwrap(); let res = Response::from_request(&req).unwrap(); let shake = Handshake { diff --git a/src/io.rs b/src/io.rs index 7739cdc..2f616c3 100644 --- a/src/io.rs +++ b/src/io.rs @@ -18,9 +18,8 @@ use super::Settings; use communication::{Command, Sender, Signal}; use connection::Connection; use factory::Factory; -use slab::Slab; use result::{Error, Kind, Result}; - +use slab::Slab; const QUEUE: Token = Token(usize::MAX - 3); const TIMER: Token = Token(usize::MAX - 4); @@ -252,16 +251,17 @@ where self.connections[tok.into()].token(), self.connections[tok.into()].events(), PollOpt::edge() | PollOpt::oneshot(), - ).map_err(Error::from) - .or_else(|err| { - error!( - "Encountered error while trying to build WebSocket connection: {}", - err - ); - let handler = self.connections.remove(tok.into()).consume(); - self.factory.connection_lost(handler); - Err(err) - }) + ) + .map_err(Error::from) + .or_else(|err| { + error!( + "Encountered error while trying to build WebSocket connection: {}", + err + ); + let handler = self.connections.remove(tok.into()).consume(); + self.factory.connection_lost(handler); + Err(err) + }) } #[cfg(not(any(feature = "ssl", feature = "nativetls")))] @@ -342,16 +342,17 @@ where self.connections[tok.into()].token(), self.connections[tok.into()].events(), PollOpt::edge() | PollOpt::oneshot(), - ).map_err(Error::from) - .or_else(|err| { - error!( - "Encountered error while trying to build WebSocket connection: {}", - err - ); - let handler = self.connections.remove(tok.into()).consume(); - self.factory.connection_lost(handler); - Err(err) - }) + ) + .map_err(Error::from) + .or_else(|err| { + error!( + "Encountered error while trying to build WebSocket connection: {}", + err + ); + let handler = self.connections.remove(tok.into()).consume(); + self.factory.connection_lost(handler); + Err(err) + }) } #[cfg(any(feature = "ssl", feature = "nativetls"))] @@ -396,18 +397,19 @@ where conn.token(), conn.events(), PollOpt::edge() | PollOpt::oneshot(), - ).map_err(Error::from) - .or_else(|err| { - error!( - "Encountered error while trying to build WebSocket connection: {}", - err - ); - conn.error(err); - if settings.panic_on_new_connection { - panic!("Encountered error while trying to build WebSocket connection."); - } - Ok(()) - }) + ) + .map_err(Error::from) + .or_else(|err| { + error!( + "Encountered error while trying to build WebSocket connection: {}", + err + ); + conn.error(err); + if settings.panic_on_new_connection { + panic!("Encountered error while trying to build WebSocket connection."); + } + Ok(()) + }) } #[cfg(not(any(feature = "ssl", feature = "nativetls")))] @@ -455,18 +457,19 @@ where conn.token(), conn.events(), PollOpt::edge() | PollOpt::oneshot(), - ).map_err(Error::from) - .or_else(|err| { - error!( - "Encountered error while trying to build WebSocket connection: {}", - err - ); - conn.error(err); - if settings.panic_on_new_connection { - panic!("Encountered error while trying to build WebSocket connection."); - } - Ok(()) - }) + ) + .map_err(Error::from) + .or_else(|err| { + error!( + "Encountered error while trying to build WebSocket connection: {}", + err + ); + conn.error(err); + if settings.panic_on_new_connection { + panic!("Encountered error while trying to build WebSocket connection."); + } + Ok(()) + }) } pub fn run(&mut self, poll: &mut Poll) -> Result<()> { @@ -605,7 +608,8 @@ where } ALL => { if events.is_readable() { - match self.listener + match self + .listener .as_ref() .expect("No listener provided for server websocket connections") .accept() @@ -626,9 +630,11 @@ where } } } - TIMER => while let Some(t) = self.timer.poll() { - self.handle_timeout(poll, t); - }, + TIMER => { + while let Some(t) = self.timer.poll() { + self.handle_timeout(poll, t); + } + } QUEUE => { for _ in 0..MESSAGES_PER_TICK { match self.queue_rx.try_recv() { @@ -660,16 +666,18 @@ where self.connections[token.into()].token(), self.connections[token.into()].events(), PollOpt::edge() | PollOpt::oneshot(), - ).or_else(|err| { - self.connections[token.into()] - .error(Error::from(err)); - let handler = self.connections - .remove(token.into()) - .consume(); - self.factory.connection_lost(handler); - Ok::<(), Error>(()) - }) - .unwrap(); + ) + .or_else(|err| { + self.connections[token.into()] + .error(Error::from(err)); + let handler = self + .connections + .remove(token.into()) + .consume(); + self.factory.connection_lost(handler); + Ok::<(), Error>(()) + }) + .unwrap(); return; } Err(err) => { @@ -699,16 +707,18 @@ where self.connections[token.into()].token(), self.connections[token.into()].events(), PollOpt::edge() | PollOpt::oneshot(), - ).or_else(|err| { - self.connections[token.into()] - .error(Error::from(err)); - let handler = self.connections - .remove(token.into()) - .consume(); - self.factory.connection_lost(handler); - Ok::<(), Error>(()) - }) - .unwrap(); + ) + .or_else(|err| { + self.connections[token.into()] + .error(Error::from(err)); + let handler = self + .connections + .remove(token.into()) + .consume(); + self.factory.connection_lost(handler); + Ok::<(), Error>(()) + }) + .unwrap(); return; } Err(err) => { @@ -981,5 +991,4 @@ mod test { err => panic!("{:?}", err), } } - } diff --git a/src/lib.rs b/src/lib.rs index ea9f1a5..158738b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,17 +1,22 @@ //! Lightweight, event-driven WebSockets for Rust. #![allow(deprecated)] -#![deny(missing_copy_implementations, trivial_casts, trivial_numeric_casts, unstable_features, - unused_import_braces)] +#![deny( + missing_copy_implementations, + trivial_casts, + trivial_numeric_casts, + unstable_features, + unused_import_braces +)] extern crate byteorder; extern crate bytes; extern crate httparse; extern crate mio; extern crate mio_extras; -#[cfg(feature = "ssl")] -extern crate openssl; #[cfg(feature = "nativetls")] extern crate native_tls; +#[cfg(feature = "ssl")] +extern crate openssl; extern crate rand; extern crate sha1; extern crate slab; diff --git a/src/result.rs b/src/result.rs index eb3c151..7688149 100644 --- a/src/result.rs +++ b/src/result.rs @@ -8,10 +8,10 @@ use std::str::Utf8Error; use httparse; use mio; -#[cfg(feature = "ssl")] -use openssl::ssl::{Error as SslError, HandshakeError as SslHandshakeError}; #[cfg(feature = "nativetls")] use native_tls::{Error as SslError, HandshakeError as SslHandshakeError}; +#[cfg(feature = "ssl")] +use openssl::ssl::{Error as SslError, HandshakeError as SslHandshakeError}; #[cfg(any(feature = "ssl", feature = "nativetls"))] type HandshakeError = SslHandshakeError; diff --git a/src/util.rs b/src/util.rs index fc66394..83aadfb 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,9 +1,9 @@ //! The util module rexports some tools from mio in order to facilitate handling timeouts. +#[cfg(any(feature = "ssl", feature = "nativetls"))] +/// TcpStream underlying the WebSocket +pub use mio::tcp::TcpStream; /// Used to identify some timed-out event. pub use mio::Token; /// A handle to a specific timeout. pub use mio_extras::timer::Timeout; -#[cfg(any(feature = "ssl", feature = "nativetls"))] -/// TcpStream underlying the WebSocket -pub use mio::tcp::TcpStream; diff --git a/tests/deflate.rs b/tests/deflate.rs index dfbfadd..47a74a1 100644 --- a/tests/deflate.rs +++ b/tests/deflate.rs @@ -29,7 +29,8 @@ fn round_trip() { name = "Server"; DeflateHandler::new(handler) - }).unwrap(); + }) + .unwrap(); let url = url::Url::parse("ws://127.0.0.1:3012").unwrap(); From cafa744205a6e4d234e31fd22a75a90c4f97612f Mon Sep 17 00:00:00 2001 From: Peter Wischer Date: Sun, 18 Aug 2019 11:44:47 +0200 Subject: [PATCH 2/4] fix travis build with clippy and rustfmt --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 146153c..367f9a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,8 +12,8 @@ script: - cargo check --features ssl - cargo check --features nativetls - cargo test - - bash -c 'if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]] ; then cargo install clippy --force && cargo clippy -- -A doc_markdown -A cyclomatic_complexity -A collapsible_if ; fi' - - bash -c 'if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]] ; then rustup component add rustfmt-preview && cargo fmt --all -- --write-mode=diff ; fi' + - bash -c 'if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]] ; then rustup component add clippy-preview && cargo clippy --all-targes ; fi' + - bash -c 'if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]] ; then rustup component add rustfmt-preview && cargo fmt --all -- --check ; fi' after_success: | # pip install --user autobahntestsuite && # /home/travis/.local/bin/wstest -m fuzzingserver -s ./tests/fuzzingserver.json & SPID=$! && From 8d70eff2d5e954db35daba4b8357f40f623f2437 Mon Sep 17 00:00:00 2001 From: Peter Wischer Date: Sun, 18 Aug 2019 12:12:38 +0200 Subject: [PATCH 3/4] apply clippy suggestions --- examples/bench.rs | 2 +- examples/html_chat.rs | 2 +- examples/ssl-server.rs | 2 +- examples/unsafe-ssl-client.rs | 2 +- src/connection.rs | 6 ++++-- src/deflate/context.rs | 15 +++++++++------ src/deflate/extension.rs | 24 +++++++++++++----------- src/frame.rs | 10 +++++----- src/handler.rs | 26 ++++++++++++++------------ src/handshake.rs | 8 +++++--- src/io.rs | 12 +++++++----- src/message.rs | 2 +- src/protocol.rs | 4 ++-- src/result.rs | 2 ++ src/stream.rs | 18 ++++++++++-------- tests/deflate.rs | 4 ++-- 16 files changed, 78 insertions(+), 61 deletions(-) diff --git a/examples/bench.rs b/examples/bench.rs index 427f841..97a5a4b 100644 --- a/examples/bench.rs +++ b/examples/bench.rs @@ -16,7 +16,7 @@ use ws::{Builder, CloseCode, Handler, Handshake, Message, Result, Sender, Settin const CONNECTIONS: usize = 10_000; // simultaneous const MESSAGES: u32 = 10; -static MESSAGE: &'static str = "TEST TEST TEST TEST TEST TEST TEST TEST"; +static MESSAGE: &str = "TEST TEST TEST TEST TEST TEST TEST TEST"; fn main() { env_logger::init(); diff --git a/examples/html_chat.rs b/examples/html_chat.rs index 7b7059b..68996cc 100644 --- a/examples/html_chat.rs +++ b/examples/html_chat.rs @@ -3,7 +3,7 @@ extern crate ws; use ws::{listen, Handler, Message, Request, Response, Result, Sender}; // This can be read from a file -static INDEX_HTML: &'static [u8] = br#" +static INDEX_HTML: &[u8] = br#" diff --git a/examples/ssl-server.rs b/examples/ssl-server.rs index ca78851..4113c87 100644 --- a/examples/ssl-server.rs +++ b/examples/ssl-server.rs @@ -100,7 +100,7 @@ fn main() { ..ws::Settings::default() }) .build(|out: ws::Sender| Server { - out: out, + out, ssl: acceptor.clone(), }) .unwrap() diff --git a/examples/unsafe-ssl-client.rs b/examples/unsafe-ssl-client.rs index c055cac..51f7afb 100644 --- a/examples/unsafe-ssl-client.rs +++ b/examples/unsafe-ssl-client.rs @@ -51,7 +51,7 @@ fn main() { env_logger::init(); if let Err(error) = ws::connect("wss://localhost:3443/api/websocket", |out| { - if let Err(_) = out.send("Hello WebSocket") { + if out.send("Hello WebSocket").is_err() { println!("Websocket couldn't queue an initial message.") } else { println!("Client sent message 'Hello WebSocket'. ") diff --git a/src/connection.rs b/src/connection.rs index 1b669ef..47878d0 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,3 +1,5 @@ +#![allow(clippy::cognitive_complexity, clippy::collapsible_if)] + use std::borrow::Borrow; use std::collections::VecDeque; use std::io::{Cursor, Read, Seek, SeekFrom, Write}; @@ -553,7 +555,7 @@ where if response.status() != 101 { self.events = Ready::empty(); - return Ok(()); + Ok(()) } else { self.handler.on_open(Handshake { request, @@ -564,7 +566,7 @@ where debug!("Connection to {} is now open.", self.peer_addr()); self.events.insert(Ready::readable()); self.check_events(); - return Ok(()); + Ok(()) } } else { Err(Error::new( diff --git a/src/deflate/context.rs b/src/deflate/context.rs index 2fa2e23..a2ab263 100644 --- a/src/deflate/context.rs +++ b/src/deflate/context.rs @@ -1,3 +1,5 @@ +#![allow(invalid_value, clippy::ptr_offset_with_cast, clippy::cast_lossless)] + use std::mem; use std::slice; @@ -6,7 +8,7 @@ use super::libc::{c_char, c_int, c_uint}; use result::{Error, Kind, Result}; -const ZLIB_VERSION: &'static str = "1.2.8\0"; +const ZLIB_VERSION: &str = "1.2.8\0"; trait Context { fn stream(&mut self) -> &mut ffi::z_stream; @@ -15,7 +17,7 @@ trait Context { where F: Fn(&mut ffi::z_stream) -> Option>, { - debug_assert!(output.len() == 0, "Output vector is not empty."); + debug_assert!(output.is_empty(), "Output vector is not empty."); let stream = self.stream(); @@ -79,7 +81,7 @@ impl Compressor { mem::size_of::() as c_int, ); assert!(result == ffi::Z_OK, "Failed to initialize compresser."); - Compressor { stream: stream } + Compressor { stream } } } @@ -147,7 +149,7 @@ impl Decompressor { mem::size_of::() as c_int, ); assert!(result == ffi::Z_OK, "Failed to initialize decompresser."); - Decompressor { stream: stream } + Decompressor { stream } } } @@ -196,15 +198,16 @@ impl Drop for Decompressor { } } +#[cfg(test)] mod test { - #![allow(unused_imports, unused_variables, dead_code)] use super::*; + #[allow(dead_code)] fn as_hex(s: &[u8]) { for byte in s { print!("0x{:x} ", byte); } - print!("\n"); + println!(); } #[test] diff --git a/src/deflate/extension.rs b/src/deflate/extension.rs index f712695..72c48b2 100644 --- a/src/deflate/extension.rs +++ b/src/deflate/extension.rs @@ -1,3 +1,5 @@ +#![allow(clippy::collapsible_if)] + use std::mem::replace; #[cfg(feature = "nativetls")] @@ -59,7 +61,7 @@ impl Default for DeflateSettings { /// Utility for applying the permessage-deflate extension to a handler with particular deflate /// settings. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Default)] pub struct DeflateBuilder { settings: DeflateSettings, } @@ -67,9 +69,7 @@ pub struct DeflateBuilder { impl DeflateBuilder { /// Create a new DeflateBuilder with the default settings. pub fn new() -> DeflateBuilder { - DeflateBuilder { - settings: DeflateSettings::default(), - } + Default::default() } /// Configure the DeflateBuilder with the given deflate settings. @@ -122,7 +122,7 @@ impl DeflateHandler { compress_reset: false, decompress_reset: false, pass: false, - settings: settings, + settings, inner: handler, } } @@ -300,7 +300,7 @@ impl Handler for DeflateHandler { if name { return Err(Error::new( Kind::Protocol, - format!("Duplicate extension name permessage-deflate"), + "Duplicate extension name permessage-deflate".to_owned(), )); } else { name = true; @@ -310,7 +310,8 @@ impl Handler for DeflateHandler { if s_takeover { return Err(Error::new( Kind::Protocol, - format!("Duplicate extension parameter server_no_context_takeover"), + "Duplicate extension parameter server_no_context_takeover" + .to_owned(), )); } else { s_takeover = true; @@ -321,7 +322,8 @@ impl Handler for DeflateHandler { if c_takeover { return Err(Error::new( Kind::Protocol, - format!("Duplicate extension parameter client_no_context_takeover"), + "Duplicate extension parameter client_no_context_takeover" + .to_owned(), )); } else { c_takeover = true; @@ -330,7 +332,7 @@ impl Handler for DeflateHandler { } else { return Err(Error::new( Kind::Protocol, - format!("The client requires context takeover."), + "The client requires context takeover.".to_owned(), )); } } @@ -339,7 +341,7 @@ impl Handler for DeflateHandler { if s_max { return Err(Error::new( Kind::Protocol, - format!("Duplicate extension parameter server_max_window_bits"), + "Duplicate extension parameter server_max_window_bits".to_owned(), )); } else { s_max = true; @@ -376,7 +378,7 @@ impl Handler for DeflateHandler { if c_max { return Err(Error::new( Kind::Protocol, - format!("Duplicate extension parameter client_max_window_bits"), + "Duplicate extension parameter client_max_window_bits".to_owned(), )); } else { c_max = true; diff --git a/src/frame.rs b/src/frame.rs index 154816c..b7c49d4 100644 --- a/src/frame.rs +++ b/src/frame.rs @@ -9,7 +9,7 @@ use protocol::{CloseCode, OpCode}; use result::{Error, Kind, Result}; use stream::TryReadBuf; -fn apply_mask(buf: &mut [u8], mask: &[u8; 4]) { +fn apply_mask(buf: &mut [u8], mask: [u8; 4]) { let iter = buf.iter_mut().zip(mask.iter().cycle()); for (byte, &key) in iter { *byte ^= key @@ -176,9 +176,9 @@ impl Frame { #[doc(hidden)] #[inline] pub fn remove_mask(&mut self) -> &mut Frame { - self.mask - .take() - .map(|mask| apply_mask(&mut self.payload, &mask)); + if let Some(mask) = self.mask.take() { + apply_mask(&mut self.payload, mask); + } self } @@ -429,7 +429,7 @@ impl Frame { if self.is_masked() { let mask = self.mask.take().unwrap(); - apply_mask(&mut self.payload, &mask); + apply_mask(&mut self.payload, mask); w.write_all(&mask)?; } diff --git a/src/handler.rs b/src/handler.rs index 1a62a75..b3c5e4b 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -291,10 +291,12 @@ pub trait Handler { stream: TcpStream, url: &url::Url, ) -> Result> { - let domain = url.domain().ok_or(Error::new( - Kind::Protocol, - format!("Unable to parse domain from {}. Needed for SSL.", url), - ))?; + let domain = url.domain().ok_or_else(|| { + Error::new( + Kind::Protocol, + format!("Unable to parse domain from {}. Needed for SSL.", url), + ) + })?; let connector = SslConnector::builder(SslMethod::tls()) .map_err(|e| { Error::new( @@ -313,10 +315,12 @@ pub trait Handler { stream: TcpStream, url: &url::Url, ) -> Result> { - let domain = url.domain().ok_or(Error::new( - Kind::Protocol, - format!("Unable to parse domain from {}. Needed for SSL.", url), - ))?; + let domain = url.domain().ok_or_else(|| { + Error::new( + Kind::Protocol, + format!("Unable to parse domain from {}. Needed for SSL.", url), + ) + })?; let connector = TlsConnector::new().map_err(|e| { Error::new( @@ -383,10 +387,8 @@ mod test { } fn on_message(&mut self, msg: message::Message) -> Result<()> { - Ok(assert_eq!( - msg, - message::Message::Text(String::from("testme")) - )) + assert_eq!(msg, message::Message::Text(String::from("testme"))); + Ok(()) } fn on_close(&mut self, code: CloseCode, _: &str) { diff --git a/src/handshake.rs b/src/handshake.rs index 001090c..ab85094 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -1,3 +1,5 @@ +#![allow(clippy::write_with_newline)] + use std::fmt; use std::io::Write; use std::net::SocketAddr; @@ -10,8 +12,8 @@ use url; use result::{Error, Kind, Result}; -static WS_GUID: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; -static BASE64: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +static BASE64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const MAX_HEADERS: usize = 124; fn generate_key() -> String { @@ -381,7 +383,7 @@ impl Request { let req = Request { path: format!("{}{}", url.path(), query), method: "GET".to_owned(), - headers: headers, + headers, }; debug!("Built request from URL:\n{}", req); diff --git a/src/io.rs b/src/io.rs index 2f616c3..7e20f46 100644 --- a/src/io.rs +++ b/src/io.rs @@ -1,3 +1,5 @@ +#![allow(clippy::cognitive_complexity)] + use std::borrow::Borrow; use std::io::{Error as IoError, ErrorKind}; use std::net::{SocketAddr, ToSocketAddrs}; @@ -209,6 +211,7 @@ where if will_encrypt { while let Err(ssl_error) = self.connections[tok.into()].encrypt() { + #[allow(clippy::single_match)] match ssl_error.kind { #[cfg(feature = "ssl")] Kind::Ssl(ref inner_ssl_error) => { @@ -969,15 +972,15 @@ mod test { let no_resolve = Url::from_str("ws://bad.elucitrans.com").unwrap(); assert!(url_to_addrs(&ws_url).is_ok()); - assert!(url_to_addrs(&ws_url).unwrap().len() > 0); + assert!(!url_to_addrs(&ws_url).unwrap().is_empty()); assert!(url_to_addrs(&wss_url).is_ok()); - assert!(url_to_addrs(&wss_url).unwrap().len() > 0); + assert!(!url_to_addrs(&wss_url).unwrap().is_empty()); match url_to_addrs(&bad_url) { Ok(_) => panic!("url_to_addrs accepts http urls."), Err(Error { kind: Kind::Internal, - details: _, + .. }) => (), // pass err => panic!("{:?}", err), } @@ -985,8 +988,7 @@ mod test { match url_to_addrs(&no_resolve) { Ok(_) => panic!("url_to_addrs creates addresses for non-existent domains."), Err(Error { - kind: Kind::Io(_), - details: _, + kind: Kind::Io(_), .. }) => (), // pass err => panic!("{:?}", err), } diff --git a/src/message.rs b/src/message.rs index 08509a5..01f60dd 100644 --- a/src/message.rs +++ b/src/message.rs @@ -141,7 +141,7 @@ mod test { #[test] fn display() { - let t = Message::text(format!("test")); + let t = Message::text("test".to_owned()); assert_eq!(t.to_string(), "test".to_owned()); let bin = Message::binary(vec![0, 1, 3, 4, 241]); diff --git a/src/protocol.rs b/src/protocol.rs index d4c1f2e..850a2fd 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -23,8 +23,8 @@ pub enum OpCode { impl OpCode { /// Test whether the opcode indicates a control frame. - pub fn is_control(&self) -> bool { - match *self { + pub fn is_control(self) -> bool { + match self { Text | Binary | Continue => false, _ => true, } diff --git a/src/result.rs b/src/result.rs index 7688149..4a88e0f 100644 --- a/src/result.rs +++ b/src/result.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant)] + use std::borrow::Cow; use std::convert::{From, Into}; use std::error::Error as StdError; diff --git a/src/stream.rs b/src/stream.rs index 3b8d9c4..de0242f 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant)] + use std::io; use std::io::ErrorKind::WouldBlock; #[cfg(any(feature = "ssl", feature = "nativetls"))] @@ -198,7 +200,7 @@ impl io::Read for Stream { negotiating = true; *tls_stream = TlsStream::Handshake { sock: mid, - negotiating: negotiating, + negotiating, }; Err(io::Error::new(io::ErrorKind::WouldBlock, "SSL would block")) } @@ -268,7 +270,7 @@ impl io::Write for Stream { negotiating = true; *tls_stream = TlsStream::Handshake { sock: mid, - negotiating: negotiating, + negotiating, }; Err(io::Error::new(io::ErrorKind::WouldBlock, "SSL would block")) } @@ -318,10 +320,7 @@ impl TlsStream { pub fn is_negotiating(&self) -> bool { match *self { TlsStream::Live(_) => false, - TlsStream::Handshake { - sock: _, - negotiating, - } => negotiating, + TlsStream::Handshake { negotiating, .. } => negotiating, TlsStream::Upgrading => panic!("Tried to access actively upgrading TlsStream"), } } @@ -333,9 +332,12 @@ impl TlsStream { "Attempted to clear negotiating flag on live ssl connection.", )), TlsStream::Handshake { - sock: _, ref mut negotiating, - } => Ok(*negotiating = false), + .. + } => { + *negotiating = false; + Ok(()) + } TlsStream::Upgrading => panic!("Tried to access actively upgrading TlsStream"), } } diff --git a/tests/deflate.rs b/tests/deflate.rs index 47a74a1..4d89456 100644 --- a/tests/deflate.rs +++ b/tests/deflate.rs @@ -8,7 +8,7 @@ use ws::{Builder, Message, Sender, Settings, WebSocket}; #[test] fn round_trip() { - const MESSAGE: &'static str = "this is the message that will be sent as a message"; + const MESSAGE: &str = "this is the message that will be sent as a message"; let mut name = "Client"; @@ -42,7 +42,7 @@ fn round_trip() { #[test] fn fragment() { env_logger::init(); - const MESSAGE: &'static str = "Hello"; + const MESSAGE: &str = "Hello"; let mut name = "Client"; From 8e2d186d2131d88a1b81474da58bf80b778d87ad Mon Sep 17 00:00:00 2001 From: Peter Wischer Date: Sun, 18 Aug 2019 14:07:28 +0200 Subject: [PATCH 4/4] edition 2018 --- Cargo.toml | 3 +- examples/autobahn-client.rs | 3 +- examples/autobahn-server.rs | 8 ++--- examples/bench-server.rs | 3 +- examples/bench.rs | 13 ++++---- examples/channel.rs | 21 ++++++------ examples/cli.rs | 12 +++---- examples/client.rs | 7 ++-- examples/external_shutdown.rs | 4 +-- examples/html_chat.rs | 4 +-- examples/peer2peer.rs | 60 +++++++++++++++++------------------ examples/pong.rs | 9 ++---- examples/router.rs | 11 ++++--- examples/server.rs | 7 ++-- examples/shared.rs | 9 +++--- examples/ssl-server.rs | 21 +++++------- examples/threaded.rs | 7 ++-- examples/unsafe-ssl-client.rs | 6 ---- src/communication.rs | 10 +++--- src/connection.rs | 18 +++++------ src/deflate/context.rs | 4 ++- src/deflate/extension.rs | 17 +++++----- src/deflate/mod.rs | 4 +-- src/factory.rs | 20 ++++++------ src/frame.rs | 11 ++++--- src/handler.rs | 25 ++++++++------- src/handshake.rs | 7 ++-- src/io.rs | 17 +++++----- src/lib.rs | 36 +++++++-------------- src/message.rs | 8 ++--- src/protocol.rs | 2 +- src/result.rs | 6 ++-- src/stream.rs | 4 ++- tests/bind.rs | 4 +-- tests/deflate.rs | 5 ++- tests/shutdown.rs | 4 +-- 36 files changed, 190 insertions(+), 220 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8da2312..1b208b7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,12 +14,13 @@ name = "ws" readme = "README.md" repository = "https://github.com/housleyjk/ws-rs" version = "0.9.1" +edition = "2018" [dependencies] byteorder = "1.2.1" bytes = "0.4.6" httparse = "1.2.4" -log = "0.4.1" +log = "0.4.8" mio = "0.6.14" mio-extras = "2.0" rand = "0.7" diff --git a/examples/autobahn-client.rs b/examples/autobahn-client.rs index 4a32d16..9cf2368 100644 --- a/examples/autobahn-client.rs +++ b/examples/autobahn-client.rs @@ -1,5 +1,4 @@ -/// WebSocket client used for testing against the Autobahn Test Suite -extern crate ws; +//! WebSocket client used for testing against the Autobahn Test Suite use std::cell::Cell; use std::rc::Rc; diff --git a/examples/autobahn-server.rs b/examples/autobahn-server.rs index 159fab5..11c2c25 100644 --- a/examples/autobahn-server.rs +++ b/examples/autobahn-server.rs @@ -1,8 +1,8 @@ -extern crate env_logger; -/// WebSocket server used for testing against the Autobahn Test Suite. This is basically the server -/// example without printing output or comments. -extern crate ws; +//! WebSocket server used for testing against the Autobahn Test Suite. This is basically the server +//! example without printing output or comments. +use env_logger; +use ws; #[cfg(feature = "permessage-deflate")] use ws::deflate::DeflateHandler; diff --git a/examples/bench-server.rs b/examples/bench-server.rs index bccfe66..13b8e4b 100644 --- a/examples/bench-server.rs +++ b/examples/bench-server.rs @@ -1,5 +1,4 @@ -/// WebSocket server used for testing the bench example. -extern crate ws; +//! WebSocket server used for testing the bench example. use ws::{Builder, Sender, Settings}; diff --git a/examples/bench.rs b/examples/bench.rs index 97a5a4b..27a6976 100644 --- a/examples/bench.rs +++ b/examples/bench.rs @@ -1,10 +1,6 @@ -extern crate env_logger; -extern crate time; -extern crate url; -/// A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving -/// WS-RS's performance excellence. ;) -/// Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000). -extern crate ws; +//! A simple, but immature, benchmark client for destroying other WebSocket frameworks and proving +//! WS-RS's performance excellence. ;) +//! Make sure you allow for enough connections in your OS (e.g. ulimit -Sn 10000). // Try this against node for some fun @@ -12,6 +8,9 @@ extern crate ws; // TODO: num threads, num connections per thread, num concurrent connections per thread, num // messages per connection, length of message, text or binary +use env_logger; +use time; +use url; use ws::{Builder, CloseCode, Handler, Handshake, Message, Result, Sender, Settings}; const CONNECTIONS: usize = 10_000; // simultaneous diff --git a/examples/channel.rs b/examples/channel.rs index 59a92a9..f9cbb2c 100644 --- a/examples/channel.rs +++ b/examples/channel.rs @@ -1,14 +1,12 @@ -extern crate env_logger; -/// An example of using channels to transfer data between three parts of some system. -/// -/// A WebSocket server echoes data back to a client and tees that data to a logging system. -/// A WebSocket client sends some data do the server. -/// A worker thread stores data as a log and sends that data back to the main program when the -/// WebSocket server has finished receiving data. -/// -/// This example demonstrates how to use threads, channels, and WebSocket handlers to create a -/// complex system from simple, composable parts. -extern crate ws; +//! An example of using channels to transfer data between three parts of some system. +//! +//! A WebSocket server echoes data back to a client and tees that data to a logging system. +//! A WebSocket client sends some data do the server. +//! A worker thread stores data as a log and sends that data back to the main program when the +//! WebSocket server has finished receiving data. +//! +//! This example demonstrates how to use threads, channels, and WebSocket handlers to create a +//! complex system from simple, composable parts. use std::sync::mpsc::channel; use std::sync::mpsc::Sender as ThreadOut; @@ -16,6 +14,7 @@ use std::thread; use std::thread::sleep; use std::time::Duration; +use env_logger; use ws::{connect, listen, CloseCode, Handler, Handshake, Message, Result, Sender}; fn main() { diff --git a/examples/cli.rs b/examples/cli.rs index 9bbc2db..9b69c5d 100644 --- a/examples/cli.rs +++ b/examples/cli.rs @@ -1,10 +1,6 @@ -extern crate clap; -extern crate env_logger; -extern crate term; -/// Run this cli like this: -/// cargo run --example server -/// cargo run --example cli -- ws://127.0.0.1:3012 -extern crate ws; +//! Run this cli like this: +//! cargo run --example server +//! cargo run --example cli -- ws://127.0.0.1:3012 use std::io; use std::io::prelude::*; @@ -13,6 +9,8 @@ use std::sync::mpsc::Sender as TSender; use std::thread; use clap::{App, Arg}; +use env_logger; +use term; use ws::{connect, CloseCode, Error, ErrorKind, Handler, Handshake, Message, Result, Sender}; fn main() { diff --git a/examples/client.rs b/examples/client.rs index 5390af3..4a8e962 100644 --- a/examples/client.rs +++ b/examples/client.rs @@ -1,8 +1,7 @@ -extern crate env_logger; -/// Simple WebSocket client with error handling. It is not necessary to setup logging, but doing -/// so will allow you to see more details about the connection by using the RUST_LOG env variable. -extern crate ws; +//! Simple WebSocket client with error handling. It is not necessary to setup logging, but doing +//! so will allow you to see more details about the connection by using the RUST_LOG env variable. +use env_logger; use ws::{connect, CloseCode}; fn main() { diff --git a/examples/external_shutdown.rs b/examples/external_shutdown.rs index 9e6f009..7831868 100644 --- a/examples/external_shutdown.rs +++ b/examples/external_shutdown.rs @@ -1,9 +1,9 @@ -extern crate ws; - use std::sync::mpsc::channel; use std::thread; use std::time::Duration; +use ws; + fn main() { let (tx, rx) = channel(); diff --git a/examples/html_chat.rs b/examples/html_chat.rs index 68996cc..aa0a86a 100644 --- a/examples/html_chat.rs +++ b/examples/html_chat.rs @@ -1,5 +1,5 @@ -/// An example of a chat web application server -extern crate ws; +//! An example of a chat web application server + use ws::{listen, Handler, Message, Request, Response, Result, Sender}; // This can be read from a file diff --git a/examples/peer2peer.rs b/examples/peer2peer.rs index c16a4b1..02c16f0 100644 --- a/examples/peer2peer.rs +++ b/examples/peer2peer.rs @@ -1,40 +1,38 @@ -extern crate clap; -extern crate env_logger; -extern crate url; -/// An example of a client-server-agnostic WebSocket that takes input from stdin and sends that -/// input to all other peers. -/// -/// For example, to create a network like this: -/// -/// 3013 ---- 3012 ---- 3014 -/// \ | -/// \ | -/// \ | -/// \ | -/// \ | -/// \ | -/// \ | -/// 3015 -/// -/// Run these commands in separate processes -/// ./peer2peer -/// ./peer2peer --server localhost:3013 ws://localhost:3012 -/// ./peer2peer --server localhost:3014 ws://localhost:3012 -/// ./peer2peer --server localhost:3015 ws://localhost:3012 ws://localhost:3013 -/// -/// Stdin on 3012 will be sent to all other peers -/// Stdin on 3013 will be sent to 3012 and 3015 -/// Stdin on 3014 will be sent to 3012 only -/// Stdin on 3015 will be sent to 3012 and 2013 -extern crate ws; -#[macro_use] -extern crate log; +//! An example of a client-server-agnostic WebSocket that takes input from stdin and sends that +//! input to all other peers. +//! +//! For example, to create a network like this: +//! +//! 3013 ---- 3012 ---- 3014 +//! \ | +//! \ | +//! \ | +//! \ | +//! \ | +//! \ | +//! \ | +//! 3015 +//! +//! Run these commands in separate processes +//! ./peer2peer +//! ./peer2peer --server localhost:3013 ws://localhost:3012 +//! ./peer2peer --server localhost:3014 ws://localhost:3012 +//! ./peer2peer --server localhost:3015 ws://localhost:3012 ws://localhost:3013 +//! +//! Stdin on 3012 will be sent to all other peers +//! Stdin on 3013 will be sent to 3012 and 3015 +//! Stdin on 3014 will be sent to 3012 only +//! Stdin on 3015 will be sent to 3012 and 2013 use std::io; use std::io::prelude::*; use std::thread; use clap::{App, Arg}; +use env_logger; +use log::info; +use url; +use ws; fn main() { // Setup logging diff --git a/examples/pong.rs b/examples/pong.rs index 6a0984e..b4d5f90 100644 --- a/examples/pong.rs +++ b/examples/pong.rs @@ -1,13 +1,10 @@ -extern crate env_logger; -extern crate mio_extras; -extern crate time; -/// An example demonstrating how to send and recieve a custom ping/pong frame. -extern crate ws; +//! An example demonstrating how to send and recieve a custom ping/pong frame. use std::str::from_utf8; +use env_logger; use mio_extras::timer::Timeout; - +use time; use ws::util::Token; use ws::{ listen, CloseCode, Error, ErrorKind, Frame, Handler, Handshake, Message, OpCode, Result, Sender, diff --git a/examples/router.rs b/examples/router.rs index d6c2d4d..dc2e8f5 100644 --- a/examples/router.rs +++ b/examples/router.rs @@ -1,9 +1,10 @@ -extern crate env_logger; -/// WebSocket server using trait objects to route -/// to an infinitely extensible number of handlers -extern crate ws; +//! WebSocket server using trait objects to route +//! to an infinitely extensible number of handlers -// A WebSocket handler that routes connections to different boxed handlers by resource +use env_logger; +use ws; + +/// A WebSocket handler that routes connections to different boxed handlers by resource struct Router { sender: ws::Sender, inner: Box, diff --git a/examples/server.rs b/examples/server.rs index fd9f5ae..3072964 100644 --- a/examples/server.rs +++ b/examples/server.rs @@ -1,8 +1,7 @@ -extern crate env_logger; -/// Simple WebSocket server with error handling. It is not necessary to setup logging, but doing -/// so will allow you to see more details about the connection by using the RUST_LOG env variable. -extern crate ws; +//! Simple WebSocket server with error handling. It is not necessary to setup logging, but doing +//! so will allow you to see more details about the connection by using the RUST_LOG env variable. +use env_logger; use ws::listen; fn main() { diff --git a/examples/shared.rs b/examples/shared.rs index 697e732..804a3b6 100644 --- a/examples/shared.rs +++ b/examples/shared.rs @@ -1,9 +1,8 @@ -extern crate env_logger; -extern crate url; -/// A single-threaded client + server example showing how flexible closure handlers can be for -/// trivial applications. -extern crate ws; +//! A single-threaded client + server example showing how flexible closure handlers can be for +//! trivial applications. +use env_logger; +use url; use ws::{Sender, WebSocket}; fn main() { diff --git a/examples/ssl-server.rs b/examples/ssl-server.rs index 4113c87..dbc79f1 100644 --- a/examples/ssl-server.rs +++ b/examples/ssl-server.rs @@ -1,16 +1,11 @@ -extern crate clap; -extern crate env_logger; -#[cfg(feature = "ssl")] -extern crate openssl; -/// WebSocket server to demonstrate ssl encryption within an a websocket server. -/// -/// The resulting executable takes three arguments: -/// ADDR - The address to listen for incoming connections (e.g. 127.0.0:3012) -/// CERT - The path to the cert PEM (e.g. snakeoil.crt) -/// KEY - The path to the key PEM (e.g. snakeoil.key) -/// -/// For more details concerning setting up the SSL context, see rust-openssl docs. -extern crate ws; +//! WebSocket server to demonstrate ssl encryption within an a websocket server. +//! +//! The resulting executable takes three arguments: +//! ADDR - The address to listen for incoming connections (e.g. 127.0.0:3012) +//! CERT - The path to the cert PEM (e.g. snakeoil.crt) +//! KEY - The path to the key PEM (e.g. snakeoil.key) +//! +//! For more details concerning setting up the SSL context, see rust-openssl docs. #[cfg(feature = "ssl")] use std::fs::File; diff --git a/examples/threaded.rs b/examples/threaded.rs index 2dbc290..b8b398e 100644 --- a/examples/threaded.rs +++ b/examples/threaded.rs @@ -1,12 +1,11 @@ -extern crate env_logger; -/// A thread-based client + server example. It also demonstrates using a struct as a WebSocket -/// handler to implement more handler methods than a closure handler allows. -extern crate ws; +//! A thread-based client + server example. It also demonstrates using a struct as a WebSocket +//! handler to implement more handler methods than a closure handler allows. use std::thread; use std::thread::sleep; use std::time::Duration; +use env_logger; use ws::{connect, listen, CloseCode, Handler, Message, Result, Sender}; fn main() { diff --git a/examples/unsafe-ssl-client.rs b/examples/unsafe-ssl-client.rs index 51f7afb..f0a0aef 100644 --- a/examples/unsafe-ssl-client.rs +++ b/examples/unsafe-ssl-client.rs @@ -1,9 +1,3 @@ -extern crate env_logger; -#[cfg(feature = "ssl")] -extern crate openssl; -extern crate url; -extern crate ws; - #[cfg(feature = "ssl")] use openssl::ssl::{SslConnector, SslMethod, SslStream, SslVerifyMode}; #[cfg(feature = "ssl")] diff --git a/src/communication.rs b/src/communication.rs index 069ad5e..0186ad3 100644 --- a/src/communication.rs +++ b/src/communication.rs @@ -6,10 +6,10 @@ use mio::Token; use mio_extras::timer::Timeout; use url; -use io::ALL; -use message; -use protocol::CloseCode; -use result::{Error, Result}; +use crate::io::ALL; +use crate::message; +use crate::protocol::CloseCode; +use crate::result::{Error, Result}; use std::cmp::PartialEq; use std::fmt; use std::hash::{Hash, Hasher}; @@ -57,7 +57,7 @@ pub struct Sender { } impl fmt::Debug for Sender { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Sender {{ token: {:?}, channel: mio::channel::SyncSender, connection_id: {:?} }}", self.token, self.connection_id) diff --git a/src/connection.rs b/src/connection.rs index 47878d0..038e734 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -7,23 +7,23 @@ use std::mem::replace; use std::net::SocketAddr; use std::str::from_utf8; +use log::{debug, error, trace}; use mio::tcp::TcpStream; use mio::{Ready, Token}; use mio_extras::timer::Timeout; -use url; - #[cfg(feature = "nativetls")] use native_tls::HandshakeError; #[cfg(feature = "ssl")] use openssl::ssl::HandshakeError; +use url; -use frame::Frame; -use handler::Handler; -use handshake::{Handshake, Request, Response}; -use message::Message; -use protocol::{CloseCode, OpCode}; -use result::{Error, Kind, Result}; -use stream::{Stream, TryReadBuf, TryWriteBuf}; +use crate::frame::Frame; +use crate::handler::Handler; +use crate::handshake::{Handshake, Request, Response}; +use crate::message::Message; +use crate::protocol::{CloseCode, OpCode}; +use crate::result::{Error, Kind, Result}; +use crate::stream::{Stream, TryReadBuf, TryWriteBuf}; use self::Endpoint::*; use self::State::*; diff --git a/src/deflate/context.rs b/src/deflate/context.rs index a2ab263..066e890 100644 --- a/src/deflate/context.rs +++ b/src/deflate/context.rs @@ -3,10 +3,12 @@ use std::mem; use std::slice; +use log::{error, trace}; + use super::ffi; use super::libc::{c_char, c_int, c_uint}; -use result::{Error, Kind, Result}; +use crate::result::{Error, Kind, Result}; const ZLIB_VERSION: &str = "1.2.8\0"; diff --git a/src/deflate/extension.rs b/src/deflate/extension.rs index 72c48b2..e112c98 100644 --- a/src/deflate/extension.rs +++ b/src/deflate/extension.rs @@ -2,21 +2,22 @@ use std::mem::replace; +use log::trace; #[cfg(feature = "nativetls")] use native_tls::TlsStream as SslStream; #[cfg(feature = "ssl")] use openssl::ssl::SslStream; use url; -use frame::Frame; -use handler::Handler; -use handshake::{Handshake, Request, Response}; -use message::Message; -use protocol::{CloseCode, OpCode}; -use result::{Error, Kind, Result}; +use crate::frame::Frame; +use crate::handler::Handler; +use crate::handshake::{Handshake, Request, Response}; +use crate::message::Message; +use crate::protocol::{CloseCode, OpCode}; +use crate::result::{Error, Kind, Result}; #[cfg(any(feature = "ssl", feature = "nativetls"))] -use util::TcpStream; -use util::{Timeout, Token}; +use crate::util::TcpStream; +use crate::util::{Timeout, Token}; use super::context::{Compressor, Decompressor}; diff --git a/src/deflate/mod.rs b/src/deflate/mod.rs index 8d79012..1190f95 100644 --- a/src/deflate/mod.rs +++ b/src/deflate/mod.rs @@ -1,7 +1,7 @@ //! The deflate module provides tools for applying the permessage-deflate extension. -extern crate libc; -extern crate libz_sys as ffi; +use libc; +use libz_sys as ffi; mod context; mod extension; diff --git a/src/factory.rs b/src/factory.rs index 048ac78..6dd2ec4 100644 --- a/src/factory.rs +++ b/src/factory.rs @@ -1,5 +1,7 @@ -use communication::Sender; -use handler::Handler; +use log::debug; + +use crate::communication::Sender; +use crate::handler::Handler; /// A trait for creating new WebSocket handlers. pub trait Factory { @@ -116,14 +118,14 @@ where mod test { #![allow(unused_imports, unused_variables, dead_code)] use super::*; - use communication::{Command, Sender}; - use frame; - use handler::Handler; - use handshake::{Handshake, Request, Response}; - use message; + use crate::communication::{Command, Sender}; + use crate::frame; + use crate::handler::Handler; + use crate::handshake::{Handshake, Request, Response}; + use crate::message; + use crate::protocol::CloseCode; + use crate::result::Result; use mio; - use protocol::CloseCode; - use result::Result; #[derive(Debug, Eq, PartialEq)] struct M; diff --git a/src/frame.rs b/src/frame.rs index b7c49d4..8f13063 100644 --- a/src/frame.rs +++ b/src/frame.rs @@ -3,11 +3,12 @@ use std::fmt; use std::io::{Cursor, ErrorKind, Read, Write}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use log::{debug, trace}; use rand; -use protocol::{CloseCode, OpCode}; -use result::{Error, Kind, Result}; -use stream::TryReadBuf; +use crate::protocol::{CloseCode, OpCode}; +use crate::result::{Error, Kind, Result}; +use crate::stream::TryReadBuf; fn apply_mask(buf: &mut [u8], mask: [u8; 4]) { let iter = buf.iter_mut().zip(mask.iter().cycle()); @@ -453,7 +454,7 @@ impl Default for Frame { } impl fmt::Display for Frame { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, " @@ -484,7 +485,7 @@ payload: 0x{} mod test { #![allow(unused_imports, unused_variables, dead_code)] use super::*; - use protocol::OpCode; + use crate::protocol::OpCode; #[test] fn display_frame() { diff --git a/src/handler.rs b/src/handler.rs index b3c5e4b..bcb4817 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -1,19 +1,20 @@ use log::Level::Error as ErrorLevel; +use log::{debug, error, log_enabled, trace}; #[cfg(feature = "nativetls")] use native_tls::{TlsConnector, TlsStream as SslStream}; #[cfg(feature = "ssl")] use openssl::ssl::{SslConnector, SslMethod, SslStream}; use url; -use frame::Frame; -use handshake::{Handshake, Request, Response}; -use message::Message; -use protocol::CloseCode; -use result::{Error, Kind, Result}; -use util::{Timeout, Token}; +use crate::frame::Frame; +use crate::handshake::{Handshake, Request, Response}; +use crate::message::Message; +use crate::protocol::CloseCode; +use crate::result::{Error, Kind, Result}; +use crate::util::{Timeout, Token}; #[cfg(any(feature = "ssl", feature = "nativetls"))] -use util::TcpStream; +use crate::util::TcpStream; /// The core trait of this library. /// Implementing this trait provides the business logic of the WebSocket application. @@ -354,12 +355,12 @@ where mod test { #![allow(unused_imports, unused_variables, dead_code)] use super::*; - use frame; - use handshake::{Handshake, Request, Response}; - use message; + use crate::frame; + use crate::handshake::{Handshake, Request, Response}; + use crate::message; + use crate::protocol::CloseCode; + use crate::result::Result; use mio; - use protocol::CloseCode; - use result::Result; use url; #[derive(Debug, Eq, PartialEq)] diff --git a/src/handshake.rs b/src/handshake.rs index ab85094..4caaec3 100644 --- a/src/handshake.rs +++ b/src/handshake.rs @@ -6,11 +6,12 @@ use std::net::SocketAddr; use std::str::from_utf8; use httparse; +use log::{debug, error}; use rand; use sha1::{self, Digest}; use url; -use result::{Error, Kind, Result}; +use crate::result::{Error, Kind, Result}; static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; static BASE64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -408,7 +409,7 @@ impl Request { } impl fmt::Display for Request { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut s = Vec::with_capacity(2048); self.format(&mut s).map_err(|err| { error!("{:?}", err); @@ -651,7 +652,7 @@ impl Response { } impl fmt::Display for Response { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut s = Vec::with_capacity(2048); self.format(&mut s).map_err(|err| { error!("{:?}", err); diff --git a/src/io.rs b/src/io.rs index 7e20f46..ba3d5e1 100644 --- a/src/io.rs +++ b/src/io.rs @@ -6,22 +6,21 @@ use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; use std::usize; +use log::{debug, error, info, trace}; use mio; use mio::tcp::{TcpListener, TcpStream}; use mio::{Poll, PollOpt, Ready, Token}; use mio_extras; - -use url::Url; - #[cfg(feature = "native_tls")] use native_tls::Error as SslError; +use slab::Slab; +use url::Url; use super::Settings; -use communication::{Command, Sender, Signal}; -use connection::Connection; -use factory::Factory; -use result::{Error, Kind, Result}; -use slab::Slab; +use crate::communication::{Command, Sender, Signal}; +use crate::connection::Connection; +use crate::factory::Factory; +use crate::result::{Error, Kind, Result}; const QUEUE: Token = Token(usize::MAX - 3); const TIMER: Token = Token(usize::MAX - 4); @@ -962,7 +961,7 @@ mod test { use super::url_to_addrs; use super::*; - use result::{Error, Kind}; + use crate::result::{Error, Kind}; #[test] fn test_url_to_addrs() { diff --git a/src/lib.rs b/src/lib.rs index 158738b..63bcf7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,22 +8,6 @@ unused_import_braces )] -extern crate byteorder; -extern crate bytes; -extern crate httparse; -extern crate mio; -extern crate mio_extras; -#[cfg(feature = "nativetls")] -extern crate native_tls; -#[cfg(feature = "ssl")] -extern crate openssl; -extern crate rand; -extern crate sha1; -extern crate slab; -extern crate url; -#[macro_use] -extern crate log; - mod communication; mod connection; mod factory; @@ -41,23 +25,25 @@ pub mod deflate; pub mod util; -pub use factory::Factory; -pub use handler::Handler; +pub use crate::factory::Factory; +pub use crate::handler::Handler; -pub use communication::Sender; -pub use frame::Frame; -pub use handshake::{Handshake, Request, Response}; -pub use message::Message; -pub use protocol::{CloseCode, OpCode}; -pub use result::Kind as ErrorKind; -pub use result::{Error, Result}; +pub use crate::communication::Sender; +pub use crate::frame::Frame; +pub use crate::handshake::{Handshake, Request, Response}; +pub use crate::message::Message; +pub use crate::protocol::{CloseCode, OpCode}; +pub use crate::result::Kind as ErrorKind; +pub use crate::result::{Error, Result}; use std::borrow::Borrow; use std::default::Default; use std::fmt; use std::net::{SocketAddr, ToSocketAddrs}; +use log::{error, info}; use mio::Poll; +use url; /// A utility function for setting up a WebSocket server. /// diff --git a/src/message.rs b/src/message.rs index 01f60dd..4793f4c 100644 --- a/src/message.rs +++ b/src/message.rs @@ -1,10 +1,10 @@ use std::convert::{From, Into}; use std::fmt; -use std::result::Result as StdResult; + use std::str::from_utf8; -use protocol::OpCode; -use result::Result; +use crate::protocol::OpCode; +use crate::result::Result; use self::Message::*; @@ -126,7 +126,7 @@ impl From> for Message { } impl fmt::Display for Message { - fn fmt(&self, f: &mut fmt::Formatter) -> StdResult<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Ok(string) = self.as_text() { write!(f, "{}", string) } else { diff --git a/src/protocol.rs b/src/protocol.rs index 850a2fd..9b8b2f7 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -32,7 +32,7 @@ impl OpCode { } impl fmt::Display for OpCode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Continue => write!(f, "CONTINUE"), Text => write!(f, "TEXT"), diff --git a/src/result.rs b/src/result.rs index 4a88e0f..0a5c74c 100644 --- a/src/result.rs +++ b/src/result.rs @@ -17,7 +17,7 @@ use openssl::ssl::{Error as SslError, HandshakeError as SslHandshakeError}; #[cfg(any(feature = "ssl", feature = "nativetls"))] type HandshakeError = SslHandshakeError; -use communication::Command; +use crate::communication::Command; pub type Result = StdResult; @@ -92,7 +92,7 @@ impl Error { } impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.details.len() > 0 { write!(f, "WS Error <{:?}>: {}", self.kind, self.details) } else { @@ -102,7 +102,7 @@ impl fmt::Debug for Error { } impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.details.len() > 0 { write!(f, "{}: {}", self.description(), self.details) } else { diff --git a/src/stream.rs b/src/stream.rs index de0242f..fa6a0ff 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -7,6 +7,8 @@ use std::mem::replace; use std::net::SocketAddr; use bytes::{Buf, BufMut}; +#[cfg(any(feature = "ssl", feature = "nativetls"))] +use log::trace; use mio::tcp::TcpStream; #[cfg(feature = "nativetls")] use native_tls::{ @@ -15,7 +17,7 @@ use native_tls::{ #[cfg(feature = "ssl")] use openssl::ssl::{ErrorCode as SslErrorCode, HandshakeError, MidHandshakeSslStream, SslStream}; -use result::{Error, Kind, Result}; +use crate::result::{Error, Kind, Result}; fn map_non_block(res: io::Result) -> io::Result> { match res { diff --git a/tests/bind.rs b/tests/bind.rs index 2a0c534..e20cdd4 100644 --- a/tests/bind.rs +++ b/tests/bind.rs @@ -1,7 +1,7 @@ -extern crate ws; - use std::net::Ipv4Addr; +use ws; + struct Handler; impl ws::Handler for Handler {} diff --git a/tests/deflate.rs b/tests/deflate.rs index 4d89456..5d261ba 100644 --- a/tests/deflate.rs +++ b/tests/deflate.rs @@ -1,8 +1,7 @@ #![cfg(feature = "permessage-deflate")] -extern crate env_logger; -extern crate url; -extern crate ws; +use env_logger; +use url; use ws::deflate::DeflateHandler; use ws::{Builder, Message, Sender, Settings, WebSocket}; diff --git a/tests/shutdown.rs b/tests/shutdown.rs index 1c12345..07d5bad 100644 --- a/tests/shutdown.rs +++ b/tests/shutdown.rs @@ -1,9 +1,9 @@ -extern crate ws; - use std::sync::mpsc::channel; use std::thread; use std::time::Duration; +use ws; + #[test] fn shutdown_before_connections() { let (tx, rx) = channel();