diff --git a/.travis.yml b/.travis.yml index 22e2f7e7e..01b739ff7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,9 +25,10 @@ matrix: script: | cargo check --all - # Test combinations of enabled features. + # Test combinations of enabled features and rustfmt - rust: stable script: | + cargo fmt --all -- --check shopt -s expand_aliases alias check="cargo check --no-default-features" check diff --git a/benches/latency.rs b/benches/latency.rs index c2619b711..d9ace03a4 100644 --- a/benches/latency.rs +++ b/benches/latency.rs @@ -10,8 +10,8 @@ use std::io; use std::net::SocketAddr; use std::thread; -use futures::sync::oneshot; use futures::sync::mpsc; +use futures::sync::oneshot; use futures::{Future, Poll, Sink, Stream}; use test::Bencher; use tokio::net::UdpSocket; @@ -57,7 +57,6 @@ fn udp_echo_latency(b: &mut Bencher) { let (tx, rx) = oneshot::channel(); let child = thread::spawn(move || { - let socket = tokio::net::UdpSocket::bind(&any_addr).unwrap(); tx.send(socket.local_addr().unwrap()).unwrap(); @@ -67,7 +66,6 @@ fn udp_echo_latency(b: &mut Bencher) { server.wait().unwrap(); }); - let client = std::net::UdpSocket::bind(&any_addr).unwrap(); let server_addr = rx.wait().unwrap(); diff --git a/benches/mio-ops.rs b/benches/mio-ops.rs index 6a71bebfe..be4db7f79 100644 --- a/benches/mio-ops.rs +++ b/benches/mio-ops.rs @@ -3,14 +3,13 @@ #![feature(test)] #![deny(warnings)] -extern crate test; extern crate mio; +extern crate test; use test::Bencher; use mio::tcp::TcpListener; -use mio::{Token, Ready, PollOpt}; - +use mio::{PollOpt, Ready, Token}; #[bench] fn mio_register_deregister(b: &mut Bencher) { @@ -22,8 +21,8 @@ fn mio_register_deregister(b: &mut Bencher) { const CLIENT: Token = Token(1); b.iter(|| { - poll.register(&sock, CLIENT, Ready::readable(), - PollOpt::edge()).unwrap(); + poll.register(&sock, CLIENT, Ready::readable(), PollOpt::edge()) + .unwrap(); poll.deregister(&sock).unwrap(); }); } @@ -36,12 +35,12 @@ fn mio_reregister(b: &mut Bencher) { let poll = mio::Poll::new().unwrap(); const CLIENT: Token = Token(1); - poll.register(&sock, CLIENT, Ready::readable(), - PollOpt::edge()).unwrap(); + poll.register(&sock, CLIENT, Ready::readable(), PollOpt::edge()) + .unwrap(); b.iter(|| { - poll.reregister(&sock, CLIENT, Ready::readable(), - PollOpt::edge()).unwrap(); + poll.reregister(&sock, CLIENT, Ready::readable(), PollOpt::edge()) + .unwrap(); }); poll.deregister(&sock).unwrap(); } diff --git a/benches/tcp.rs b/benches/tcp.rs index fde72ce09..1872790d9 100644 --- a/benches/tcp.rs +++ b/benches/tcp.rs @@ -11,18 +11,18 @@ pub extern crate test; mod prelude { pub use futures::*; - pub use tokio::reactor::Reactor; pub use tokio::net::{TcpListener, TcpStream}; + pub use tokio::reactor::Reactor; pub use tokio_io::io::read_to_end; - pub use test::{self, Bencher}; + pub use std::io::{self, Read, Write}; pub use std::thread; pub use std::time::Duration; - pub use std::io::{self, Read, Write}; + pub use test::{self, Bencher}; } mod connect_churn { - use ::prelude::*; + use prelude::*; const NUM: usize = 300; const CONCURRENT: usize = 8; @@ -36,25 +36,29 @@ mod connect_churn { let addr = listener.local_addr().unwrap(); // Spawn a single future that accepts & drops connections - let serve_incomings = listener.incoming() + let serve_incomings = listener + .incoming() .map_err(|e| panic!("server err: {:?}", e)) .for_each(|_| Ok(())); let connects = stream::iter_result((0..NUM).map(|_| { - Ok(TcpStream::connect(&addr) - .and_then(|sock| { - sock.set_linger(Some(Duration::from_secs(0))).unwrap(); - read_to_end(sock, vec![]) - })) + Ok(TcpStream::connect(&addr).and_then(|sock| { + sock.set_linger(Some(Duration::from_secs(0))).unwrap(); + read_to_end(sock, vec![]) + })) })); - let connects_concurrent = connects.buffer_unordered(CONCURRENT) + let connects_concurrent = connects + .buffer_unordered(CONCURRENT) .map_err(|e| panic!("client err: {:?}", e)) .for_each(|_| Ok(())); - serve_incomings.select(connects_concurrent) - .map(|_| ()).map_err(|_| ()) - .wait().unwrap(); + serve_incomings + .select(connects_concurrent) + .map(|_| ()) + .map_err(|_| ()) + .wait() + .unwrap(); }); } @@ -65,8 +69,7 @@ mod connect_churn { // Spawn reactor thread let server_thread = thread::spawn(move || { // Bind the TCP listener - let listener = TcpListener::bind( - &"127.0.0.1:0".parse().unwrap()).unwrap(); + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); // Get the address being listened on. let addr = listener.local_addr().unwrap(); @@ -75,47 +78,56 @@ mod connect_churn { addr_tx.send(addr).unwrap(); // Spawn a single future that accepts & drops connections - let serve_incomings = listener.incoming() + let serve_incomings = listener + .incoming() .map_err(|e| panic!("server err: {:?}", e)) .for_each(|_| Ok(())); // Run server - serve_incomings.select(shutdown_rx) - .map(|_| ()).map_err(|_| ()) - .wait().unwrap(); + serve_incomings + .select(shutdown_rx) + .map(|_| ()) + .map_err(|_| ()) + .wait() + .unwrap(); }); // Get the bind addr of the server let addr = addr_rx.wait().unwrap(); b.iter(move || { - use std::sync::{Barrier, Arc}; + use std::sync::{Arc, Barrier}; // Create a barrier to coordinate threads let barrier = Arc::new(Barrier::new(n + 1)); // Spawn worker threads - let threads: Vec<_> = (0..n).map(|_| { - let barrier = barrier.clone(); - let addr = addr.clone(); + let threads: Vec<_> = (0..n) + .map(|_| { + let barrier = barrier.clone(); + let addr = addr.clone(); - thread::spawn(move || { - let connects = stream::iter_result((0..(NUM / n)).map(|_| { - Ok(TcpStream::connect(&addr) - .map_err(|e| panic!("connect err: {:?}", e)) - .and_then(|sock| { - sock.set_linger(Some(Duration::from_secs(0))).unwrap(); - read_to_end(sock, vec![]) - })) - })); + thread::spawn(move || { + let connects = stream::iter_result((0..(NUM / n)).map(|_| { + Ok(TcpStream::connect(&addr) + .map_err(|e| panic!("connect err: {:?}", e)) + .and_then(|sock| { + sock.set_linger(Some(Duration::from_secs(0))).unwrap(); + read_to_end(sock, vec![]) + })) + })); - barrier.wait(); + barrier.wait(); - connects.buffer_unordered(CONCURRENT) - .map_err(|e| panic!("client err: {:?}", e)) - .for_each(|_| Ok(())).wait().unwrap(); + connects + .buffer_unordered(CONCURRENT) + .map_err(|e| panic!("client err: {:?}", e)) + .for_each(|_| Ok(())) + .wait() + .unwrap(); + }) }) - }).collect(); + .collect(); barrier.wait(); @@ -141,7 +153,7 @@ mod connect_churn { } mod transfer { - use ::prelude::*; + use prelude::*; use std::{cmp, mem}; const MB: usize = 3 * 1024 * 1024; @@ -200,7 +212,8 @@ mod transfer { let addr = listener.local_addr().unwrap(); // Spawn a single future that accepts 1 connection, Drain it and drops - let server = listener.incoming() + let server = listener + .incoming() .into_future() // take the first connection .map_err(|(e, _other_incomings)| e) .map(|(connection, _other_incomings)| connection.unwrap()) @@ -210,17 +223,17 @@ mod transfer { sock: sock, chunk: read_size, }; - drain.map(|_| ()).map_err(|e| panic!("server error: {:?}", e)) + drain + .map(|_| ()) + .map_err(|e| panic!("server error: {:?}", e)) }) .map_err(|e| panic!("server err: {:?}", e)); let client = TcpStream::connect(&addr) - .and_then(move |sock| { - Transfer { - sock: sock, - rem: MB, - chunk: write_size, - } + .and_then(move |sock| Transfer { + sock: sock, + rem: MB, + chunk: write_size, }) .map_err(|e| panic!("client err: {:?}", e)); @@ -229,7 +242,7 @@ mod transfer { } mod small_chunks { - use ::prelude::*; + use prelude::*; #[bench] fn one_thread(b: &mut Bencher) { @@ -238,7 +251,7 @@ mod transfer { } mod big_chunks { - use ::prelude::*; + use prelude::*; #[bench] fn one_thread(b: &mut Bencher) { diff --git a/examples/chat-combinator-current-thread.rs b/examples/chat-combinator-current-thread.rs index c528eeeca..ee147025d 100644 --- a/examples/chat-combinator-current-thread.rs +++ b/examples/chat-combinator-current-thread.rs @@ -26,21 +26,20 @@ #![deny(warnings)] -extern crate tokio; extern crate futures; +extern crate tokio; use tokio::io; use tokio::net::TcpListener; use tokio::prelude::*; use tokio::runtime::current_thread::{Runtime, TaskExecutor}; -use std::collections::HashMap; -use std::iter; -use std::env; -use std::io::{BufReader}; -use std::rc::Rc; use std::cell::RefCell; - +use std::collections::HashMap; +use std::env; +use std::io::BufReader; +use std::iter; +use std::rc::Rc; fn main() -> Result<(), Box> { let mut runtime = Runtime::new().unwrap(); @@ -58,8 +57,12 @@ fn main() -> Result<(), Box> { // The server task asynchronously iterates over and processes each incoming // connection. - let srv = socket.incoming() - .map_err(|e| {println!("failed to accept socket; error = {:?}", e); e}) + let srv = socket + .incoming() + .map_err(|e| { + println!("failed to accept socket; error = {:?}", e); + e + }) .for_each(move |stream| { // The client's socket address let addr = stream.peer_addr()?; @@ -102,9 +105,7 @@ fn main() -> Result<(), Box> { // Convert the bytes we read into a string, and then send that // string to all other connected clients. - let line = line.map(|(reader, vec)| { - (reader, String::from_utf8(vec)) - }); + let line = line.map(|(reader, vec)| (reader, String::from_utf8(vec))); // Move the connection state into the closure below. let connections = connections_inner.clone(); @@ -116,15 +117,17 @@ fn main() -> Result<(), Box> { if let Ok(msg) = message { // For each open connection except the sender, send the // string via the channel. - let iter = conns.iter_mut() - .filter(|&(&k, _)| k != addr) - .map(|(_, v)| v); + let iter = conns + .iter_mut() + .filter(|&(&k, _)| k != addr) + .map(|(_, v)| v); for tx in iter { tx.unbounded_send(format!("{}: {}", addr, msg)).unwrap(); } } else { let tx = conns.get_mut(&addr).unwrap(); - tx.unbounded_send("You didn't send valid UTF-8.".to_string()).unwrap(); + tx.unbounded_send("You didn't send valid UTF-8.".to_string()) + .unwrap(); } reader @@ -147,12 +150,14 @@ fn main() -> Result<(), Box> { let connection = socket_reader.map(|_| ()).select(socket_writer.map(|_| ())); // Spawn locally a task to process the connection - TaskExecutor::current().spawn_local(Box::new(connection.then(move |_| { - let mut conns = connections.borrow_mut(); - conns.remove(&addr); - println!("Connection {} closed.", addr); - Ok(()) - }))).unwrap(); + TaskExecutor::current() + .spawn_local(Box::new(connection.then(move |_| { + let mut conns = connections.borrow_mut(); + conns.remove(&addr); + println!("Connection {} closed.", addr); + Ok(()) + }))) + .unwrap(); Ok(()) }) diff --git a/examples/chat-combinator.rs b/examples/chat-combinator.rs index 0572afbd0..b81e8f7c3 100644 --- a/examples/chat-combinator.rs +++ b/examples/chat-combinator.rs @@ -21,17 +21,17 @@ #![deny(warnings)] -extern crate tokio; extern crate futures; +extern crate tokio; use tokio::io; use tokio::net::TcpListener; use tokio::prelude::*; use std::collections::HashMap; -use std::iter; use std::env; -use std::io::{BufReader}; +use std::io::BufReader; +use std::iter; use std::sync::{Arc, Mutex}; fn main() -> Result<(), Box> { @@ -48,8 +48,12 @@ fn main() -> Result<(), Box> { // The server task asynchronously iterates over and processes each incoming // connection. - let srv = socket.incoming() - .map_err(|e| {println!("failed to accept socket; error = {:?}", e); e}) + let srv = socket + .incoming() + .map_err(|e| { + println!("failed to accept socket; error = {:?}", e); + e + }) .for_each(move |stream| { // The client's socket address let addr = stream.peer_addr()?; @@ -91,9 +95,7 @@ fn main() -> Result<(), Box> { // Convert the bytes we read into a string, and then send that // string to all other connected clients. - let line = line.map(|(reader, vec)| { - (reader, String::from_utf8(vec)) - }); + let line = line.map(|(reader, vec)| (reader, String::from_utf8(vec))); // Move the connection state into the closure below. let connections = connections_inner.clone(); @@ -105,15 +107,17 @@ fn main() -> Result<(), Box> { if let Ok(msg) = message { // For each open connection except the sender, send the // string via the channel. - let iter = conns.iter_mut() - .filter(|&(&k, _)| k != addr) - .map(|(_, v)| v); + let iter = conns + .iter_mut() + .filter(|&(&k, _)| k != addr) + .map(|(_, v)| v); for tx in iter { tx.unbounded_send(format!("{}: {}", addr, msg)).unwrap(); } } else { let tx = conns.get_mut(&addr).unwrap(); - tx.unbounded_send("You didn't send valid UTF-8.".to_string()).unwrap(); + tx.unbounded_send("You didn't send valid UTF-8.".to_string()) + .unwrap(); } reader diff --git a/examples/chat.rs b/examples/chat.rs index 182af7c8a..b21432afa 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -31,12 +31,12 @@ extern crate tokio; extern crate futures; extern crate bytes; +use bytes::{BufMut, Bytes, BytesMut}; +use futures::future::{self, Either}; +use futures::sync::mpsc; use tokio::io; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; -use futures::sync::mpsc; -use futures::future::{self, Either}; -use bytes::{BytesMut, Bytes, BufMut}; use std::collections::HashMap; use std::net::SocketAddr; @@ -131,10 +131,7 @@ impl Shared { impl Peer { /// Create a new instance of `Peer`. - fn new(name: BytesMut, - state: Arc>, - lines: Lines) -> Peer - { + fn new(name: BytesMut, state: Arc>, lines: Lines) -> Peer { // Get the client socket address let addr = lines.socket.peer_addr().unwrap(); @@ -142,8 +139,7 @@ impl Peer { let (tx, rx) = mpsc::unbounded(); // Add an entry for this `Peer` in the shared state map. - state.lock().unwrap() - .peers.insert(addr, tx); + state.lock().unwrap().peers.insert(addr, tx); Peer { name, @@ -198,7 +194,7 @@ impl Future for Peer { // though there could still be lines to read. Because we did // not reach `Async::NotReady`, we have to notify ourselves // in order to tell the executor to schedule the task again. - if i+1 == LINES_PER_TICK { + if i + 1 == LINES_PER_TICK { task::current().notify(); } } @@ -256,8 +252,7 @@ impl Future for Peer { impl Drop for Peer { fn drop(&mut self) { - self.state.lock().unwrap().peers - .remove(&self.addr); + self.state.lock().unwrap().peers.remove(&self.addr); } } @@ -333,7 +328,10 @@ impl Stream for Lines { let sock_closed = self.fill_read_buf()?.is_ready(); // Now, try finding lines - let pos = self.rd.windows(2).enumerate() + let pos = self + .rd + .windows(2) + .enumerate() .find(|&(_, bytes)| bytes == b"\r\n") .map(|(i, _)| i); @@ -373,7 +371,8 @@ fn process(socket: TcpStream, state: Arc>) { // We use the `into_future` combinator to extract the first item from the // lines stream. `into_future` takes a `Stream` and converts it to a future // of `(first, rest)` where `rest` is the original stream instance. - let connection = lines.into_future() + let connection = lines + .into_future() // `into_future` doesn't have the right error type, so map the error to // make it work. .map_err(|(e, _)| e) @@ -408,10 +407,7 @@ fn process(socket: TcpStream, state: Arc>) { // // This is also a future that processes the connection, only // completing when the socket closes. - let peer = Peer::new( - name, - state, - lines); + let peer = Peer::new(name, state, lines); // Wrap `peer` with `Either::B` to make the return type fit. Either::B(peer) @@ -443,18 +439,20 @@ pub fn main() -> Result<(), Box> { // The server task asynchronously iterates over and processes each // incoming connection. - let server = listener.incoming().for_each(move |socket| { - // Spawn a task to process the connection - process(socket, state.clone()); - Ok(()) - }) - .map_err(|err| { - // All tasks must have an `Error` type of `()`. This forces error - // handling and helps avoid silencing failures. - // - // In our example, we are only going to log the error to STDOUT. - println!("accept error = {:?}", err); - }); + let server = listener + .incoming() + .for_each(move |socket| { + // Spawn a task to process the connection + process(socket, state.clone()); + Ok(()) + }) + .map_err(|err| { + // All tasks must have an `Error` type of `()`. This forces error + // handling and helps avoid silencing failures. + // + // In our example, we are only going to log the error to STDOUT. + println!("accept error = {:?}", err); + }); println!("server running on localhost:6142"); diff --git a/examples/connect.rs b/examples/connect.rs index 93f55533c..4dc0ea31e 100644 --- a/examples/connect.rs +++ b/examples/connect.rs @@ -16,18 +16,18 @@ #![deny(warnings)] +extern crate bytes; +extern crate futures; extern crate tokio; extern crate tokio_io; -extern crate futures; -extern crate bytes; use std::env; use std::io::{self, Read, Write}; use std::net::SocketAddr; use std::thread; -use tokio::prelude::*; use futures::sync::mpsc; +use tokio::prelude::*; fn main() -> Result<(), Box> { // Determine if we're going to run in TCP or UDP mode @@ -73,18 +73,16 @@ fn main() -> Result<(), Box> { tokio::run({ stdout - .for_each(move |chunk| { - out.write_all(&chunk) - }) + .for_each(move |chunk| out.write_all(&chunk)) .map_err(|e| println!("error reading stdout; error = {:?}", e)) }); Ok(()) } mod codec { - use std::io; use bytes::{BufMut, BytesMut}; - use tokio::codec::{Encoder, Decoder}; + use std::io; + use tokio::codec::{Decoder, Encoder}; /// A simple `Codec` implementation that just ships bytes around. /// @@ -122,9 +120,9 @@ mod codec { mod tcp { use tokio; + use tokio::codec::Decoder; use tokio::net::TcpStream; use tokio::prelude::*; - use tokio::codec::Decoder; use bytes::BytesMut; use codec::Bytes; @@ -133,10 +131,10 @@ mod tcp { use std::io; use std::net::SocketAddr; - pub fn connect(addr: &SocketAddr, - stdin: Box, Error = io::Error> + Send>) - -> Result + Send>, Box> - { + pub fn connect( + addr: &SocketAddr, + stdin: Box, Error = io::Error> + Send>, + ) -> Result + Send>, Box> { let tcp = TcpStream::connect(addr); // After the TCP connection has been established, we set up our client @@ -154,18 +152,21 @@ mod tcp { // You'll also note that we *spawn* the work to read stdin and write it // to the TCP stream. This is done to ensure that happens concurrently // with us reading data from the stream. - let stream = Box::new(tcp.map(move |stream| { - let (sink, stream) = Bytes.framed(stream).split(); + let stream = Box::new( + tcp.map(move |stream| { + let (sink, stream) = Bytes.framed(stream).split(); - tokio::spawn(stdin.forward(sink).then(|result| { - if let Err(e) = result { - println!("failed to write to socket: {}", e) - } - Ok(()) - })); + tokio::spawn(stdin.forward(sink).then(|result| { + if let Err(e) = result { + println!("failed to write to socket: {}", e) + } + Ok(()) + })); - stream - }).flatten_stream()); + stream + }) + .flatten_stream(), + ); Ok(stream) } } @@ -175,17 +176,17 @@ mod udp { use std::io; use std::net::SocketAddr; - use tokio; - use tokio::net::{UdpSocket, UdpFramed}; - use tokio::prelude::*; use bytes::BytesMut; + use tokio; + use tokio::net::{UdpFramed, UdpSocket}; + use tokio::prelude::*; use codec::Bytes; - pub fn connect(&addr: &SocketAddr, - stdin: Box, Error = io::Error> + Send>) - -> Result + Send>, Box> - { + pub fn connect( + &addr: &SocketAddr, + stdin: Box, Error = io::Error> + Send>, + ) -> Result + Send>, Box> { // We'll bind our UDP socket to a local IP/port, but for now we // basically let the OS pick both of those. let addr_to_bind = if addr.ip().is_ipv4() { @@ -206,14 +207,15 @@ mod udp { // All bytes from `stdin` will go to the `addr` specified in our // argument list. Like with TCP this is spawned concurrently - let forward_stdin = stdin.map(move |chunk| { - (chunk, addr) - }).forward(sink).then(|result| { - if let Err(e) = result { - println!("failed to write to socket: {}", e) - } - Ok(()) - }); + let forward_stdin = stdin + .map(move |chunk| (chunk, addr)) + .forward(sink) + .then(|result| { + if let Err(e) = result { + println!("failed to write to socket: {}", e) + } + Ok(()) + }); // With UDP we could receive data from any source, so filter out // anything coming from a different address @@ -225,10 +227,13 @@ mod udp { } }); - let stream = Box::new(future::lazy(|| { - tokio::spawn(forward_stdin); - future::ok(receive) - }).flatten_stream()); + let stream = Box::new( + future::lazy(|| { + tokio::spawn(forward_stdin); + future::ok(receive) + }) + .flatten_stream(), + ); Ok(stream) } } @@ -240,8 +245,7 @@ fn read_stdin(mut tx: mpsc::Sender>) { loop { let mut buf = vec![0; 1024]; let n = match stdin.read(&mut buf) { - Err(_) | - Ok(0) => break, + Err(_) | Ok(0) => break, Ok(n) => n, }; buf.truncate(n); diff --git a/examples/echo-udp.rs b/examples/echo-udp.rs index 08a145637..93ebca799 100644 --- a/examples/echo-udp.rs +++ b/examples/echo-udp.rs @@ -16,11 +16,11 @@ extern crate futures; extern crate tokio; -use std::{env, io}; use std::net::SocketAddr; +use std::{env, io}; -use tokio::prelude::*; use tokio::net::UdpSocket; +use tokio::prelude::*; struct Server { socket: UdpSocket, diff --git a/examples/echo.rs b/examples/echo.rs index f33247cb7..45f808f89 100644 --- a/examples/echo.rs +++ b/examples/echo.rs @@ -54,7 +54,8 @@ fn main() -> Result<(), Box> { // connections made to the server). The return value of the `for_each` // method is itself a future representing processing the entire stream of // connections, and ends up being our server. - let done = socket.incoming() + let done = socket + .incoming() .map_err(|e| println!("failed to accept socket; error = {:?}", e)) .for_each(move |socket| { // Once we're inside this closure this represents an accepted client @@ -89,7 +90,6 @@ fn main() -> Result<(), Box> { Ok(()) }); - // And this is where much of the magic of this server happens. We // crucially want all clients to make progress concurrently, rather than // blocking one on completion of another. To achieve this we use the diff --git a/examples/hello_world.rs b/examples/hello_world.rs index a05a8f221..c82762691 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -25,20 +25,21 @@ pub fn main() -> Result<(), Box> { // Open a TCP stream to the socket address. // // Note that this is the Tokio TcpStream, which is fully async. - let client = TcpStream::connect(&addr).and_then(|stream| { - println!("created stream"); - io::write_all(stream, "hello world\n").then(|result| { - println!("wrote to stream; success={:?}", result.is_ok()); - Ok(()) + let client = TcpStream::connect(&addr) + .and_then(|stream| { + println!("created stream"); + io::write_all(stream, "hello world\n").then(|result| { + println!("wrote to stream; success={:?}", result.is_ok()); + Ok(()) + }) }) - }) - .map_err(|err| { - // All tasks must have an `Error` type of `()`. This forces error - // handling and helps avoid silencing failures. - // - // In our example, we are only going to log the error to STDOUT. - println!("connection error = {:?}", err); - }); + .map_err(|err| { + // All tasks must have an `Error` type of `()`. This forces error + // handling and helps avoid silencing failures. + // + // In our example, we are only going to log the error to STDOUT. + println!("connection error = {:?}", err); + }); // Start the Tokio runtime. // diff --git a/examples/print_each_packet.rs b/examples/print_each_packet.rs index 864d94bdc..94a606483 100644 --- a/examples/print_each_packet.rs +++ b/examples/print_each_packet.rs @@ -57,10 +57,10 @@ extern crate tokio; extern crate tokio_codec; -use tokio_codec::BytesCodec; +use tokio::codec::Decoder; use tokio::net::TcpListener; use tokio::prelude::*; -use tokio::codec::Decoder; +use tokio_codec::BytesCodec; use std::env; use std::net::SocketAddr; diff --git a/examples/proxy.rs b/examples/proxy.rs index 1df115fdd..ae8bf3a45 100644 --- a/examples/proxy.rs +++ b/examples/proxy.rs @@ -24,10 +24,10 @@ extern crate tokio; -use std::sync::{Arc, Mutex}; use std::env; -use std::net::{Shutdown, SocketAddr}; use std::io::{self, Read, Write}; +use std::net::{Shutdown, SocketAddr}; +use std::sync::{Arc, Mutex}; use tokio::io::{copy, shutdown}; use tokio::net::{TcpListener, TcpStream}; @@ -45,7 +45,8 @@ fn main() -> Result<(), Box> { println!("Listening on: {}", listen_addr); println!("Proxying to: {}", server_addr); - let done = socket.incoming() + let done = socket + .incoming() .map_err(|e| println!("error accepting socket; error = {:?}", e)) .for_each(move |client| { let server = TcpStream::connect(&server_addr); @@ -68,25 +69,25 @@ fn main() -> Result<(), Box> { // After the copy is done we indicate to the remote side that we've // finished by shutting down the connection. let client_to_server = copy(client_reader, server_writer) - .and_then(|(n, _, server_writer)| { - shutdown(server_writer).map(move |_| n) - }); + .and_then(|(n, _, server_writer)| shutdown(server_writer).map(move |_| n)); let server_to_client = copy(server_reader, client_writer) - .and_then(|(n, _, client_writer)| { - shutdown(client_writer).map(move |_| n) - }); + .and_then(|(n, _, client_writer)| shutdown(client_writer).map(move |_| n)); client_to_server.join(server_to_client) }); - let msg = amounts.map(move |(from_client, from_server)| { - println!("client wrote {} bytes and received {} bytes", - from_client, from_server); - }).map_err(|e| { - // Don't panic. Maybe the client just disconnected too soon. - println!("error: {}", e); - }); + let msg = amounts + .map(move |(from_client, from_server)| { + println!( + "client wrote {} bytes and received {} bytes", + from_client, from_server + ); + }) + .map_err(|e| { + // Don't panic. Maybe the client just disconnected too soon. + println!("error: {}", e); + }); tokio::spawn(msg); diff --git a/examples/tinydb.rs b/examples/tinydb.rs index 702704d3a..11298ed13 100644 --- a/examples/tinydb.rs +++ b/examples/tinydb.rs @@ -44,8 +44,8 @@ extern crate tokio; use std::collections::HashMap; -use std::io::BufReader; use std::env; +use std::io::BufReader; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; @@ -69,9 +69,18 @@ enum Request { /// Responses to the `Request` commands above enum Response { - Value { key: String, value: String }, - Set { key: String, value: String, previous: Option }, - Error { msg: String }, + Value { + key: String, + value: String, + }, + Set { + key: String, + value: String, + previous: Option, + }, + Error { + msg: String, + }, } fn main() -> Result<(), Box> { @@ -93,7 +102,8 @@ fn main() -> Result<(), Box> { map: Mutex::new(initial_db), }); - let done = listener.incoming() + let done = listener + .incoming() .map_err(|e| println!("error accepting socket; error = {:?}", e)) .for_each(move |socket| { // As with many other small examples, the first thing we'll do is @@ -124,15 +134,22 @@ fn main() -> Result<(), Box> { let mut db = db.map.lock().unwrap(); match request { - Request::Get { key } => { - match db.get(&key) { - Some(value) => Response::Value { key, value: value.clone() }, - None => Response::Error { msg: format!("no key {}", key) }, - } - } + Request::Get { key } => match db.get(&key) { + Some(value) => Response::Value { + key, + value: value.clone(), + }, + None => Response::Error { + msg: format!("no key {}", key), + }, + }, Request::Set { key, value } => { let previous = db.insert(key.clone(), value.clone()); - Response::Set { key, value, previous } + Response::Set { + key, + value, + previous, + } } } }); @@ -169,9 +186,11 @@ impl Request { None => return Err(format!("GET must be followed by a key")), }; if parts.next().is_some() { - return Err(format!("GET's key must not be followed by anything")) + return Err(format!("GET's key must not be followed by anything")); } - Ok(Request::Get { key: key.to_string() }) + Ok(Request::Get { + key: key.to_string(), + }) } Some("SET") => { let key = match parts.next() { @@ -182,7 +201,10 @@ impl Request { Some(value) => value, None => return Err(format!("SET needs a value")), }; - Ok(Request::Set { key: key.to_string(), value: value.to_string() }) + Ok(Request::Set { + key: key.to_string(), + value: value.to_string(), + }) } Some(cmd) => Err(format!("unknown command: {}", cmd)), None => Err(format!("empty input")), @@ -193,15 +215,13 @@ impl Request { impl Response { fn serialize(&self) -> String { match *self { - Response::Value { ref key, ref value } => { - format!("{} = {}", key, value) - } - Response::Set { ref key, ref value, ref previous } => { - format!("set {} = `{}`, previous: {:?}", key, value, previous) - } - Response::Error { ref msg } => { - format!("error: {}", msg) - } + Response::Value { ref key, ref value } => format!("{} = {}", key, value), + Response::Set { + ref key, + ref value, + ref previous, + } => format!("set {} = `{}`, previous: {:?}", key, value, previous), + Response::Error { ref msg } => format!("error: {}", msg), } } } diff --git a/examples/tinyhttp.rs b/examples/tinyhttp.rs index 4cbefcc9c..cde1b79af 100644 --- a/examples/tinyhttp.rs +++ b/examples/tinyhttp.rs @@ -23,12 +23,12 @@ extern crate time; extern crate tokio; extern crate tokio_io; -use std::{env, fmt, io}; use std::net::SocketAddr; +use std::{env, fmt, io}; -use tokio::net::{TcpStream, TcpListener}; +use tokio::codec::{Decoder, Encoder}; +use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; -use tokio::codec::{Encoder, Decoder}; use bytes::BytesMut; use http::header::HeaderValue; @@ -44,7 +44,8 @@ fn main() -> Result<(), Box> { println!("Listening on: {}", addr); tokio::run({ - listener.incoming() + listener + .incoming() .map_err(|e| println!("failed to accept socket; error = {:?}", e)) .for_each(|socket| { process(socket); @@ -64,14 +65,13 @@ fn process(socket: TcpStream) { .split(); // Map all requests into responses and send them back to the client. - let task = tx.send_all(rx.and_then(respond)) - .then(|res| { - if let Err(e) = res { - println!("failed to process connection; error = {:?}", e); - } + let task = tx.send_all(rx.and_then(respond)).then(|res| { + if let Err(e) = res { + println!("failed to process connection; error = {:?}", e); + } - Ok(()) - }); + Ok(()) + }); // Spawn the task that handles the connection. tokio::spawn(task); @@ -82,9 +82,7 @@ fn process(socket: TcpStream) { /// This function is a map from and HTTP request to a future of a response and /// represents the various handling a server might do. Currently the contents /// here are pretty uninteresting. -fn respond(req: Request<()>) - -> Box, Error = io::Error> + Send> -{ +fn respond(req: Request<()>) -> Box, Error = io::Error> + Send> { let f = future::lazy(move || { let mut response = Response::builder(); let body = match req.uri().path() { @@ -99,14 +97,18 @@ fn respond(req: Request<()>) struct Message { message: &'static str, } - serde_json::to_string(&Message { message: "Hello, World!" })? + serde_json::to_string(&Message { + message: "Hello, World!", + })? } _ => { response.status(StatusCode::NOT_FOUND); String::new() } }; - let response = response.body(body).map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; + let response = response + .body(body) + .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?; Ok(response) }); @@ -124,12 +126,19 @@ impl Encoder for Http { fn encode(&mut self, item: Response, dst: &mut BytesMut) -> io::Result<()> { use std::fmt::Write; - write!(BytesWrite(dst), "\ - HTTP/1.1 {}\r\n\ - Server: Example\r\n\ - Content-Length: {}\r\n\ - Date: {}\r\n\ - ", item.status(), item.body().len(), date::now()).unwrap(); + write!( + BytesWrite(dst), + "\ + HTTP/1.1 {}\r\n\ + Server: Example\r\n\ + Content-Length: {}\r\n\ + Date: {}\r\n\ + ", + item.status(), + item.body().len(), + date::now() + ) + .unwrap(); for (k, v) in item.headers() { dst.extend_from_slice(k.as_str().as_bytes()); @@ -198,13 +207,18 @@ impl Decoder for Http { headers[i] = Some((k, v)); } - (toslice(r.method.unwrap().as_bytes()), - toslice(r.path.unwrap().as_bytes()), - r.version.unwrap(), - amt) + ( + toslice(r.method.unwrap().as_bytes()), + toslice(r.path.unwrap().as_bytes()), + r.version.unwrap(), + amt, + ) }; if version != 1 { - return Err(io::Error::new(io::ErrorKind::Other, "only HTTP/1.1 accepted")) + return Err(io::Error::new( + io::ErrorKind::Other, + "only HTTP/1.1 accepted", + )); } let data = src.split_to(amt).freeze(); let mut ret = Request::builder(); @@ -216,15 +230,13 @@ impl Decoder for Http { Some((ref k, ref v)) => (k, v), None => break, }; - let value = unsafe { - HeaderValue::from_shared_unchecked(data.slice(v.0, v.1)) - }; + let value = unsafe { HeaderValue::from_shared_unchecked(data.slice(v.0, v.1)) }; ret.header(&data[k.0..k.1], value); } - let req = ret.body(()).map_err(|e| { - io::Error::new(io::ErrorKind::Other, e) - })?; + let req = ret + .body(()) + .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; Ok(Some(req)) } } diff --git a/examples/udp-client.rs b/examples/udp-client.rs index d2d4bc994..900d3616d 100644 --- a/examples/udp-client.rs +++ b/examples/udp-client.rs @@ -51,7 +51,8 @@ fn main() -> Result<(), Box> { "0.0.0.0:0" } else { "[::]:0" - }.parse()?; + } + .parse()?; let socket = UdpSocket::bind(&local_addr)?; const MAX_DATAGRAM_SIZE: usize = 65_507; socket diff --git a/examples/udp-codec.rs b/examples/udp-codec.rs index 837266ac0..3657d8cc1 100644 --- a/examples/udp-codec.rs +++ b/examples/udp-codec.rs @@ -8,15 +8,15 @@ #![deny(warnings)] +extern crate env_logger; extern crate tokio; extern crate tokio_codec; extern crate tokio_io; -extern crate env_logger; use std::net::SocketAddr; +use tokio::net::{UdpFramed, UdpSocket}; use tokio::prelude::*; -use tokio::net::{UdpSocket, UdpFramed}; use tokio_codec::BytesCodec; fn main() -> Result<(), Box> { diff --git a/src/async_await.rs b/src/async_await.rs index 88903643f..900a68036 100644 --- a/src/async_await.rs +++ b/src/async_await.rs @@ -1,4 +1,4 @@ -use std::future::{Future as StdFuture}; +use std::future::Future as StdFuture; async fn map_ok(future: T) -> Result<(), ()> { let _ = await!(future); @@ -7,7 +7,8 @@ async fn map_ok(future: T) -> Result<(), ()> { /// Like `tokio::run`, but takes an `async` block pub fn run_async(future: F) -where F: StdFuture + Send + 'static, +where + F: StdFuture + Send + 'static, { use tokio_async_await::compat::backward; let future = backward::Compat::new(map_ok(future)); @@ -17,7 +18,8 @@ where F: StdFuture + Send + 'static, /// Like `tokio::spawn`, but takes an `async` block pub fn spawn_async(future: F) -where F: StdFuture + Send + 'static, +where + F: StdFuture + Send + 'static, { use tokio_async_await::compat::backward; let future = backward::Compat::new(map_ok(future)); diff --git a/src/codec/length_delimited.rs b/src/codec/length_delimited.rs index 174a7ab0c..c9245f1c5 100644 --- a/src/codec/length_delimited.rs +++ b/src/codec/length_delimited.rs @@ -355,19 +355,15 @@ //! [`BytesMut`]: https://docs.rs/bytes/0.4/bytes/struct.BytesMut.html use { - codec::{ - Decoder, Encoder, FramedRead, FramedWrite, Framed - }, - io::{ - AsyncRead, AsyncWrite - }, + codec::{Decoder, Encoder, Framed, FramedRead, FramedWrite}, + io::{AsyncRead, AsyncWrite}, }; use bytes::{Buf, BufMut, Bytes, BytesMut, IntoBuf}; -use std::{cmp, fmt}; use std::error::Error as StdError; use std::io::{self, Cursor}; +use std::{cmp, fmt}; /// Configure length delimited `LengthDelimitedCodec`s. /// @@ -476,9 +472,10 @@ impl LengthDelimitedCodec { }; if n > self.builder.max_frame_len as u64 { - return Err(io::Error::new(io::ErrorKind::InvalidData, FrameTooBig { - _priv: (), - })); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + FrameTooBig { _priv: () }, + )); } // The check above ensures there is no overflow @@ -494,7 +491,12 @@ impl LengthDelimitedCodec { // Error handling match n { Some(n) => n, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, "provided length would overflow after adjustment")), + None => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "provided length would overflow after adjustment", + )); + } } }; @@ -528,15 +530,13 @@ impl Decoder for LengthDelimitedCodec { fn decode(&mut self, src: &mut BytesMut) -> io::Result> { let n = match self.state { - DecodeState::Head => { - match try!(self.decode_head(src)) { - Some(n) => { - self.state = DecodeState::Data(n); - n - } - None => return Ok(None), + DecodeState::Head => match try!(self.decode_head(src)) { + Some(n) => { + self.state = DecodeState::Data(n); + n } - } + None => return Ok(None), + }, DecodeState::Data(n) => n, }; @@ -563,9 +563,10 @@ impl Encoder for LengthDelimitedCodec { let n = (&data).into_buf().remaining(); if n > self.builder.max_frame_len { - return Err(io::Error::new(io::ErrorKind::InvalidInput, FrameTooBig { - _priv: (), - })); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + FrameTooBig { _priv: () }, + )); } // Adjust `n` with bounds checking @@ -575,10 +576,12 @@ impl Encoder for LengthDelimitedCodec { n.checked_sub(self.builder.length_adjustment as usize) }; - let n = n.ok_or_else(|| io::Error::new( - io::ErrorKind::InvalidInput, - "provided length would overflow after adjustment", - ))?; + let n = n.ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "provided length would overflow after adjustment", + ) + })?; // Reserve capacity in the destination buffer to fit the frame and // length field (plus adjustment). @@ -892,7 +895,8 @@ impl Builder { /// # pub fn main() {} /// ``` pub fn new_read(&self, upstream: T) -> FramedRead - where T: AsyncRead, + where + T: AsyncRead, { FramedRead::new(upstream, self.new_codec()) } @@ -915,7 +919,8 @@ impl Builder { /// # pub fn main() {} /// ``` pub fn new_write(&self, inner: T) -> FramedWrite - where T: AsyncWrite, + where + T: AsyncWrite, { FramedWrite::new(inner, self.new_codec()) } @@ -939,7 +944,8 @@ impl Builder { /// # pub fn main() {} /// ``` pub fn new_framed(&self, inner: T) -> Framed - where T: AsyncRead + AsyncWrite, + where + T: AsyncRead + AsyncWrite, { Framed::new(inner, self.new_codec()) } @@ -950,17 +956,16 @@ impl Builder { } fn get_num_skip(&self) -> usize { - self.num_skip.unwrap_or(self.length_field_offset + self.length_field_len) + self.num_skip + .unwrap_or(self.length_field_offset + self.length_field_len) } } - // ===== impl FrameTooBig ===== impl fmt::Debug for FrameTooBig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("FrameTooBig") - .finish() + f.debug_struct("FrameTooBig").finish() } } diff --git a/src/codec/mod.rs b/src/codec/mod.rs index cb0fc922d..b6a3bbcb0 100644 --- a/src/codec/mod.rs +++ b/src/codec/mod.rs @@ -11,14 +11,7 @@ //! [transports]: https://tokio.rs/docs/going-deeper/frames/ pub use tokio_codec::{ - Decoder, - Encoder, - Framed, - FramedParts, - FramedRead, - FramedWrite, - BytesCodec, - LinesCodec, + BytesCodec, Decoder, Encoder, Framed, FramedParts, FramedRead, FramedWrite, LinesCodec, }; pub mod length_delimited; diff --git a/src/fs.rs b/src/fs.rs index e9f050bbb..5d185cd0f 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -7,7 +7,9 @@ //! the context of the Tokio runtime as they require Tokio specific features to //! function. -pub use tokio_fs::{create_dir, create_dir_all, file, hard_link, metadata, os, read_dir, read_link}; -pub use tokio_fs::{remove_dir, remove_file, rename, set_permissions, symlink_metadata, File}; pub use tokio_fs::OpenOptions; +pub use tokio_fs::{ + create_dir, create_dir_all, file, hard_link, metadata, os, read_dir, read_link, +}; pub use tokio_fs::{read, write, ReadFile, WriteFile}; +pub use tokio_fs::{remove_dir, remove_file, rename, set_permissions, symlink_metadata, File}; diff --git a/src/io.rs b/src/io.rs index 1f7ecc28c..feb1f6b26 100644 --- a/src/io.rs +++ b/src/io.rs @@ -45,51 +45,18 @@ //! [`ErrorKind`]: enum.ErrorKind.html //! [`Result`]: type.Result.html -pub use tokio_io::{ - AsyncRead, - AsyncWrite, -}; +pub use tokio_io::{AsyncRead, AsyncWrite}; // standard input, output, and error #[cfg(feature = "fs")] -pub use tokio_fs::{ - stdin, - Stdin, - stdout, - Stdout, - stderr, - Stderr, -}; +pub use tokio_fs::{stderr, stdin, stdout, Stderr, Stdin, Stdout}; // Utils pub use tokio_io::io::{ - copy, - Copy, - flush, - Flush, - lines, - Lines, - read, - read_exact, - ReadExact, - read_to_end, - ReadToEnd, - read_until, - ReadUntil, - ReadHalf, - shutdown, - Shutdown, - write_all, - WriteAll, - WriteHalf, + copy, flush, lines, read, read_exact, read_to_end, read_until, shutdown, write_all, Copy, + Flush, Lines, ReadExact, ReadHalf, ReadToEnd, ReadUntil, Shutdown, WriteAll, WriteHalf, }; // Re-export io::Error so that users don't have to deal // with conflicts when `use`ing `futures::io` and `std::io`. -pub use ::std::io::{ - Error, - ErrorKind, - Result, - Read, - Write, -}; +pub use std::io::{Error, ErrorKind, Read, Result, Write}; diff --git a/src/lib.rs b/src/lib.rs index e61112505..4f75764ef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,9 @@ #![doc(html_root_url = "https://docs.rs/tokio/0.1.15")] #![deny(missing_docs, warnings, missing_debug_implementations)] -#![cfg_attr(feature = "async-await-preview", feature( - async_await, - await_macro, - futures_api, - ))] +#![cfg_attr( + feature = "async-await-preview", + feature(async_await, await_macro, futures_api,) +)] //! A runtime for writing reliable, asynchronous, and slim applications. //! @@ -88,24 +87,24 @@ extern crate bytes; extern crate mio; #[cfg(feature = "rt-full")] extern crate num_cpus; -#[cfg(feature = "rt-full")] -extern crate tokio_current_thread; -#[cfg(feature = "io")] -extern crate tokio_io; #[cfg(feature = "codec")] extern crate tokio_codec; +#[cfg(feature = "rt-full")] +extern crate tokio_current_thread; #[cfg(feature = "fs")] extern crate tokio_fs; +#[cfg(feature = "io")] +extern crate tokio_io; #[cfg(feature = "reactor")] extern crate tokio_reactor; -#[cfg(feature = "rt-full")] -extern crate tokio_threadpool; #[cfg(feature = "sync")] extern crate tokio_sync; -#[cfg(feature = "timer")] -extern crate tokio_timer; #[cfg(feature = "tcp")] extern crate tokio_tcp; +#[cfg(feature = "rt-full")] +extern crate tokio_threadpool; +#[cfg(feature = "timer")] +extern crate tokio_timer; #[cfg(feature = "udp")] extern crate tokio_udp; diff --git a/src/prelude.rs b/src/prelude.rs index 5ca20399e..17b2469d1 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -11,45 +11,18 @@ //! The prelude may grow over time as additional items see ubiquitous use. #[cfg(feature = "io")] -pub use tokio_io::{ - AsyncRead, - AsyncWrite, -}; +pub use tokio_io::{AsyncRead, AsyncWrite}; -pub use util::{ - FutureExt, - StreamExt, -}; +pub use util::{FutureExt, StreamExt}; -pub use ::std::io::{ - Read, - Write, -}; +pub use std::io::{Read, Write}; -pub use futures::{ - Future, - future, - Stream, - stream, - Sink, - IntoFuture, - Async, - AsyncSink, - Poll, - task, -}; +pub use futures::{future, stream, task, Async, AsyncSink, Future, IntoFuture, Poll, Sink, Stream}; #[cfg(feature = "async-await-preview")] #[doc(inline)] pub use tokio_async_await::{ - io::{ - AsyncReadExt, - AsyncWriteExt, - }, - sink::{ - SinkExt, - }, - stream::{ - StreamExt as StreamAsyncExt, - }, + io::{AsyncReadExt, AsyncWriteExt}, + sink::SinkExt, + stream::StreamExt as StreamAsyncExt, }; diff --git a/src/reactor/mod.rs b/src/reactor/mod.rs index a7263fd83..0e3f4eaab 100644 --- a/src/reactor/mod.rs +++ b/src/reactor/mod.rs @@ -136,12 +136,7 @@ //! [`std::io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html pub use tokio_reactor::{ - Reactor, - Handle, - Background, - Turn, - Registration, - PollEvented as PollEvented2, + Background, Handle, PollEvented as PollEvented2, Reactor, Registration, Turn, }; mod poll_evented; diff --git a/src/reactor/poll_evented.rs b/src/reactor/poll_evented.rs index d5f6750b6..74e5d2ed8 100644 --- a/src/reactor/poll_evented.rs +++ b/src/reactor/poll_evented.rs @@ -10,9 +10,9 @@ use std::fmt; use std::io::{self, Read, Write}; -use std::sync::Mutex; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; +use std::sync::Mutex; use futures::{task, Async, Poll}; use mio::event::Evented; @@ -41,9 +41,7 @@ struct Inner { impl fmt::Debug for PollEvented { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("PollEvented") - .field("io", &self.io) - .finish() + f.debug_struct("PollEvented").field("io", &self.io).finish() } } @@ -51,7 +49,8 @@ impl PollEvented { /// Creates a new readiness stream associated with the provided /// `loop_handle` and for the given `source`. pub fn new(io: E, handle: &Handle) -> io::Result> - where E: Evented, + where + E: Evented, { let registration = Registration::new(); registration.register(&io)?; @@ -153,7 +152,9 @@ impl PollEvented { }; // Cache the value - self.inner.write_readiness.store(ready2usize(ready), Relaxed); + self.inner + .write_readiness + .store(ready2usize(ready), Relaxed); ().into() } @@ -334,17 +335,17 @@ impl PollEvented { /// method is called, and will likely return an error if this `PollEvented` /// was created on a separate event loop from the `handle` specified. pub fn deregister(&self) -> io::Result<()> - where E: Evented, + where + E: Evented, { - self.inner.registration.lock().unwrap() - .deregister(&self.io) + self.inner.registration.lock().unwrap().deregister(&self.io) } } impl Read for PollEvented { fn read(&mut self, buf: &mut [u8]) -> io::Result { if let Async::NotReady = self.poll_read() { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().read(buf); @@ -353,14 +354,14 @@ impl Read for PollEvented { self.need_read()?; } - return r + return r; } } impl Write for PollEvented { fn write(&mut self, buf: &[u8]) -> io::Result { if let Async::NotReady = self.poll_write() { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().write(buf); @@ -369,12 +370,12 @@ impl Write for PollEvented { self.need_write()?; } - return r + return r; } fn flush(&mut self) -> io::Result<()> { if let Async::NotReady = self.poll_write() { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().flush(); @@ -383,12 +384,11 @@ impl Write for PollEvented { self.need_write()?; } - return r + return r; } } -impl AsyncRead for PollEvented { -} +impl AsyncRead for PollEvented {} impl AsyncWrite for PollEvented { fn shutdown(&mut self) -> Poll<(), io::Error> { @@ -430,8 +430,8 @@ fn usize2ready(bits: usize) -> Ready { #[cfg(unix)] mod platform { - use mio::Ready; use mio::unix::UnixReady; + use mio::Ready; const HUP: usize = 1 << 2; const ERROR: usize = 1 << 3; @@ -476,14 +476,22 @@ mod platform { bits } - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", - target_os = "macos"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos" + ))] fn usize2ready_aio(ready: &mut UnixReady) { ready.insert(UnixReady::aio()); } - #[cfg(not(any(target_os = "dragonfly", - target_os = "freebsd", target_os = "ios", target_os = "macos")))] + #[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos" + )))] fn usize2ready_aio(_ready: &mut UnixReady) { // aio not available here → empty } diff --git a/src/sync.rs b/src/sync.rs index 52b8787b0..6aa42164a 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -10,7 +10,4 @@ //! - [mpsc](mpsc/index.html), a multi-producer, single-consumer channel for //! sending values between tasks. -pub use tokio_sync::{ - mpsc, - oneshot, -}; +pub use tokio_sync::{mpsc, oneshot}; diff --git a/src/timer.rs b/src/timer.rs index fc85a2a72..888e7a9db 100644 --- a/src/timer.rs +++ b/src/timer.rs @@ -82,15 +82,7 @@ //! [Interval]: struct.Interval.html //! [`DelayQueue`]: struct.DelayQueue.html -pub use tokio_timer::{ - delay_queue, - DelayQueue, - Error, - Interval, - Delay, - Timeout, - timeout, -}; +pub use tokio_timer::{delay_queue, timeout, Delay, DelayQueue, Error, Interval, Timeout}; #[deprecated(since = "0.1.8", note = "use Timeout instead")] #[allow(deprecated)] diff --git a/src/util/enumerate.rs b/src/util/enumerate.rs index dccbb7161..8f6926fa4 100644 --- a/src/util/enumerate.rs +++ b/src/util/enumerate.rs @@ -1,4 +1,4 @@ -use futures::{Async, Poll, Stream, Sink, StartSend}; +use futures::{Async, Poll, Sink, StartSend, Stream}; /// A stream combinator which combines the yields the current item /// plus its count starting from 0. @@ -13,7 +13,10 @@ pub struct Enumerate { impl Enumerate { pub(crate) fn new(stream: T) -> Self { - Self { inner: stream, count: 0 } + Self { + inner: stream, + count: 0, + } } /// Acquires a reference to the underlying stream that this combinator is @@ -61,7 +64,8 @@ where // Forwarding impl of Sink from the underlying stream impl Sink for Enumerate - where T: Sink +where + T: Sink, { type SinkItem = T::SinkItem; type SinkError = T::SinkError; diff --git a/src/util/future.rs b/src/util/future.rs index cae0fc9bb..5a3818101 100644 --- a/src/util/future.rs +++ b/src/util/future.rs @@ -7,8 +7,7 @@ use tokio_timer::Timeout; use futures::Future; #[cfg(feature = "timer")] -use std::time::{Instant, Duration}; - +use std::time::{Duration, Instant}; /// An extension trait for `Future` that provides a variety of convenient /// combinator functions. @@ -24,7 +23,6 @@ use std::time::{Instant, Duration}; /// /// [`timeout`]: #method.timeout pub trait FutureExt: Future { - /// Creates a new future which allows `self` until `timeout`. /// /// This combinator creates a new future which wraps the receiving future @@ -60,7 +58,8 @@ pub trait FutureExt: Future { /// ``` #[cfg(feature = "timer")] fn timeout(self, timeout: Duration) -> Timeout - where Self: Sized, + where + Self: Sized, { Timeout::new(self, timeout) } @@ -70,7 +69,8 @@ pub trait FutureExt: Future { #[allow(deprecated)] #[doc(hidden)] fn deadline(self, deadline: Instant) -> Deadline - where Self: Sized, + where + Self: Sized, { Deadline::new(self, deadline) } diff --git a/src/util/mod.rs b/src/util/mod.rs index e26f44ca9..58fd3d0b0 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -7,9 +7,9 @@ //! [`FutureExt`]: trait.FutureExt.html //! [`StreamExt`]: trait.StreamExt.html +mod enumerate; mod future; mod stream; -mod enumerate; pub use self::future::FutureExt; pub use self::stream::StreamExt; diff --git a/src/util/stream.rs b/src/util/stream.rs index 8f3d7e81d..3b7aa2686 100644 --- a/src/util/stream.rs +++ b/src/util/stream.rs @@ -1,8 +1,5 @@ #[cfg(feature = "timer")] -use tokio_timer::{ - throttle::Throttle, - Timeout, -}; +use tokio_timer::{throttle::Throttle, Timeout}; use futures::Stream; @@ -29,7 +26,8 @@ pub trait StreamExt: Stream { /// Errors are also delayed. #[cfg(feature = "timer")] fn throttle(self, duration: Duration) -> Throttle - where Self: Sized + where + Self: Sized, { Throttle::new(self, duration) } @@ -47,7 +45,8 @@ pub trait StreamExt: Stream { /// an iterator with more than [`std::usize::MAX`] elements either produces the /// wrong result or panics. fn enumerate(self) -> Enumerate - where Self: Sized, + where + Self: Sized, { Enumerate::new(self) } @@ -86,7 +85,8 @@ pub trait StreamExt: Stream { /// ``` #[cfg(feature = "timer")] fn timeout(self, timeout: Duration) -> Timeout - where Self: Sized, + where + Self: Sized, { Timeout::new(self, timeout) } diff --git a/tests/buffered.rs b/tests/buffered.rs index 3605eba38..45560ad20 100644 --- a/tests/buffered.rs +++ b/tests/buffered.rs @@ -3,20 +3,22 @@ extern crate futures; extern crate tokio; extern crate tokio_io; +use std::io::{BufReader, BufWriter, Read, Write}; use std::net::TcpStream; use std::thread; -use std::io::{Read, Write, BufReader, BufWriter}; -use futures::Future; use futures::stream::Stream; -use tokio_io::io::copy; +use futures::Future; use tokio::net::TcpListener; +use tokio_io::io::copy; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] diff --git a/tests/clock.rs b/tests/clock.rs index 6e9d9121f..184705aed 100644 --- a/tests/clock.rs +++ b/tests/clock.rs @@ -1,7 +1,7 @@ +extern crate env_logger; extern crate futures; extern crate tokio; extern crate tokio_timer; -extern crate env_logger; use tokio::prelude::*; use tokio::runtime::{self, current_thread}; @@ -26,10 +26,7 @@ fn clock_and_timer_concurrent() { let when = Instant::now() + Duration::from_millis(5_000); let clock = Clock::new_with_now(MockNow(when)); - let mut rt = runtime::Builder::new() - .clock(clock) - .build() - .unwrap(); + let mut rt = runtime::Builder::new().clock(clock).build().unwrap(); let (tx, rx) = mpsc::channel(); @@ -53,10 +50,7 @@ fn clock_and_timer_single_threaded() { let when = Instant::now() + Duration::from_millis(5_000); let clock = Clock::new_with_now(MockNow(when)); - let mut rt = current_thread::Builder::new() - .clock(clock) - .build() - .unwrap(); + let mut rt = current_thread::Builder::new().clock(clock).build().unwrap(); rt.block_on({ Delay::new(when) @@ -65,5 +59,6 @@ fn clock_and_timer_single_threaded() { assert!(Instant::now() < when); Ok(()) }) - }).unwrap(); + }) + .unwrap(); } diff --git a/tests/drop-core.rs b/tests/drop-core.rs index 75ac9b7eb..8be0d711d 100644 --- a/tests/drop-core.rs +++ b/tests/drop-core.rs @@ -1,8 +1,8 @@ -extern crate tokio; extern crate futures; +extern crate tokio; -use std::thread; use std::net; +use std::thread; use futures::future; use futures::prelude::*; diff --git a/tests/enumerate.rs b/tests/enumerate.rs index dc16443fb..c71b7a24c 100644 --- a/tests/enumerate.rs +++ b/tests/enumerate.rs @@ -23,5 +23,4 @@ fn enumerate() { result.wait(), Ok(vec![(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)]) ); - } diff --git a/tests/global.rs b/tests/global.rs index d3bc09315..1bf45a66f 100644 --- a/tests/global.rs +++ b/tests/global.rs @@ -1,42 +1,48 @@ +extern crate env_logger; extern crate futures; extern crate tokio; extern crate tokio_io; -extern crate env_logger; -use std::{io, thread}; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; +use std::sync::Arc; +use std::{io, thread}; use futures::prelude::*; -use tokio::net::{TcpStream, TcpListener}; +use tokio::net::{TcpListener, TcpStream}; use tokio::runtime::Runtime; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] fn hammer_old() { let _ = env_logger::try_init(); - let threads = (0..10).map(|_| { - thread::spawn(|| { - let srv = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap())); - let addr = t!(srv.local_addr()); - let mine = TcpStream::connect(&addr); - let theirs = srv.incoming().into_future() - .map(|(s, _)| s.unwrap()) - .map_err(|(s, _)| s); - let (mine, theirs) = t!(mine.join(theirs).wait()); + let threads = (0..10) + .map(|_| { + thread::spawn(|| { + let srv = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap())); + let addr = t!(srv.local_addr()); + let mine = TcpStream::connect(&addr); + let theirs = srv + .incoming() + .into_future() + .map(|(s, _)| s.unwrap()) + .map_err(|(s, _)| s); + let (mine, theirs) = t!(mine.join(theirs).wait()); - assert_eq!(t!(mine.local_addr()), t!(theirs.peer_addr())); - assert_eq!(t!(theirs.local_addr()), t!(mine.peer_addr())); + assert_eq!(t!(mine.local_addr()), t!(theirs.peer_addr())); + assert_eq!(t!(theirs.local_addr()), t!(mine.peer_addr())); + }) }) - }).collect::>(); + .collect::>(); for thread in threads { thread.join().unwrap(); } @@ -51,8 +57,7 @@ impl io::Read for Rd { } } -impl tokio_io::AsyncRead for Rd { -} +impl tokio_io::AsyncRead for Rd {} impl io::Write for Wr { fn write(&mut self, src: &[u8]) -> io::Result { diff --git a/tests/length_delimited.rs b/tests/length_delimited.rs index 4e118d379..f87cfa936 100644 --- a/tests/length_delimited.rs +++ b/tests/length_delimited.rs @@ -1,16 +1,16 @@ -extern crate tokio; -extern crate futures; extern crate bytes; +extern crate futures; +extern crate tokio; -use tokio::io::{AsyncRead, AsyncWrite}; use tokio::codec::*; +use tokio::io::{AsyncRead, AsyncWrite}; -use bytes::{Bytes, BytesMut, BufMut}; -use futures::{Stream, Sink, Poll}; +use bytes::{BufMut, Bytes, BytesMut}; use futures::Async::*; +use futures::{Poll, Sink, Stream}; -use std::io; use std::collections::VecDeque; +use std::io; macro_rules! mock { ($($x:expr,)*) => {{ @@ -20,7 +20,6 @@ macro_rules! mock { }}; } - #[test] fn read_empty_io_yields_nothing() { let mut io = FramedRead::new(mock!(), LengthDelimitedCodec::new()); @@ -30,9 +29,12 @@ fn read_empty_io_yields_nothing() { #[test] fn read_single_frame_one_packet() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(None)); @@ -74,9 +76,12 @@ fn read_single_multi_frame_one_packet() { data.extend_from_slice(b"\x00\x00\x00\x03123"); data.extend_from_slice(b"\x00\x00\x00\x0bhello world"); - let mut io = FramedRead::new(mock! { - Ok(data.into()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(data.into()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(Some(b"123"[..].into()))); @@ -86,11 +91,14 @@ fn read_single_multi_frame_one_packet() { #[test] fn read_single_frame_multi_packet() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00"[..].into()), - Ok(b"\x00\x09abc"[..].into()), - Ok(b"defghi"[..].into()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00"[..].into()), + Ok(b"\x00\x09abc"[..].into()), + Ok(b"defghi"[..].into()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(None)); @@ -98,13 +106,16 @@ fn read_single_frame_multi_packet() { #[test] fn read_multi_frame_multi_packet() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00"[..].into()), - Ok(b"\x00\x09abc"[..].into()), - Ok(b"defghi"[..].into()), - Ok(b"\x00\x00\x00\x0312"[..].into()), - Ok(b"3\x00\x00\x00\x0bhello world"[..].into()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00"[..].into()), + Ok(b"\x00\x09abc"[..].into()), + Ok(b"defghi"[..].into()), + Ok(b"\x00\x00\x00\x0312"[..].into()), + Ok(b"3\x00\x00\x00\x0bhello world"[..].into()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(Some(b"123"[..].into()))); @@ -114,14 +125,17 @@ fn read_multi_frame_multi_packet() { #[test] fn read_single_frame_multi_packet_wait() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00"[..].into()), - Err(would_block()), - Ok(b"\x00\x09abc"[..].into()), - Err(would_block()), - Ok(b"defghi"[..].into()), - Err(would_block()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00"[..].into()), + Err(would_block()), + Ok(b"\x00\x09abc"[..].into()), + Err(would_block()), + Ok(b"defghi"[..].into()), + Err(would_block()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), NotReady); @@ -132,19 +146,21 @@ fn read_single_frame_multi_packet_wait() { #[test] fn read_multi_frame_multi_packet_wait() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00"[..].into()), - Err(would_block()), - Ok(b"\x00\x09abc"[..].into()), - Err(would_block()), - Ok(b"defghi"[..].into()), - Err(would_block()), - Ok(b"\x00\x00\x00\x0312"[..].into()), - Err(would_block()), - Ok(b"3\x00\x00\x00\x0bhello world"[..].into()), - Err(would_block()), - }, LengthDelimitedCodec::new()); - + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00"[..].into()), + Err(would_block()), + Ok(b"\x00\x09abc"[..].into()), + Err(would_block()), + Ok(b"defghi"[..].into()), + Err(would_block()), + Ok(b"\x00\x00\x00\x0312"[..].into()), + Err(would_block()), + Ok(b"3\x00\x00\x00\x0bhello world"[..].into()), + Err(would_block()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), NotReady); @@ -159,20 +175,26 @@ fn read_multi_frame_multi_packet_wait() { #[test] fn read_incomplete_head() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00"[..].into()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00"[..].into()), + }, + LengthDelimitedCodec::new(), + ); assert!(io.poll().is_err()); } #[test] fn read_incomplete_head_multi() { - let mut io = FramedRead::new(mock! { - Err(would_block()), - Ok(b"\x00"[..].into()), - Err(would_block()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Err(would_block()), + Ok(b"\x00"[..].into()), + Err(would_block()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), NotReady); @@ -181,12 +203,15 @@ fn read_incomplete_head_multi() { #[test] fn read_incomplete_payload() { - let mut io = FramedRead::new(mock! { - Ok(b"\x00\x00\x00\x09ab"[..].into()), - Err(would_block()), - Ok(b"cd"[..].into()), - Err(would_block()), - }, LengthDelimitedCodec::new()); + let mut io = FramedRead::new( + mock! { + Ok(b"\x00\x00\x00\x09ab"[..].into()), + Err(would_block()), + Ok(b"cd"[..].into()), + Err(would_block()), + }, + LengthDelimitedCodec::new(), + ); assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), NotReady); @@ -206,11 +231,10 @@ fn read_max_frame_len() { #[test] fn read_update_max_frame_len_at_rest() { - let mut io = length_delimited::Builder::new() - .new_read(mock! { - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }); + let mut io = length_delimited::Builder::new().new_read(mock! { + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); io.decoder_mut().set_max_frame_length(5); @@ -219,13 +243,12 @@ fn read_update_max_frame_len_at_rest() { #[test] fn read_update_max_frame_len_in_flight() { - let mut io = length_delimited::Builder::new() - .new_read(mock! { - Ok(b"\x00\x00\x00\x09abcd"[..].into()), - Err(would_block()), - Ok(b"efghi"[..].into()), - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }); + let mut io = length_delimited::Builder::new().new_read(mock! { + Ok(b"\x00\x00\x00\x09abcd"[..].into()), + Err(would_block()), + Ok(b"efghi"[..].into()), + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), NotReady); io.decoder_mut().set_max_frame_length(5); @@ -274,9 +297,15 @@ fn read_single_multi_frame_one_packet_skip_none_adjusted() { Ok(data.into()), }); - assert_eq!(io.poll().unwrap(), Ready(Some(b"xx\x00\x09abcdefghi"[..].into()))); + assert_eq!( + io.poll().unwrap(), + Ready(Some(b"xx\x00\x09abcdefghi"[..].into())) + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"yy\x00\x03123"[..].into()))); - assert_eq!(io.poll().unwrap(), Ready(Some(b"zz\x00\x0bhello world"[..].into()))); + assert_eq!( + io.poll().unwrap(), + Ready(Some(b"zz\x00\x0bhello world"[..].into())) + ); assert_eq!(io.poll().unwrap(), Ready(None)); } @@ -316,20 +345,20 @@ fn write_single_frame_length_adjusted() { #[test] fn write_nothing_yields_nothing() { - let mut io = FramedWrite::new( - mock!(), - LengthDelimitedCodec::new() - ); + let mut io = FramedWrite::new(mock!(), LengthDelimitedCodec::new()); assert!(io.poll_complete().unwrap().is_ready()); } #[test] fn write_single_frame_one_packet() { - let mut io = FramedWrite::new(mock! { - Ok(b"\x00\x00\x00\x09"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - }, LengthDelimitedCodec::new()); + let mut io = FramedWrite::new( + mock! { + Ok(b"\x00\x00\x00\x09"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + }, + LengthDelimitedCodec::new(), + ); assert!(io.start_send(Bytes::from("abcdefghi")).unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); @@ -338,56 +367,71 @@ fn write_single_frame_one_packet() { #[test] fn write_single_multi_frame_one_packet() { - let mut io = FramedWrite::new(mock! { - Ok(b"\x00\x00\x00\x09"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(b"\x00\x00\x00\x03"[..].into()), - Ok(b"123"[..].into()), - Ok(b"\x00\x00\x00\x0b"[..].into()), - Ok(b"hello world"[..].into()), - Ok(Flush), - }, LengthDelimitedCodec::new()); + let mut io = FramedWrite::new( + mock! { + Ok(b"\x00\x00\x00\x09"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(b"\x00\x00\x00\x03"[..].into()), + Ok(b"123"[..].into()), + Ok(b"\x00\x00\x00\x0b"[..].into()), + Ok(b"hello world"[..].into()), + Ok(Flush), + }, + LengthDelimitedCodec::new(), + ); assert!(io.start_send(Bytes::from("abcdefghi")).unwrap().is_ready()); assert!(io.start_send(Bytes::from("123")).unwrap().is_ready()); - assert!(io.start_send(Bytes::from("hello world")).unwrap().is_ready()); + assert!(io + .start_send(Bytes::from("hello world")) + .unwrap() + .is_ready()); assert!(io.poll_complete().unwrap().is_ready()); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_single_multi_frame_multi_packet() { - let mut io = FramedWrite::new(mock! { - Ok(b"\x00\x00\x00\x09"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - Ok(b"\x00\x00\x00\x03"[..].into()), - Ok(b"123"[..].into()), - Ok(Flush), - Ok(b"\x00\x00\x00\x0b"[..].into()), - Ok(b"hello world"[..].into()), - Ok(Flush), - }, LengthDelimitedCodec::new()); + let mut io = FramedWrite::new( + mock! { + Ok(b"\x00\x00\x00\x09"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + Ok(b"\x00\x00\x00\x03"[..].into()), + Ok(b"123"[..].into()), + Ok(Flush), + Ok(b"\x00\x00\x00\x0b"[..].into()), + Ok(b"hello world"[..].into()), + Ok(Flush), + }, + LengthDelimitedCodec::new(), + ); assert!(io.start_send(Bytes::from("abcdefghi")).unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); assert!(io.start_send(Bytes::from("123")).unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); - assert!(io.start_send(Bytes::from("hello world")).unwrap().is_ready()); + assert!(io + .start_send(Bytes::from("hello world")) + .unwrap() + .is_ready()); assert!(io.poll_complete().unwrap().is_ready()); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_single_frame_would_block() { - let mut io = FramedWrite::new(mock! { - Err(would_block()), - Ok(b"\x00\x00"[..].into()), - Err(would_block()), - Ok(b"\x00\x09"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - }, LengthDelimitedCodec::new()); + let mut io = FramedWrite::new( + mock! { + Err(would_block()), + Ok(b"\x00\x00"[..].into()), + Err(would_block()), + Ok(b"\x00\x09"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + }, + LengthDelimitedCodec::new(), + ); assert!(io.start_send(Bytes::from("abcdefghi")).unwrap().is_ready()); assert!(!io.poll_complete().unwrap().is_ready()); @@ -412,7 +456,6 @@ fn write_single_frame_little_endian() { assert!(io.get_ref().calls.is_empty()); } - #[test] fn write_single_frame_with_short_length_field() { let mut io = length_delimited::Builder::new() @@ -432,54 +475,63 @@ fn write_single_frame_with_short_length_field() { fn write_max_frame_len() { let mut io = length_delimited::Builder::new() .max_frame_length(5) - .new_write(mock! { }); + .new_write(mock! {}); - assert_eq!(io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_update_max_frame_len_at_rest() { - let mut io = length_delimited::Builder::new() - .new_write(mock! { - Ok(b"\x00\x00\x00\x06"[..].into()), - Ok(b"abcdef"[..].into()), - Ok(Flush), - }); + let mut io = length_delimited::Builder::new().new_write(mock! { + Ok(b"\x00\x00\x00\x06"[..].into()), + Ok(b"abcdef"[..].into()), + Ok(Flush), + }); assert!(io.start_send(Bytes::from("abcdef")).unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); io.encoder_mut().set_max_frame_length(5); - assert_eq!(io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_update_max_frame_len_in_flight() { - let mut io = length_delimited::Builder::new() - .new_write(mock! { - Ok(b"\x00\x00\x00\x06"[..].into()), - Ok(b"ab"[..].into()), - Err(would_block()), - Ok(b"cdef"[..].into()), - Ok(Flush), - }); + let mut io = length_delimited::Builder::new().new_write(mock! { + Ok(b"\x00\x00\x00\x06"[..].into()), + Ok(b"ab"[..].into()), + Err(would_block()), + Ok(b"cdef"[..].into()), + Ok(Flush), + }); assert!(io.start_send(Bytes::from("abcdef")).unwrap().is_ready()); assert!(!io.poll_complete().unwrap().is_ready()); io.encoder_mut().set_max_frame_length(5); assert!(io.poll_complete().unwrap().is_ready()); - assert_eq!(io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send(Bytes::from("abcdef")).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_zero() { - let mut io = length_delimited::Builder::new() - .new_write(mock! { }); + let mut io = length_delimited::Builder::new().new_write(mock! {}); assert!(io.start_send(Bytes::from("abcdef")).unwrap().is_ready()); - assert_eq!(io.poll_complete().unwrap_err().kind(), io::ErrorKind::WriteZero); + assert_eq!( + io.poll_complete().unwrap_err().kind(), + io::ErrorKind::WriteZero + ); assert!(io.get_ref().calls.is_empty()); } @@ -490,9 +542,7 @@ fn encode_overflow() { let mut buf = BytesMut::with_capacity(1024); // Put some data into the buffer without resizing it to hold more. - let some_as = std::iter::repeat(b'a') - .take(1024) - .collect::>(); + let some_as = std::iter::repeat(b'a').take(1024).collect::>(); buf.put_slice(&some_as[..]); // Trying to encode the length header should resize the buffer if it won't fit. @@ -531,8 +581,7 @@ impl io::Read for Mock { } } -impl AsyncRead for Mock { -} +impl AsyncRead for Mock {} impl io::Write for Mock { fn write(&mut self, src: &[u8]) -> io::Result { @@ -551,9 +600,7 @@ impl io::Write for Mock { fn flush(&mut self) -> io::Result<()> { match self.calls.pop_front() { - Some(Ok(Op::Flush)) => { - Ok(()) - } + Some(Ok(Op::Flush)) => Ok(()), Some(Ok(_)) => panic!(), Some(Err(e)) => Err(e), None => Ok(()), diff --git a/tests/line-frames.rs b/tests/line-frames.rs index e36d5a73e..84b860a2a 100644 --- a/tests/line-frames.rs +++ b/tests/line-frames.rs @@ -1,19 +1,19 @@ +extern crate bytes; extern crate env_logger; extern crate futures; extern crate tokio; extern crate tokio_codec; extern crate tokio_io; extern crate tokio_threadpool; -extern crate bytes; use std::io; use std::net::Shutdown; -use bytes::{BytesMut, BufMut}; -use futures::{Future, Stream, Sink}; +use bytes::{BufMut, BytesMut}; +use futures::{Future, Sink, Stream}; use tokio::net::{TcpListener, TcpStream}; -use tokio_codec::{Encoder, Decoder}; -use tokio_io::io::{write_all, read}; +use tokio_codec::{Decoder, Encoder}; +use tokio_io::io::{read, write_all}; use tokio_threadpool::Builder; pub struct LineCodec; @@ -53,20 +53,22 @@ impl Encoder for LineCodec { fn echo() { drop(env_logger::try_init()); - let pool = Builder::new() - .pool_size(1) - .build(); + let pool = Builder::new().pool_size(1).build(); let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); let addr = listener.local_addr().unwrap(); let sender = pool.sender().clone(); let srv = listener.incoming().for_each(move |socket| { let (sink, stream) = LineCodec.framed(socket).split(); - sender.spawn(sink.send_all(stream).map(|_| ()).map_err(|_| ())).unwrap(); + sender + .spawn(sink.send_all(stream).map(|_| ()).map_err(|_| ())) + .unwrap(); Ok(()) }); - pool.sender().spawn(srv.map_err(|e| panic!("srv error: {}", e))).unwrap(); + pool.sender() + .spawn(srv.map_err(|e| panic!("srv error: {}", e))) + .unwrap(); let client = TcpStream::connect(&addr); let client = client.wait().unwrap(); diff --git a/tests/pipe-hup.rs b/tests/pipe-hup.rs index a23ae7f6b..eabdec4c8 100644 --- a/tests/pipe-hup.rs +++ b/tests/pipe-hup.rs @@ -13,18 +13,20 @@ use std::os::unix::io::{AsRawFd, FromRawFd}; use std::thread; use std::time::Duration; +use futures::Future; use mio::event::Evented; -use mio::unix::{UnixReady, EventedFd}; +use mio::unix::{EventedFd, UnixReady}; use mio::{PollOpt, Ready, Token}; use tokio::reactor::{Handle, PollEvented2}; use tokio_io::io::read_to_end; -use futures::Future; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } struct MyFile(File); @@ -46,13 +48,23 @@ impl io::Read for MyFile { } impl Evented for MyFile { - fn register(&self, poll: &mio::Poll, token: Token, interest: Ready, opts: PollOpt) - -> io::Result<()> { + fn register( + &self, + poll: &mio::Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { let hup: Ready = UnixReady::hup().into(); EventedFd(&self.0.as_raw_fd()).register(poll, token, interest | hup, opts) } - fn reregister(&self, poll: &mio::Poll, token: Token, interest: Ready, opts: PollOpt) - -> io::Result<()> { + fn reregister( + &self, + poll: &mio::Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { let hup: Ready = UnixReady::hup().into(); EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest | hup, opts) } @@ -68,8 +80,11 @@ fn hup() { let handle = Handle::default(); unsafe { let mut pipes = [0; 2]; - assert!(libc::pipe(pipes.as_mut_ptr()) != -1, - "pipe error: {}", io::Error::last_os_error()); + assert!( + libc::pipe(pipes.as_mut_ptr()) != -1, + "pipe error: {}", + io::Error::last_os_error() + ); let read = File::from_raw_fd(pipes[0]); let mut write = File::from_raw_fd(pipes[1]); let t = thread::spawn(move || { diff --git a/tests/reactor.rs b/tests/reactor.rs index 1bac13ad4..fd3a8eea6 100644 --- a/tests/reactor.rs +++ b/tests/reactor.rs @@ -6,8 +6,8 @@ extern crate tokio_tcp; use tokio_reactor::Reactor; use tokio_tcp::TcpListener; -use futures::{Future, Stream}; use futures::executor::{spawn, Notify, Spawn}; +use futures::{Future, Stream}; use std::mem; use std::net::TcpStream; @@ -62,7 +62,8 @@ fn test_drop_on_notify() { // Define a task that just drains the listener let task = Box::new({ - listener.incoming() + listener + .incoming() .for_each(|_| Ok(())) .map_err(|_| panic!()) }) as Box>; @@ -75,7 +76,8 @@ fn test_drop_on_notify() { tokio_reactor::with_default(&reactor.handle(), &mut enter, |_| { let id = &*task as *const Task as usize; - task.lock().unwrap() + task.lock() + .unwrap() .poll_future_notify(¬ify, id) .unwrap(); }); diff --git a/tests/runtime.rs b/tests/runtime.rs index ed77dba5b..f84c66738 100644 --- a/tests/runtime.rs +++ b/tests/runtime.rs @@ -1,12 +1,12 @@ -extern crate tokio; extern crate env_logger; extern crate futures; +extern crate tokio; use futures::sync::oneshot; -use std::sync::{Arc, Mutex, atomic}; +use std::sync::{atomic, Arc, Mutex}; use std::thread; use tokio::io; -use tokio::net::{TcpStream, TcpListener}; +use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::future::lazy; use tokio::prelude::*; use tokio::runtime::Runtime; @@ -17,18 +17,22 @@ use tokio::runtime::Runtime; pub use futures::future::Executor; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } -fn create_client_server_future() -> Box + Send> { +fn create_client_server_future() -> Box + Send> { let server = t!(TcpListener::bind(&"127.0.0.1:0".parse().unwrap())); let addr = t!(server.local_addr()); let client = TcpStream::connect(&addr); - let server = server.incoming().take(1) + let server = server + .incoming() + .take(1) .map_err(|e| panic!("accept err = {:?}", e)) .for_each(|socket| { tokio::spawn({ @@ -48,8 +52,7 @@ fn create_client_server_future() -> Box + Send> { .map_err(|e| panic!("read err = {:?}", e)) }); - let future = server.join(client) - .map(|_| ()); + let future = server.join(client).map(|_| ()); Box::new(future) } @@ -64,8 +67,7 @@ fn runtime_tokio_run() { fn runtime_single_threaded() { let _ = env_logger::try_init(); - let mut runtime = tokio::runtime::current_thread::Runtime::new() - .unwrap(); + let mut runtime = tokio::runtime::current_thread::Runtime::new().unwrap(); runtime.block_on(create_client_server_future()).unwrap(); runtime.run().unwrap(); } @@ -82,7 +84,7 @@ mod runtime_single_threaded_block_on_all { fn test(spawn: F) where - F: Fn(Box + Send>), + F: Fn(Box + Send>), { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -103,7 +105,8 @@ mod runtime_single_threaded_block_on_all { }))); Ok::<_, ()>("hello") - })).unwrap(); + })) + .unwrap(); assert_eq!(2, *cnt.lock().unwrap()); assert_eq!(msg, "hello"); @@ -111,7 +114,9 @@ mod runtime_single_threaded_block_on_all { #[test] fn spawn() { - test(|f| { tokio::spawn(f); }) + test(|f| { + tokio::spawn(f); + }) } #[test] @@ -128,10 +133,7 @@ mod runtime_single_threaded_racy { use super::*; fn test(spawn: F) where - F: Fn( - tokio::runtime::current_thread::Handle, - Box + Send>, - ), + F: Fn(tokio::runtime::current_thread::Handle, Box + Send>), { let (trigger, exit) = futures::sync::oneshot::channel(); let (handle_tx, handle_rx) = ::std::sync::mpsc::channel(); @@ -149,10 +151,13 @@ mod runtime_single_threaded_racy { let (tx, rx) = futures::sync::oneshot::channel(); let handle = handle_rx.recv().unwrap(); - spawn(handle, Box::new(futures::future::lazy(move || { - tx.send(()).unwrap(); - Ok(()) - }))); + spawn( + handle, + Box::new(futures::future::lazy(move || { + tx.send(()).unwrap(); + Ok(()) + })), + ); // signal runtime thread to exit trigger.send(()).unwrap(); @@ -165,12 +170,16 @@ mod runtime_single_threaded_racy { #[test] fn spawn() { - test(|handle, f| { handle.spawn(f).unwrap(); }) + test(|handle, f| { + handle.spawn(f).unwrap(); + }) } #[test] fn execute() { - test(|handle, f| { handle.execute(f).unwrap(); }) + test(|handle, f| { + handle.execute(f).unwrap(); + }) } } @@ -182,25 +191,28 @@ mod runtime_multi_threaded { { let _ = env_logger::try_init(); - let mut runtime = tokio::runtime::Builder::new() - .build() - .unwrap(); + let mut runtime = tokio::runtime::Builder::new().build().unwrap(); spawn(&mut runtime); runtime.shutdown_on_idle().wait().unwrap(); } #[test] fn spawn() { - test(|rt| { rt.spawn(create_client_server_future()); }); + test(|rt| { + rt.spawn(create_client_server_future()); + }); } #[test] fn execute() { - test(|rt| { rt.executor().execute(create_client_server_future()).unwrap(); }); + test(|rt| { + rt.executor() + .execute(create_client_server_future()) + .unwrap(); + }); } } - #[test] fn block_on_timer() { use std::time::{Duration, Instant}; @@ -223,7 +235,7 @@ mod from_block_on { fn test(spawn: F) where - F: Fn(Box + Send>) + Send + 'static, + F: Fn(Box + Send>) + Send + 'static, { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -305,20 +317,23 @@ mod many { const ITER: usize = 200; fn test(spawn: F) where - F: Fn(&mut Runtime, Box + Send>), + F: Fn(&mut Runtime, Box + Send>), { let cnt = Arc::new(Mutex::new(0)); let mut runtime = Runtime::new().unwrap(); for _ in 0..ITER { let c = cnt.clone(); - spawn(&mut runtime, Box::new(lazy(move || { - { - let mut x = c.lock().unwrap(); - *x = 1 + *x; - } - Ok::<(), ()>(()) - }))); + spawn( + &mut runtime, + Box::new(lazy(move || { + { + let mut x = c.lock().unwrap(); + *x = 1 + *x; + } + Ok::<(), ()>(()) + })), + ); } runtime.shutdown_on_idle().wait().unwrap(); @@ -327,26 +342,25 @@ mod many { #[test] fn spawn() { - test(|rt, f| { rt.spawn(f); }) + test(|rt, f| { + rt.spawn(f); + }) } #[test] fn execute() { test(|rt, f| { - rt.executor() - .execute(f) - .unwrap(); + rt.executor().execute(f).unwrap(); }) } } - mod from_block_on_all { use super::*; fn test(spawn: F) where - F: Fn(Box + Send>) + Send + 'static, + F: Fn(Box + Send>) + Send + 'static, { let cnt = Arc::new(Mutex::new(0)); let c = cnt.clone(); @@ -387,19 +401,21 @@ mod from_block_on_all { #[test] fn spawn() { - test(|f| { tokio::spawn(f); }) + test(|f| { + tokio::spawn(f); + }) } } mod nested_enter { use super::*; - use tokio::runtime::current_thread; use std::panic; + use tokio::runtime::current_thread; fn test(first: F1, nested: F2) where - F1: Fn(Box + Send>) + Send + 'static, - F2: Fn(Box + Send>) + panic::UnwindSafe + Send + 'static, + F1: Fn(Box + Send>) + Send + 'static, + F2: Fn(Box + Send>) + panic::UnwindSafe + Send + 'static, { let panicked = Arc::new(Mutex::new(false)); let panicked2 = panicked.clone(); @@ -421,16 +437,18 @@ mod nested_enter { })); first(Box::new(lazy(move || { - panic::catch_unwind(move || { - nested(Box::new(lazy(|| { Ok::<(), ()>(()) }))) - }).expect_err("nested should panic"); + panic::catch_unwind(move || nested(Box::new(lazy(|| Ok::<(), ()>(()))))) + .expect_err("nested should panic"); *panicked2.lock().unwrap() = true; Ok::<(), ()>(()) }))); panic::set_hook(prev_hook); - assert!(*panicked.lock().unwrap(), "nested call should have panicked"); + assert!( + *panicked.lock().unwrap(), + "nested call should have panicked" + ); } fn threadpool_new() -> Runtime { @@ -471,10 +489,7 @@ fn runtime_reactor_handle() { #![allow(deprecated)] use futures::Stream; - use std::net::{ - TcpListener as StdListener, - TcpStream as StdStream, - }; + use std::net::{TcpListener as StdListener, TcpStream as StdStream}; let rt = Runtime::new().unwrap(); @@ -484,10 +499,7 @@ fn runtime_reactor_handle() { let addr = tk_listener.local_addr().unwrap(); // Spawn a thread since we are avoiding the runtime - let th = thread::spawn(|| { - for _ in tk_listener.incoming().take(1).wait() { - } - }); + let th = thread::spawn(|| for _ in tk_listener.incoming().take(1).wait() {}); let _ = StdStream::connect(&addr).unwrap(); @@ -504,10 +516,14 @@ fn after_start_and_before_stop_is_called() { let after_inner = after_start.clone(); let before_inner = before_stop.clone(); let runtime = tokio::runtime::Builder::new() - .after_start(move || { after_inner.clone().fetch_add(1, atomic::Ordering::Relaxed); }) - .before_stop(move || { before_inner.clone().fetch_add(1, atomic::Ordering::Relaxed); }) - .build() - .unwrap(); + .after_start(move || { + after_inner.clone().fetch_add(1, atomic::Ordering::Relaxed); + }) + .before_stop(move || { + before_inner.clone().fetch_add(1, atomic::Ordering::Relaxed); + }) + .build() + .unwrap(); runtime.block_on_all(create_client_server_future()).unwrap(); diff --git a/tests/timer.rs b/tests/timer.rs index 72a5595d7..54c3b9d31 100644 --- a/tests/timer.rs +++ b/tests/timer.rs @@ -1,7 +1,7 @@ +extern crate env_logger; extern crate futures; extern crate tokio; extern crate tokio_io; -extern crate env_logger; use tokio::prelude::*; use tokio::timer::*; @@ -31,7 +31,7 @@ fn timer_with_runtime() { #[test] fn starving() { - use futures::{task, Poll, Async}; + use futures::{task, Async, Poll}; let _ = env_logger::try_init(); @@ -60,12 +60,11 @@ fn starving() { let (tx, rx) = mpsc::channel(); tokio::run({ - starve - .and_then(move |_ticks| { - assert!(Instant::now() >= when); - tx.send(()).unwrap(); - Ok(()) - }) + starve.and_then(move |_ticks| { + assert!(Instant::now() >= when); + tx.send(()).unwrap(); + Ok(()) + }) }); rx.recv().unwrap(); @@ -82,13 +81,11 @@ fn deadline() { #[allow(deprecated)] tokio::run({ - future::empty::<(), ()>() - .deadline(when) - .then(move |res| { - assert!(res.is_err()); - tx.send(()).unwrap(); - Ok(()) - }) + future::empty::<(), ()>().deadline(when).then(move |res| { + assert!(res.is_err()); + tx.send(()).unwrap(); + Ok(()) + }) }); rx.recv().unwrap(); diff --git a/tokio-async-await/src/await.rs b/tokio-async-await/src/await.rs index 7cc7f8133..1e8f6e7eb 100644 --- a/tokio-async-await/src/await.rs +++ b/tokio-async-await/src/await.rs @@ -2,15 +2,15 @@ #[macro_export] macro_rules! await { ($e:expr) => {{ - use $crate::std_await; - #[allow(unused_imports)] - use $crate::compat::forward::IntoAwaitable as IntoAwaitableForward; #[allow(unused_imports)] use $crate::compat::backward::IntoAwaitable as IntoAwaitableBackward; + #[allow(unused_imports)] + use $crate::compat::forward::IntoAwaitable as IntoAwaitableForward; + use $crate::std_await; #[allow(unused_mut)] let mut e = $e; let e = e.into_awaitable(); std_await!(e) - }} + }}; } diff --git a/tokio-async-await/src/compat/backward.rs b/tokio-async-await/src/compat/backward.rs index 8c5999b13..fca801821 100644 --- a/tokio-async-await/src/compat/backward.rs +++ b/tokio-async-await/src/compat/backward.rs @@ -1,16 +1,9 @@ use futures::{Future, Poll}; +use std::future::Future as StdFuture; use std::pin::Pin; -use std::future::{ - Future as StdFuture, -}; use std::ptr::NonNull; -use std::task::{ - LocalWaker, - Poll as StdPoll, - UnsafeWake, - Waker, -}; +use std::task::{LocalWaker, Poll as StdPoll, UnsafeWake, Waker}; /// Convert an 0.3 `Future` to an 0.1 `Future`. #[derive(Debug)] @@ -31,7 +24,8 @@ pub trait IntoAwaitable { } impl IntoAwaitable for T -where T: StdFuture, +where + T: StdFuture, { type Awaitable = Self; @@ -41,7 +35,8 @@ where T: StdFuture, } impl Future for Compat -where T: StdFuture>, +where + T: StdFuture>, { type Item = Item; type Error = Error; @@ -80,8 +75,7 @@ unsafe impl UnsafeWake for NoopWaker { noop_waker() } - unsafe fn drop_raw(&self) { - } + unsafe fn drop_raw(&self) {} unsafe fn wake(&self) { unimplemented!("async-await-preview currently only supports futures 0.1. Use the compatibility layer of futures 0.3 instead, if you want to use futures 0.3."); diff --git a/tokio-async-await/src/compat/forward.rs b/tokio-async-await/src/compat/forward.rs index 65b1351b9..bd99ed236 100644 --- a/tokio-async-await/src/compat/forward.rs +++ b/tokio-async-await/src/compat/forward.rs @@ -1,8 +1,7 @@ +use futures::{Async, Future}; -use futures::{Future, Async}; - -use std::marker::Unpin; use std::future::Future as StdFuture; +use std::marker::Unpin; use std::pin::Pin; use std::task::{LocalWaker, Poll as StdPoll}; @@ -11,7 +10,7 @@ use std::task::{LocalWaker, Poll as StdPoll}; pub struct Compat(T); pub(crate) fn convert_poll(poll: Result, E>) -> StdPoll> { - use futures::Async::{Ready, NotReady}; + use futures::Async::{NotReady, Ready}; match poll { Ok(Ready(val)) => StdPoll::Ready(Ok(val)), @@ -21,9 +20,9 @@ pub(crate) fn convert_poll(poll: Result, E>) -> StdPoll( - poll: Result>, E>) -> StdPoll>> -{ - use futures::Async::{Ready, NotReady}; + poll: Result>, E>, +) -> StdPoll>> { + use futures::Async::{NotReady, Ready}; match poll { Ok(Ready(Some(val))) => StdPoll::Ready(Some(Ok(val))), @@ -50,12 +49,13 @@ impl IntoAwaitable for T { } impl StdFuture for Compat -where T: Future + Unpin +where + T: Future + Unpin, { type Output = Result; fn poll(mut self: Pin<&mut Self>, _lw: &LocalWaker) -> StdPoll { - use futures::Async::{Ready, NotReady}; + use futures::Async::{NotReady, Ready}; // TODO: wire in cx diff --git a/tokio-async-await/src/compat/mod.rs b/tokio-async-await/src/compat/mod.rs index 6672f07a1..c80e346ca 100644 --- a/tokio-async-await/src/compat/mod.rs +++ b/tokio-async-await/src/compat/mod.rs @@ -1,4 +1,4 @@ #![doc(hidden)] -pub mod forward; pub mod backward; +pub mod forward; diff --git a/tokio-async-await/src/io/flush.rs b/tokio-async-await/src/io/flush.rs index db0dbb05b..9443d152b 100644 --- a/tokio-async-await/src/io/flush.rs +++ b/tokio-async-await/src/io/flush.rs @@ -1,8 +1,7 @@ use tokio_io::AsyncWrite; - -use std::io; use std::future::Future; +use std::io; use std::marker::Unpin; use std::pin::Pin; use std::task::{LocalWaker, Poll}; diff --git a/tokio-async-await/src/io/read.rs b/tokio-async-await/src/io/read.rs index 909a4d60b..0886aef62 100644 --- a/tokio-async-await/src/io/read.rs +++ b/tokio-async-await/src/io/read.rs @@ -19,10 +19,7 @@ impl<'a, T: ?Sized> Unpin for Read<'a, T> {} impl<'a, T: AsyncRead + ?Sized> Read<'a, T> { pub(super) fn new(reader: &'a mut T, buf: &'a mut [u8]) -> Read<'a, T> { - Read { - reader, - buf, - } + Read { reader, buf } } } diff --git a/tokio-async-await/src/io/read_exact.rs b/tokio-async-await/src/io/read_exact.rs index ca9cd4d09..7b1ec1e9b 100644 --- a/tokio-async-await/src/io/read_exact.rs +++ b/tokio-async-await/src/io/read_exact.rs @@ -20,10 +20,7 @@ impl<'a, T: ?Sized> Unpin for ReadExact<'a, T> {} impl<'a, T: AsyncRead + ?Sized> ReadExact<'a, T> { pub(super) fn new(reader: &'a mut T, buf: &'a mut [u8]) -> ReadExact<'a, T> { - ReadExact { - reader, - buf, - } + ReadExact { reader, buf } } } @@ -47,7 +44,7 @@ impl<'a, T: AsyncRead + ?Sized> Future for ReadExact<'a, T> { this.buf = rest; } if n == 0 { - return Poll::Ready(Err(eof())) + return Poll::Ready(Err(eof())); } } diff --git a/tokio-async-await/src/io/write.rs b/tokio-async-await/src/io/write.rs index 4e5dd354d..af6f7adfa 100644 --- a/tokio-async-await/src/io/write.rs +++ b/tokio-async-await/src/io/write.rs @@ -19,10 +19,7 @@ impl<'a, T: ?Sized> Unpin for Write<'a, T> {} impl<'a, T: AsyncWrite + ?Sized> Write<'a, T> { pub(super) fn new(writer: &'a mut T, buf: &'a [u8]) -> Write<'a, T> { - Write { - writer, - buf, - } + Write { writer, buf } } } diff --git a/tokio-async-await/src/io/write_all.rs b/tokio-async-await/src/io/write_all.rs index cfc3e7ef0..fcc72b567 100644 --- a/tokio-async-await/src/io/write_all.rs +++ b/tokio-async-await/src/io/write_all.rs @@ -20,10 +20,7 @@ impl<'a, T: ?Sized> Unpin for WriteAll<'a, T> {} impl<'a, T: AsyncWrite + ?Sized> WriteAll<'a, T> { pub(super) fn new(writer: &'a mut T, buf: &'a [u8]) -> WriteAll<'a, T> { - WriteAll { - writer, - buf, - } + WriteAll { writer, buf } } } @@ -48,7 +45,7 @@ impl<'a, T: AsyncWrite + ?Sized> Future for WriteAll<'a, T> { } if n == 0 { - return Poll::Ready(Err(zero_write())) + return Poll::Ready(Err(zero_write())); } } diff --git a/tokio-async-await/src/lib.rs b/tokio-async-await/src/lib.rs index dea3a0455..38a335c64 100644 --- a/tokio-async-await/src/lib.rs +++ b/tokio-async-await/src/lib.rs @@ -4,9 +4,8 @@ arbitrary_self_types, async_await, await_macro, - futures_api, - )] - + futures_api +)] #![doc(html_root_url = "https://docs.rs/tokio-async-await/0.1.5")] #![deny(missing_docs, missing_debug_implementations)] #![cfg_attr(test, deny(warnings))] @@ -23,12 +22,10 @@ macro_rules! try_ready { ($x:expr) => { match $x { std::task::Poll::Ready(Ok(x)) => x, - std::task::Poll::Ready(Err(e)) => - return std::task::Poll::Ready(Err(e.into())), - std::task::Poll::Pending => - return std::task::Poll::Pending, + std::task::Poll::Ready(Err(e)) => return std::task::Poll::Ready(Err(e.into())), + std::task::Poll::Pending => return std::task::Poll::Pending, } - } + }; } #[macro_use] diff --git a/tokio-async-await/src/sink/send.rs b/tokio-async-await/src/sink/send.rs index f643ffc6c..b86f1a54b 100644 --- a/tokio-async-await/src/sink/send.rs +++ b/tokio-async-await/src/sink/send.rs @@ -30,7 +30,7 @@ impl Future for Send<'_, T> { fn poll(mut self: Pin<&mut Self>, _lw: &task::LocalWaker) -> Poll { use crate::compat::forward::convert_poll; - use futures::AsyncSink::{Ready, NotReady}; + use futures::AsyncSink::{NotReady, Ready}; if let Some(item) = self.item.take() { match self.sink.start_send(item) { diff --git a/tokio-buf/src/ext/collect.rs b/tokio-buf/src/ext/collect.rs index 95da54528..d4bc57e6c 100644 --- a/tokio-buf/src/ext/collect.rs +++ b/tokio-buf/src/ext/collect.rs @@ -1,5 +1,5 @@ -use BufStream; use super::FromBufStream; +use BufStream; use futures::{Future, Poll}; @@ -53,29 +53,26 @@ where fn poll(&mut self) -> Poll { loop { - let res = self.stream.poll_buf() - .map_err(|err| { - let inner = Error::Stream(err); - CollectError { inner } - }); + let res = self.stream.poll_buf().map_err(|err| { + let inner = Error::Stream(err); + CollectError { inner } + }); match try_ready!(res) { Some(mut buf) => { let builder = self.builder.as_mut().expect("cannot poll after done"); - U::extend(builder, &mut buf, &self.stream.size_hint()) - .map_err(|err| { - let inner = Error::Collect(err); - CollectError { inner } - })?; + U::extend(builder, &mut buf, &self.stream.size_hint()).map_err(|err| { + let inner = Error::Collect(err); + CollectError { inner } + })?; } None => { let builder = self.builder.take().expect("cannot poll after done"); - let value = U::build(builder) - .map_err(|err| { - let inner = Error::Collect(err); - CollectError { inner } - })?; + let value = U::build(builder).map_err(|err| { + let inner = Error::Collect(err); + CollectError { inner } + })?; return Ok(value.into()); } } diff --git a/tokio-buf/src/ext/from.rs b/tokio-buf/src/ext/from.rs index c15057a4d..b94ebc2d8 100644 --- a/tokio-buf/src/ext/from.rs +++ b/tokio-buf/src/ext/from.rs @@ -43,7 +43,9 @@ pub trait FromBufStream: Sized { /// Error returned from collecting into a `Vec` #[derive(Debug)] -pub struct CollectVecError { _p: () } +pub struct CollectVecError { + _p: (), +} impl FromBufStream for Vec { type Builder = Vec; @@ -70,7 +72,7 @@ impl FromBufStream for Vec { Some(upper) if upper <= 64 => { reserve = upper as usize; } - _ => {}, + _ => {} } // hint.lower() represents the minimum amount of data that will be diff --git a/tokio-buf/src/ext/limit.rs b/tokio-buf/src/ext/limit.rs index 1d3e0ba3a..c89e687ad 100644 --- a/tokio-buf/src/ext/limit.rs +++ b/tokio-buf/src/ext/limit.rs @@ -40,10 +40,10 @@ where return Err(LimitError { inner: None }); } - let res = self.stream.poll_buf() - .map_err(|err| { - LimitError { inner: Some(err) } - }); + let res = self + .stream + .poll_buf() + .map_err(|err| LimitError { inner: Some(err) }); match res { Ok(Ready(Some(ref buf))) => { diff --git a/tokio-buf/src/lib.rs b/tokio-buf/src/lib.rs index d816f5509..b5da17b1f 100644 --- a/tokio-buf/src/lib.rs +++ b/tokio-buf/src/lib.rs @@ -16,21 +16,21 @@ extern crate either; #[macro_use] extern crate futures; +pub mod errors; #[cfg(feature = "ext")] pub mod ext; -pub mod errors; mod size_hint; mod str; +pub use self::size_hint::SizeHint; #[doc(inline)] #[cfg(feature = "ext")] pub use ext::BufStreamExt; -pub use self::size_hint::SizeHint; -use futures::Poll; use bytes::{Buf, Bytes, BytesMut}; -use std::io; use errors::internal::Never; +use futures::Poll; +use std::io; /// An asynchronous stream of bytes. /// @@ -151,9 +151,7 @@ impl BufStream for BytesMut { } } -fn poll_bytes(buf: &mut T) - -> Poll>, Never> -{ +fn poll_bytes(buf: &mut T) -> Poll>, Never> { use std::mem; let bytes = mem::replace(buf, Default::default()); diff --git a/tokio-buf/src/str.rs b/tokio-buf/src/str.rs index b18080809..4b73ad005 100644 --- a/tokio-buf/src/str.rs +++ b/tokio-buf/src/str.rs @@ -1,5 +1,5 @@ -use BufStream; use errors::internal::Never; +use BufStream; use futures::Poll; diff --git a/tokio-buf/tests/buf_stream.rs b/tokio-buf/tests/buf_stream.rs index 848a5de1e..c116dac02 100644 --- a/tokio-buf/tests/buf_stream.rs +++ b/tokio-buf/tests/buf_stream.rs @@ -1,11 +1,10 @@ -extern crate tokio_buf; extern crate bytes; extern crate futures; +extern crate tokio_buf; -use tokio_buf::{BufStream, SizeHint}; use bytes::Buf; use futures::Async::*; - +use tokio_buf::{BufStream, SizeHint}; #[macro_use] mod support; diff --git a/tokio-buf/tests/buf_stream_ext.rs b/tokio-buf/tests/buf_stream_ext.rs index 2395d20e7..92658ee1a 100644 --- a/tokio-buf/tests/buf_stream_ext.rs +++ b/tokio-buf/tests/buf_stream_ext.rs @@ -1,13 +1,13 @@ #![cfg(feature = "ext")] -extern crate tokio_buf; extern crate bytes; extern crate futures; +extern crate tokio_buf; -use tokio_buf::{BufStream, BufStreamExt}; -use futures::Future; -use futures::Async::*; use bytes::Buf; +use futures::Async::*; +use futures::Future; +use tokio_buf::{BufStream, BufStreamExt}; #[macro_use] mod support; @@ -27,8 +27,7 @@ fn chain() { assert_none!(bs.poll_buf()); // Chain multi with multi - let mut bs = list(&["foo", "bar"]) - .chain(list(&["baz", "bok"])); + let mut bs = list(&["foo", "bar"]).chain(list(&["baz", "bok"])); assert_buf_eq!(bs.poll_buf(), "foo"); assert_buf_eq!(bs.poll_buf(), "bar"); @@ -38,11 +37,7 @@ fn chain() { // Chain includes a not ready call // - let mut bs = new_mock(&[ - Ok(Ready("foo")), - Ok(NotReady), - Ok(Ready("bar")) - ]).chain(one("baz")); + let mut bs = new_mock(&[Ok(Ready("foo")), Ok(NotReady), Ok(Ready("bar"))]).chain(one("baz")); assert_buf_eq!(bs.poll_buf(), "foo"); assert_not_ready!(bs.poll_buf()); @@ -62,8 +57,7 @@ fn collect_vec() { // let bs = one("hello world"); - let vec: Vec = bs.collect() - .wait().unwrap(); + let vec: Vec = bs.collect().wait().unwrap(); assert_eq!(vec, b"hello world"); assert_eq!(vec.capacity(), 64); @@ -73,8 +67,7 @@ fn collect_vec() { let mut bs = one("hello world"); bs.size_hint.set_lower(11); - let vec: Vec = bs.collect() - .wait().unwrap(); + let vec: Vec = bs.collect().wait().unwrap(); assert_eq!(vec, b"hello world"); assert_eq!(vec.capacity(), 64); @@ -84,8 +77,7 @@ fn collect_vec() { let mut bs = one("hello world"); bs.size_hint.set_lower(10); - let vec: Vec = bs.collect() - .wait().unwrap(); + let vec: Vec = bs.collect().wait().unwrap(); assert_eq!(vec, b"hello world"); assert_eq!(vec.capacity(), 64); @@ -94,8 +86,7 @@ fn collect_vec() { // let bs = list(&["hello", " ", "world", ", one two three"]); - let vec: Vec = bs.collect() - .wait().unwrap(); + let vec: Vec = bs.collect().wait().unwrap(); assert_eq!(vec, b"hello world, one two three"); } @@ -109,42 +100,38 @@ fn limit() { let res = one("hello world") .limit(100) .collect::>() - .wait().unwrap(); + .wait() + .unwrap(); assert_eq!(res, b"hello world"); let res = list(&["hello", " ", "world"]) .limit(100) .collect::>() - .wait().unwrap(); + .wait() + .unwrap(); assert_eq!(res, b"hello world"); let res = list(&["hello", " ", "world"]) .limit(11) .collect::>() - .wait().unwrap(); + .wait() + .unwrap(); assert_eq!(res, b"hello world"); // Limited - let res = one("hello world") - .limit(5) - .collect::>() - .wait(); + let res = one("hello world").limit(5).collect::>().wait(); assert!(res.is_err()); - let res = one("hello world") - .limit(10) - .collect::>() - .wait(); + let res = one("hello world").limit(10).collect::>().wait(); assert!(res.is_err()); - let mut bs = list(&["hello", " ", "world"]) - .limit(9); + let mut bs = list(&["hello", " ", "world"]).limit(9); assert_buf_eq!(bs.poll_buf(), "hello"); assert_buf_eq!(bs.poll_buf(), " "); diff --git a/tokio-buf/tests/support.rs b/tokio-buf/tests/support.rs index 7e7d1b4b1..61fb09494 100644 --- a/tokio-buf/tests/support.rs +++ b/tokio-buf/tests/support.rs @@ -1,13 +1,13 @@ #![allow(unused)] -extern crate tokio_buf; extern crate bytes; extern crate futures; +extern crate tokio_buf; -use tokio_buf::{BufStream, SizeHint}; use bytes::Buf; -use futures::Poll; use futures::Async::*; +use futures::Poll; +use tokio_buf::{BufStream, SizeHint}; use std::collections::VecDeque; use std::io::Cursor; @@ -32,7 +32,7 @@ macro_rules! assert_none { Ok(Ready(None)) => {} actual => panic!("expected None; actual = {:?}", actual), } - } + }; } macro_rules! assert_not_ready { @@ -41,7 +41,7 @@ macro_rules! assert_not_ready { Ok(NotReady) => {} actual => panic!("expected NotReady; actual = {:?}", actual), } - } + }; } // ===== Test utils ===== @@ -130,4 +130,3 @@ impl Buf for MockBuf { self.data.advance(cnt) } } - diff --git a/tokio-codec/src/bytes_codec.rs b/tokio-codec/src/bytes_codec.rs index d535aef68..3d6e979d9 100644 --- a/tokio-codec/src/bytes_codec.rs +++ b/tokio-codec/src/bytes_codec.rs @@ -1,6 +1,6 @@ -use bytes::{Bytes, BufMut, BytesMut}; -use tokio_io::_tokio_codec::{Encoder, Decoder}; +use bytes::{BufMut, Bytes, BytesMut}; use std::io; +use tokio_io::_tokio_codec::{Decoder, Encoder}; /// A simple `Codec` implementation that just ships bytes around. #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] @@ -8,7 +8,9 @@ pub struct BytesCodec(()); impl BytesCodec { /// Creates a new `BytesCodec` for shipping around raw bytes. - pub fn new() -> BytesCodec { BytesCodec(()) } + pub fn new() -> BytesCodec { + BytesCodec(()) + } } impl Decoder for BytesCodec { diff --git a/tokio-codec/src/lib.rs b/tokio-codec/src/lib.rs index de2920965..a5ed45d06 100644 --- a/tokio-codec/src/lib.rs +++ b/tokio-codec/src/lib.rs @@ -19,14 +19,7 @@ extern crate tokio_io; mod bytes_codec; mod lines_codec; -pub use tokio_io::_tokio_codec::{ - Decoder, - Encoder, - Framed, - FramedParts, - FramedRead, - FramedWrite, -}; +pub use tokio_io::_tokio_codec::{Decoder, Encoder, Framed, FramedParts, FramedRead, FramedWrite}; pub use bytes_codec::BytesCodec; pub use lines_codec::LinesCodec; diff --git a/tokio-codec/src/lines_codec.rs b/tokio-codec/src/lines_codec.rs index 8982ff5a9..9422d312f 100644 --- a/tokio-codec/src/lines_codec.rs +++ b/tokio-codec/src/lines_codec.rs @@ -1,6 +1,6 @@ use bytes::{BufMut, BytesMut}; -use tokio_io::_tokio_codec::{Encoder, Decoder}; use std::{cmp, io, str, usize}; +use tokio_io::_tokio_codec::{Decoder, Encoder}; /// A simple `Codec` implementation that splits up data into lines. #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] @@ -103,10 +103,8 @@ impl LinesCodec { } fn utf8(buf: &[u8]) -> Result<&str, io::Error> { - str::from_utf8(buf).map_err(|_| - io::Error::new( - io::ErrorKind::InvalidData, - "Unable to decode input as UTF8")) + str::from_utf8(buf) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Unable to decode input as UTF8")) } fn without_carriage_return(s: &[u8]) -> &[u8] { @@ -153,7 +151,7 @@ impl Decoder for LinesCodec { self.is_discarding = true; Err(io::Error::new( io::ErrorKind::Other, - "line length limit exceeded" + "line length limit exceeded", )) } else { // We didn't find a line or reach the length limit, so the next diff --git a/tokio-codec/tests/codecs.rs b/tokio-codec/tests/codecs.rs index f43f1ce28..0ab5256f8 100644 --- a/tokio-codec/tests/codecs.rs +++ b/tokio-codec/tests/codecs.rs @@ -1,8 +1,8 @@ -extern crate tokio_codec; extern crate bytes; +extern crate tokio_codec; -use bytes::{BytesMut, Bytes, BufMut}; -use tokio_codec::{BytesCodec, LinesCodec, Decoder, Encoder}; +use bytes::{BufMut, Bytes, BytesMut}; +use tokio_codec::{BytesCodec, Decoder, Encoder, LinesCodec}; #[test] fn bytes_decoder() { @@ -27,13 +27,17 @@ fn bytes_encoder() { const INLINE_CAP: usize = 4 * 4 - 1; let mut buf = BytesMut::new(); - codec.encode(Bytes::from_static(&[0; INLINE_CAP + 1]), &mut buf).unwrap(); + codec + .encode(Bytes::from_static(&[0; INLINE_CAP + 1]), &mut buf) + .unwrap(); // Default capacity of Framed Read const INITIAL_CAPACITY: usize = 8 * 1024; let mut buf = BytesMut::with_capacity(INITIAL_CAPACITY); - codec.encode(Bytes::from_static(&[0; INITIAL_CAPACITY + 1]), &mut buf).unwrap(); + codec + .encode(Bytes::from_static(&[0; INITIAL_CAPACITY + 1]), &mut buf) + .unwrap(); } #[test] @@ -68,17 +72,32 @@ fn lines_decoder_max_length() { assert!(codec.decode(buf).is_err()); let line = codec.decode(buf).unwrap().unwrap(); - assert!(line.len() <= MAX_LENGTH, "{:?}.len() <= {:?}", line, MAX_LENGTH); + assert!( + line.len() <= MAX_LENGTH, + "{:?}.len() <= {:?}", + line, + MAX_LENGTH + ); assert_eq!("line 2", line); assert!(codec.decode(buf).is_err()); let line = codec.decode(buf).unwrap().unwrap(); - assert!(line.len() <= MAX_LENGTH, "{:?}.len() <= {:?}", line, MAX_LENGTH); + assert!( + line.len() <= MAX_LENGTH, + "{:?}.len() <= {:?}", + line, + MAX_LENGTH + ); assert_eq!("line 4", line); let line = codec.decode(buf).unwrap().unwrap(); - assert!(line.len() <= MAX_LENGTH, "{:?}.len() <= {:?}", line, MAX_LENGTH); + assert!( + line.len() <= MAX_LENGTH, + "{:?}.len() <= {:?}", + line, + MAX_LENGTH + ); assert_eq!("", line); assert_eq!(None, codec.decode(buf).unwrap()); @@ -87,7 +106,12 @@ fn lines_decoder_max_length() { assert_eq!(None, codec.decode(buf).unwrap()); let line = codec.decode_eof(buf).unwrap().unwrap(); - assert!(line.len() <= MAX_LENGTH, "{:?}.len() <= {:?}", line, MAX_LENGTH); + assert!( + line.len() <= MAX_LENGTH, + "{:?}.len() <= {:?}", + line, + MAX_LENGTH + ); assert_eq!("\rk", line); assert_eq!(None, codec.decode(buf).unwrap()); diff --git a/tokio-codec/tests/framed.rs b/tokio-codec/tests/framed.rs index f7dd9cdf7..53aafcbc3 100644 --- a/tokio-codec/tests/framed.rs +++ b/tokio-codec/tests/framed.rs @@ -1,13 +1,13 @@ -extern crate tokio_codec; -extern crate tokio_io; extern crate bytes; extern crate futures; +extern crate tokio_codec; +extern crate tokio_io; -use futures::{Stream, Future}; +use bytes::{Buf, BufMut, BytesMut, IntoBuf}; +use futures::{Future, Stream}; use std::io::{self, Read}; -use tokio_codec::{Framed, FramedParts, Decoder, Encoder}; +use tokio_codec::{Decoder, Encoder, Framed, FramedParts}; use tokio_io::AsyncRead; -use bytes::{BytesMut, Buf, BufMut, IntoBuf}; const INITIAL_CAPACITY: usize = 8 * 1024; @@ -45,8 +45,10 @@ struct DontReadIntoThis; impl Read for DontReadIntoThis { fn read(&mut self, _: &mut [u8]) -> io::Result { - Err(io::Error::new(io::ErrorKind::Other, - "Read into something you weren't supposed to.")) + Err(io::Error::new( + io::ErrorKind::Other, + "Read into something you weren't supposed to.", + )) } } @@ -61,9 +63,7 @@ fn can_read_from_existing_buf() { let num = framed .into_future() - .map(|(first_num, _)| { - first_num.unwrap() - }) + .map(|(first_num, _)| first_num.unwrap()) .wait() .map_err(|e| e.0) .unwrap(); diff --git a/tokio-codec/tests/framed_read.rs b/tokio-codec/tests/framed_read.rs index 805229a0e..53ec20388 100644 --- a/tokio-codec/tests/framed_read.rs +++ b/tokio-codec/tests/framed_read.rs @@ -1,17 +1,17 @@ -extern crate tokio_codec; -extern crate tokio_io; extern crate bytes; extern crate futures; +extern crate tokio_codec; +extern crate tokio_io; +use tokio_codec::{Decoder, FramedRead}; use tokio_io::AsyncRead; -use tokio_codec::{FramedRead, Decoder}; -use bytes::{BytesMut, Buf, IntoBuf}; +use bytes::{Buf, BytesMut, IntoBuf}; +use futures::Async::{NotReady, Ready}; use futures::Stream; -use futures::Async::{Ready, NotReady}; -use std::io::{self, Read}; use std::collections::VecDeque; +use std::io::{self, Read}; macro_rules! mock { ($($x:expr,)*) => {{ @@ -212,5 +212,4 @@ impl Read for Mock { } } -impl AsyncRead for Mock { -} +impl AsyncRead for Mock {} diff --git a/tokio-codec/tests/framed_write.rs b/tokio-codec/tests/framed_write.rs index 7b3b4bd57..9ce392c68 100644 --- a/tokio-codec/tests/framed_write.rs +++ b/tokio-codec/tests/framed_write.rs @@ -1,16 +1,16 @@ -extern crate tokio_codec; -extern crate tokio_io; extern crate bytes; extern crate futures; +extern crate tokio_codec; +extern crate tokio_io; -use tokio_io::AsyncWrite; use tokio_codec::{Encoder, FramedWrite}; +use tokio_io::AsyncWrite; -use futures::{Sink, Poll}; -use bytes::{BytesMut, BufMut}; +use bytes::{BufMut, BytesMut}; +use futures::{Poll, Sink}; -use std::io::{self, Write}; use std::collections::VecDeque; +use std::io::{self, Write}; macro_rules! mock { ($($x:expr,)*) => {{ diff --git a/tokio-current-thread/src/lib.rs b/tokio-current-thread/src/lib.rs index 948327387..0e7545ffc 100644 --- a/tokio-current-thread/src/lib.rs +++ b/tokio-current-thread/src/lib.rs @@ -32,19 +32,19 @@ mod scheduler; use self::scheduler::Scheduler; +use tokio_executor::park::{Park, ParkThread, Unpark}; use tokio_executor::{Enter, SpawnError}; -use tokio_executor::park::{Park, Unpark, ParkThread}; +use futures::future::{ExecuteError, ExecuteErrorKind, Executor}; use futures::{executor, Async, Future}; -use futures::future::{Executor, ExecuteError, ExecuteErrorKind}; -use std::fmt; use std::cell::Cell; use std::error::Error; +use std::fmt; use std::rc::Rc; use std::sync::{atomic, mpsc, Arc}; -use std::time::{Duration, Instant}; use std::thread; +use std::time::{Duration, Instant}; /// Executes tasks on the current thread pub struct CurrentThread { @@ -86,7 +86,7 @@ pub struct TaskExecutor { /// Returned by the `turn` function. #[derive(Debug)] pub struct Turn { - polled: bool + polled: bool, } impl Turn { @@ -194,7 +194,7 @@ struct CurrentRunner { id: Cell>, } -thread_local!{ +thread_local! { /// Current thread's task runner. This is set in `TaskRunner::with` static CURRENT: CurrentRunner = CurrentRunner { spawn: Cell::new(None), @@ -202,7 +202,7 @@ thread_local!{ } } -thread_local!{ +thread_local! { /// Unique ID to assign to each new executor launched on this thread. /// /// The unique ID is used to determine if the currently running executor matches the one @@ -226,7 +226,8 @@ thread_local!{ /// [`CurrentThread`]: struct.CurrentThread.html /// [mod]: index.html pub fn block_on_all(future: F) -> Result -where F: Future, +where + F: Future, { let mut current_thread = CurrentThread::new(); @@ -250,7 +251,8 @@ where F: Future, /// /// [`tokio::spawn`]: ../fn.spawn.html pub fn spawn(future: F) -where F: Future + 'static +where + F: Future + 'static, { TaskExecutor::current() .spawn_local(Box::new(future)) @@ -316,7 +318,8 @@ impl CurrentThread

{ /// /// This internally queues the future to be executed once `run` is called. pub fn spawn(&mut self, future: F) -> &mut Self - where F: Future + 'static, + where + F: Future + 'static, { self.borrow().spawn_local(Box::new(future), false); self @@ -335,41 +338,33 @@ impl CurrentThread

{ /// /// The caller is responsible for ensuring that other spawned futures /// complete execution. - pub fn block_on(&mut self, future: F) - -> Result> - where F: Future + pub fn block_on(&mut self, future: F) -> Result> + where + F: Future, { - let mut enter = tokio_executor::enter() - .expect("failed to start `current_thread::Runtime`"); + let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`"); self.enter(&mut enter).block_on(future) } /// Run the executor to completion, blocking the thread until **all** /// spawned futures have completed. pub fn run(&mut self) -> Result<(), RunError> { - let mut enter = tokio_executor::enter() - .expect("failed to start `current_thread::Runtime`"); + let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`"); self.enter(&mut enter).run() } /// Run the executor to completion, blocking the thread until all /// spawned futures have completed **or** `duration` time has elapsed. - pub fn run_timeout(&mut self, duration: Duration) - -> Result<(), RunTimeoutError> - { - let mut enter = tokio_executor::enter() - .expect("failed to start `current_thread::Runtime`"); + pub fn run_timeout(&mut self, duration: Duration) -> Result<(), RunTimeoutError> { + let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`"); self.enter(&mut enter).run_timeout(duration) } /// Perform a single iteration of the event loop. /// /// This function blocks the current thread even if the executor is idle. - pub fn turn(&mut self, duration: Option) - -> Result - { - let mut enter = tokio_executor::enter() - .expect("failed to start `current_thread::Runtime`"); + pub fn turn(&mut self, duration: Option) -> Result { + let mut enter = tokio_executor::enter().expect("failed to start `current_thread::Runtime`"); self.enter(&mut enter).turn(duration) } @@ -440,7 +435,10 @@ impl fmt::Debug for CurrentThread

{ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("CurrentThread") .field("scheduler", &self.scheduler) - .field("num_futures", &self.num_futures.load(atomic::Ordering::SeqCst)) + .field( + "num_futures", + &self.num_futures.load(atomic::Ordering::SeqCst), + ) .finish() } } @@ -452,7 +450,8 @@ impl<'a, P: Park> Entered<'a, P> { /// /// This internally queues the future to be executed once `run` is called. pub fn spawn(&mut self, future: F) -> &mut Self - where F: Future + 'static, + where + F: Future + 'static, { self.executor.borrow().spawn_local(Box::new(future), false); self @@ -471,17 +470,18 @@ impl<'a, P: Park> Entered<'a, P> { /// /// The caller is responsible for ensuring that other spawned futures /// complete execution. - pub fn block_on(&mut self, future: F) - -> Result> - where F: Future + pub fn block_on(&mut self, future: F) -> Result> + where + F: Future, { let mut future = executor::spawn(future); let notify = self.executor.scheduler.notify(); loop { - let res = self.executor.borrow().enter(self.enter, || { - future.poll_future_notify(¬ify, 0) - }); + let res = self + .executor + .borrow() + .enter(self.enter, || future.poll_future_notify(¬ify, 0)); match res { Ok(Async::Ready(e)) => return Ok(e), @@ -500,24 +500,19 @@ impl<'a, P: Park> Entered<'a, P> { /// Run the executor to completion, blocking the thread until **all** /// spawned futures have completed. pub fn run(&mut self) -> Result<(), RunError> { - self.run_timeout2(None) - .map_err(|_| RunError { _p: () }) + self.run_timeout2(None).map_err(|_| RunError { _p: () }) } /// Run the executor to completion, blocking the thread until all /// spawned futures have completed **or** `duration` time has elapsed. - pub fn run_timeout(&mut self, duration: Duration) - -> Result<(), RunTimeoutError> - { + pub fn run_timeout(&mut self, duration: Duration) -> Result<(), RunTimeoutError> { self.run_timeout2(Some(duration)) } /// Perform a single iteration of the event loop. /// /// This function blocks the current thread even if the executor is idle. - pub fn turn(&mut self, duration: Option) - -> Result - { + pub fn turn(&mut self, duration: Option) -> Result { let res = if self.executor.scheduler.has_pending_futures() { self.executor.park.park_timeout(Duration::from_millis(0)) } else { @@ -546,9 +541,7 @@ impl<'a, P: Park> Entered<'a, P> { &mut self.executor.park } - fn run_timeout2(&mut self, dur: Option) - -> Result<(), RunTimeoutError> - { + fn run_timeout2(&mut self, dur: Option) -> Result<(), RunTimeoutError> { if self.executor.is_idle() { // Nothing to do return Ok(()); @@ -606,10 +599,9 @@ impl<'a, P: Park> Entered<'a, P> { } // After any pending futures were scheduled, do the actual tick - borrow.scheduler.tick( - borrow.id, - &mut *self.enter, - borrow.num_futures) + borrow + .scheduler + .tick(borrow.id, &mut *self.enter, borrow.num_futures) } } @@ -680,7 +672,8 @@ impl Handle { return Err(SpawnError::shutdown()); } - self.sender.send(Box::new(future)) + self.sender + .send(Box::new(future)) .expect("CurrentThread does not exist anymore"); // use 0 for the id, CurrentThread does not make use of it self.notify.notify(0); @@ -722,51 +715,44 @@ impl TaskExecutor { /// Get the current executor's thread-local ID. fn id(&self) -> Option { - CURRENT.with(|current| { - current.id.get() - }) + CURRENT.with(|current| current.id.get()) } /// Spawn a future onto the current `CurrentThread` instance. - pub fn spawn_local(&mut self, future: Box>) - -> Result<(), SpawnError> - { - CURRENT.with(|current| { - match current.spawn.get() { - Some(spawn) => { - unsafe { (*spawn).spawn_local(future, false) }; - Ok(()) - } - None => { - Err(SpawnError::shutdown()) - } + pub fn spawn_local( + &mut self, + future: Box>, + ) -> Result<(), SpawnError> { + CURRENT.with(|current| match current.spawn.get() { + Some(spawn) => { + unsafe { (*spawn).spawn_local(future, false) }; + Ok(()) } + None => Err(SpawnError::shutdown()), }) } } impl tokio_executor::Executor for TaskExecutor { - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError> - { + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError> { self.spawn_local(future) } } impl Executor for TaskExecutor -where F: Future + 'static +where + F: Future + 'static, { fn execute(&self, future: F) -> Result<(), ExecuteError> { - CURRENT.with(|current| { - match current.spawn.get() { - Some(spawn) => { - unsafe { (*spawn).spawn_local(Box::new(future), false) }; - Ok(()) - } - None => { - Err(ExecuteError::new(ExecuteErrorKind::Shutdown, future)) - } + CURRENT.with(|current| match current.spawn.get() { + Some(spawn) => { + unsafe { (*spawn).spawn_local(Box::new(future), false) }; + Ok(()) } + None => Err(ExecuteError::new(ExecuteErrorKind::Shutdown, future)), }) } } @@ -775,13 +761,12 @@ where F: Future + 'static impl<'a, U: Unpark> Borrow<'a, U> { fn enter(&mut self, _: &mut Enter, f: F) -> R - where F: FnOnce() -> R, + where + F: FnOnce() -> R, { CURRENT.with(|current| { current.id.set(Some(self.id)); - current.set_spawn(self, || { - f() - }) + current.set_spawn(self, || f()) }) } } @@ -801,7 +786,8 @@ impl<'a, U: Unpark> SpawnLocal for Borrow<'a, U> { impl CurrentRunner { fn set_spawn(&self, spawn: &mut SpawnLocal, f: F) -> R - where F: FnOnce() -> R + where + F: FnOnce() -> R, { struct Reset<'a>(&'a CurrentRunner); diff --git a/tokio-current-thread/src/scheduler.rs b/tokio-current-thread/src/scheduler.rs index eac30d178..c814b60f7 100644 --- a/tokio-current-thread/src/scheduler.rs +++ b/tokio-current-thread/src/scheduler.rs @@ -1,20 +1,20 @@ use super::Borrow; -use tokio_executor::Enter; use tokio_executor::park::Unpark; +use tokio_executor::Enter; -use futures::{Future, Async}; -use futures::executor::{self, Spawn, UnsafeNotify, NotifyHandle}; +use futures::executor::{self, NotifyHandle, Spawn, UnsafeNotify}; +use futures::{Async, Future}; use std::cell::UnsafeCell; use std::fmt::{self, Debug}; +use std::marker::PhantomData; use std::mem; use std::ptr; -use std::sync::atomic::Ordering::{Relaxed, SeqCst, Acquire, Release, AcqRel}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release, SeqCst}; use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize}; use std::sync::{Arc, Weak}; -use std::usize; use std::thread; -use std::marker::PhantomData; +use std::usize; /// A generic task-aware scheduler. /// @@ -135,7 +135,8 @@ pub struct Scheduled<'a, U: 'a> { } impl Scheduler -where U: Unpark, +where + U: Unpark, { /// Constructs a new, empty `Scheduler` /// @@ -200,9 +201,7 @@ where U: Unpark, pub fn has_pending_futures(&mut self) -> bool { // See function definition for why the unsafe is needed and // correctly used here - unsafe { - self.inner.has_pending_futures() - } + unsafe { self.inner.has_pending_futures() } } /// Advance the scheduler state, returning `true` if any futures were @@ -210,11 +209,9 @@ where U: Unpark, /// /// This function should be called whenever the caller is notified via a /// wakeup. - pub fn tick(&mut self, eid: u64, enter: &mut Enter, num_futures: &AtomicUsize) -> bool - { + pub fn tick(&mut self, eid: u64, enter: &mut Enter, num_futures: &AtomicUsize) -> bool { let mut ret = false; - let tick = self.inner.tick_num.fetch_add(1, SeqCst) - .wrapping_add(1); + let tick = self.inner.tick_num.fetch_add(1, SeqCst).wrapping_add(1); loop { let node = match unsafe { self.inner.dequeue(Some(tick)) } { @@ -246,7 +243,7 @@ where U: Unpark, let node = ptr2arc(node); assert!((*node.next_all.get()).is_null()); assert!((*node.prev_all.get()).is_null()); - continue + continue; }; // We're going to need to be very careful if the `poll` @@ -369,8 +366,7 @@ impl Task { impl fmt::Debug for Task { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Task") - .finish() + fmt.debug_struct("Task").finish() } } @@ -580,7 +576,7 @@ impl List { self.len += 1; - return ptr + return ptr; } /// Pop an element from the front of the list @@ -632,7 +628,7 @@ impl List { self.len -= 1; - return node + return node; } } @@ -749,7 +745,7 @@ impl Drop for Node { fn arc2ptr(ptr: Arc) -> *const T { let addr = &*ptr as *const T; mem::forget(ptr); - return addr + return addr; } unsafe fn ptr2arc(ptr: *const T) -> Arc { diff --git a/tokio-current-thread/tests/current_thread.rs b/tokio-current-thread/tests/current_thread.rs index d2b6a6908..0ed0ca246 100644 --- a/tokio-current-thread/tests/current_thread.rs +++ b/tokio-current-thread/tests/current_thread.rs @@ -1,6 +1,6 @@ +extern crate futures; extern crate tokio_current_thread; extern crate tokio_executor; -extern crate futures; use tokio_current_thread::{block_on_all, CurrentThread}; @@ -10,8 +10,8 @@ use std::rc::Rc; use std::thread; use std::time::Duration; -use futures::task; use futures::future::{self, lazy}; +use futures::task; // This is not actually unused --- we need this trait to be in scope for // the tests that sue TaskExecutor::current().execute(). The compiler // doesn't realise that. @@ -22,7 +22,7 @@ use futures::sync::oneshot; mod from_block_on_all { use super::*; - fn test>) + 'static>(spawn: F) { + fn test>) + 'static>(spawn: F) { let cnt = Rc::new(Cell::new(0)); let c = cnt.clone(); @@ -36,7 +36,8 @@ mod from_block_on_all { }))); Ok::<_, ()>("hello") - })).unwrap(); + })) + .unwrap(); assert_eq!(2, cnt.get()); assert_eq!(msg, "hello"); @@ -72,7 +73,8 @@ fn block_waits() { block_on_all(rx.then(move |_| { cnt.set(1 + cnt.get()); Ok::<_, ()>(()) - })).unwrap(); + })) + .unwrap(); assert_eq!(1, cnt2.get()); } @@ -100,11 +102,14 @@ fn spawn_many() { mod does_not_set_global_executor_by_default { use super::*; - fn test + Send>) -> Result<(), E> + 'static, E>(spawn: F) { + fn test + Send>) -> Result<(), E> + 'static, E>( + spawn: F, + ) { block_on_all(lazy(|| { spawn(Box::new(lazy(|| ok()))).unwrap_err(); ok() - })).unwrap() + })) + .unwrap() } #[test] @@ -123,20 +128,22 @@ mod from_block_on_future { use super::*; fn test>)>(spawn: F) { - let cnt = Rc::new(Cell::new(0)); + let cnt = Rc::new(Cell::new(0)); let mut tokio_current_thread = CurrentThread::new(); - tokio_current_thread.block_on(lazy(|| { - let cnt = cnt.clone(); + tokio_current_thread + .block_on(lazy(|| { + let cnt = cnt.clone(); - spawn(Box::new(lazy(move || { - cnt.set(1 + cnt.get()); - Ok(()) - }))); + spawn(Box::new(lazy(move || { + cnt.set(1 + cnt.get()); + Ok(()) + }))); - Ok::<_, ()>(()) - })).unwrap(); + Ok::<_, ()>(()) + })) + .unwrap(); tokio_current_thread.run().unwrap(); @@ -150,7 +157,11 @@ mod from_block_on_future { #[test] fn execute() { - test(|f| { tokio_current_thread::TaskExecutor::current().execute(f).unwrap(); }); + test(|f| { + tokio_current_thread::TaskExecutor::current() + .execute(f) + .unwrap(); + }); } } @@ -170,8 +181,8 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>) + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { let mut rc = Rc::new(()); @@ -189,10 +200,12 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { let mut tokio_current_thread = CurrentThread::new(); - tokio_current_thread.block_on(lazy(|| { - spawn(Box::new(Never(rc.clone()))); - Ok::<_, ()>(()) - })).unwrap(); + tokio_current_thread + .block_on(lazy(|| { + spawn(Box::new(Never(rc.clone()))); + Ok::<_, ()>(()) + })) + .unwrap(); drop(tokio_current_thread); @@ -202,12 +215,15 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { #[test] fn spawn() { - test(tokio_current_thread::spawn, |rt, f| { rt.spawn(f); }) + test(tokio_current_thread::spawn, |rt, f| { + rt.spawn(f); + }) } #[test] fn execute() { - test(|f| { + test( + |f| { tokio_current_thread::TaskExecutor::current() .execute(f) .unwrap(); @@ -216,7 +232,9 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { // `futures::Executor`, so we'll call `.spawn(...)` rather than // `.execute(...)` for now. If `CurrentThread` is changed to // implement Executor, change this to `.execute(...).unwrap()`. - |rt, f| { rt.spawn(f); } + |rt, f| { + rt.spawn(f); + }, ); } } @@ -225,12 +243,11 @@ mod outstanding_tasks_are_dropped_when_executor_is_dropped { #[should_panic] fn nesting_run() { block_on_all(lazy(|| { - block_on_all(lazy(|| { - ok() - })).unwrap(); + block_on_all(lazy(|| ok())).unwrap(); ok() - })).unwrap(); + })) + .unwrap(); } mod run_in_future { @@ -241,13 +258,12 @@ mod run_in_future { fn spawn() { block_on_all(lazy(|| { tokio_current_thread::spawn(lazy(|| { - block_on_all(lazy(|| { - ok() - })).unwrap(); + block_on_all(lazy(|| ok())).unwrap(); ok() })); ok() - })).unwrap(); + })) + .unwrap(); } #[test] @@ -256,18 +272,16 @@ mod run_in_future { block_on_all(lazy(|| { tokio_current_thread::TaskExecutor::current() .execute(lazy(|| { - block_on_all(lazy(|| { - ok() - })).unwrap(); + block_on_all(lazy(|| ok())).unwrap(); ok() })) .unwrap(); ok() - })).unwrap(); + })) + .unwrap(); } } - #[test] fn tick_on_infini_future() { let num = Rc::new(Cell::new(0)); @@ -288,9 +302,7 @@ fn tick_on_infini_future() { } CurrentThread::new() - .spawn(Infini { - num: num.clone(), - }) + .spawn(Infini { num: num.clone() }) .turn(None) .unwrap(); @@ -347,7 +359,8 @@ mod tasks_are_scheduled_fairly { }); ok() - })).unwrap(); + })) + .unwrap(); } #[test] @@ -359,8 +372,8 @@ mod tasks_are_scheduled_fairly { fn execute() { test(|f| { tokio_current_thread::TaskExecutor::current() - .execute(f) - .unwrap(); + .execute(f) + .unwrap(); }) } } @@ -370,8 +383,8 @@ mod and_turn { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>) + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { let cnt = Rc::new(Cell::new(0)); let c = cnt.clone(); @@ -379,24 +392,25 @@ mod and_turn { let mut tokio_current_thread = CurrentThread::new(); // Spawn a basic task to get the executor to turn - dotspawn(&mut tokio_current_thread, Box::new(lazy(move || { - Ok(()) - }))); + dotspawn(&mut tokio_current_thread, Box::new(lazy(move || Ok(())))); // Turn once... tokio_current_thread.turn(None).unwrap(); - dotspawn(&mut tokio_current_thread, Box::new(lazy(move || { - c.set(1 + c.get()); - - // Spawn! - spawn(Box::new(lazy(move || { + dotspawn( + &mut tokio_current_thread, + Box::new(lazy(move || { c.set(1 + c.get()); - Ok::<(), ()>(()) - }))); - Ok(()) - }))); + // Spawn! + spawn(Box::new(lazy(move || { + c.set(1 + c.get()); + Ok::<(), ()>(()) + }))); + + Ok(()) + })), + ); // This does not run the newly spawned thread tokio_current_thread.turn(None).unwrap(); @@ -409,12 +423,15 @@ mod and_turn { #[test] fn spawn() { - test(tokio_current_thread::spawn, |rt, f| { rt.spawn(f); }) + test(tokio_current_thread::spawn, |rt, f| { + rt.spawn(f); + }) } #[test] fn execute() { - test(|f| { + test( + |f| { tokio_current_thread::TaskExecutor::current() .execute(f) .unwrap(); @@ -423,11 +440,12 @@ mod and_turn { // `futures::Executor`, so we'll call `.spawn(...)` rather than // `.execute(...)` for now. If `CurrentThread` is changed to // implement Executor, change this to `.execute(...).unwrap()`. - |rt, f| { rt.spawn(f); } + |rt, f| { + rt.spawn(f); + }, ); } - } mod in_drop { @@ -455,23 +473,24 @@ mod in_drop { fn test(spawn: F, dotspawn: G) where - F: Fn(Box>) + 'static, - G: Fn(&mut CurrentThread, Box>) + F: Fn(Box>) + 'static, + G: Fn(&mut CurrentThread, Box>), { - let mut tokio_current_thread = CurrentThread::new(); + let mut tokio_current_thread = CurrentThread::new(); let (tx, rx) = oneshot::channel(); - dotspawn(&mut tokio_current_thread, Box::new( - MyFuture { + dotspawn( + &mut tokio_current_thread, + Box::new(MyFuture { _data: Box::new(OnDrop(Some(move || { spawn(Box::new(lazy(move || { tx.send(()).unwrap(); Ok(()) }))); }))), - } - )); + }), + ); tokio_current_thread.block_on(rx).unwrap(); tokio_current_thread.run().unwrap(); @@ -479,12 +498,15 @@ mod in_drop { #[test] fn spawn() { - test(tokio_current_thread::spawn, |rt, f| { rt.spawn(f); }) + test(tokio_current_thread::spawn, |rt, f| { + rt.spawn(f); + }) } #[test] fn execute() { - test(|f| { + test( + |f| { tokio_current_thread::TaskExecutor::current() .execute(f) .unwrap(); @@ -493,7 +515,9 @@ mod in_drop { // `futures::Executor`, so we'll call `.spawn(...)` rather than // `.execute(...)` for now. If `CurrentThread` is changed to // implement Executor, change this to `.execute(...).unwrap()`. - |rt, f| { rt.spawn(f); } + |rt, f| { + rt.spawn(f); + }, ); } @@ -562,13 +586,17 @@ fn turn_has_polled() { tokio_current_thread.spawn(receiver.then(|_| Ok(()))); // Turn once... - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); // Should've polled the receiver once, but considered it not ready assert!(res.has_polled()); // Turn another time - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); // Should've polled nothing, the receiver is not ready yet assert!(!res.has_polled()); @@ -577,14 +605,18 @@ fn turn_has_polled() { sender.send(()).unwrap(); // Turn another time - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); // Should've polled the receiver, it's ready now assert!(res.has_polled()); // Now the executor should be empty assert!(tokio_current_thread.is_idle()); - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); // So should've polled nothing assert!(!res.has_polled()); @@ -646,46 +678,41 @@ fn turn_fair() { // Once an item is received on the oneshot channel, it will immediately // immediately make the second oneshot channel ready - tokio_current_thread.spawn(receiver - .map_err(|_| unreachable!()) - .and_then(move |_| { - sender_2.send(()).unwrap(); - receiver_1_done_clone.set(true); + tokio_current_thread.spawn(receiver.map_err(|_| unreachable!()).and_then(move |_| { + sender_2.send(()).unwrap(); + receiver_1_done_clone.set(true); - Ok(()) - }) - ); + Ok(()) + })); let receiver_2_done = Rc::new(Cell::new(false)); let receiver_2_done_clone = receiver_2_done.clone(); - tokio_current_thread.spawn(receiver_2 - .map_err(|_| unreachable!()) - .and_then(move |_| { - receiver_2_done_clone.set(true); - Ok(()) - }) - ); + tokio_current_thread.spawn(receiver_2.map_err(|_| unreachable!()).and_then(move |_| { + receiver_2_done_clone.set(true); + Ok(()) + })); // The third receiver is only woken up from our Park implementation, it simulates // e.g. a socket that first has to be polled to know if it is ready now let receiver_3_done = Rc::new(Cell::new(false)); let receiver_3_done_clone = receiver_3_done.clone(); - tokio_current_thread.spawn(receiver_3 - .map_err(|_| unreachable!()) - .and_then(move |_| { - receiver_3_done_clone.set(true); - Ok(()) - }) - ); + tokio_current_thread.spawn(receiver_3.map_err(|_| unreachable!()).and_then(move |_| { + receiver_3_done_clone.set(true); + Ok(()) + })); // First turn should've polled both and considered them not ready - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); assert!(res.has_polled()); // Next turn should've polled nothing - let res = tokio_current_thread.turn(Some(Duration::from_millis(0))).unwrap(); + let res = tokio_current_thread + .turn(Some(Duration::from_millis(0))) + .unwrap(); assert!(!res.has_polled()); assert!(!receiver_1_done.get()); @@ -736,10 +763,12 @@ fn spawn_from_other_thread() { let (sender, receiver) = oneshot::channel::<()>(); thread::spawn(move || { - handle.spawn(lazy(move || { - sender.send(()).unwrap(); - Ok(()) - })).unwrap(); + handle + .spawn(lazy(move || { + sender.send(()).unwrap(); + Ok(()) + })) + .unwrap(); }); let _ = current_thread.block_on(receiver).unwrap(); @@ -758,10 +787,12 @@ fn spawn_from_other_thread_unpark() { thread::spawn(move || { let _ = receiver_2.recv().unwrap(); - handle.spawn(lazy(move || { - sender_1.send(()).unwrap(); - Ok(()) - })).unwrap(); + handle + .spawn(lazy(move || { + sender_1.send(()).unwrap(); + Ok(()) + })) + .unwrap(); }); // Ensure that unparking the executor works correctly. It will first @@ -769,13 +800,15 @@ fn spawn_from_other_thread_unpark() { // lazy future below which will cause the future to be spawned from // the other thread. Then the executor will park but should be woken // up because *now* we have a new future to schedule - let _ = current_thread.block_on( - lazy(move || { - sender_2.send(()).unwrap(); - Ok(()) - }) - .and_then(|_| receiver_1) - ).unwrap(); + let _ = current_thread + .block_on( + lazy(move || { + sender_2.send(()).unwrap(); + Ok(()) + }) + .and_then(|_| receiver_1), + ) + .unwrap(); } #[test] @@ -785,10 +818,12 @@ fn spawn_from_executor_with_handle() { let (tx, rx) = oneshot::channel(); current_thread.spawn(lazy(move || { - handle.spawn(lazy(move || { - tx.send(()).unwrap(); - Ok(()) - })).unwrap(); + handle + .spawn(lazy(move || { + tx.send(()).unwrap(); + Ok(()) + })) + .unwrap(); Ok::<_, ()>(()) })); diff --git a/tokio-executor/src/enter.rs b/tokio-executor/src/enter.rs index 4d9af8ccf..64bfeb340 100644 --- a/tokio-executor/src/enter.rs +++ b/tokio-executor/src/enter.rs @@ -1,7 +1,7 @@ -use std::prelude::v1::*; use std::cell::Cell; use std::error::Error; use std::fmt; +use std::prelude::v1::*; use futures::{self, Future}; @@ -70,7 +70,10 @@ pub fn enter() -> Result { impl Enter { /// Register a callback to be invoked if and when the thread /// ceased to act as an executor. - pub fn on_exit(&mut self, f: F) where F: FnOnce() + 'static { + pub fn on_exit(&mut self, f: F) + where + F: FnOnce() + 'static, + { self.on_exit.push(Box::new(f)); } @@ -88,7 +91,6 @@ impl Enter { pub fn block_on(&mut self, f: F) -> Result { futures::executor::spawn(f).wait_future() } - } impl fmt::Debug for Enter { @@ -103,7 +105,7 @@ impl Drop for Enter { assert!(c.get()); if self.permanent { - return + return; } for callback in self.on_exit.drain(..) { diff --git a/tokio-executor/src/global.rs b/tokio-executor/src/global.rs index 40bdbf303..852f6db85 100644 --- a/tokio-executor/src/global.rs +++ b/tokio-executor/src/global.rs @@ -1,4 +1,4 @@ -use super::{Executor, Enter, SpawnError}; +use super::{Enter, Executor, SpawnError}; use futures::{future, Future}; @@ -33,24 +33,22 @@ impl DefaultExecutor { /// `DefaultExecutor::current()` on thread A and then sending the result to /// thread B will _not_ reference the default executor that was set on thread A. pub fn current() -> DefaultExecutor { - DefaultExecutor { - _dummy: (), - } + DefaultExecutor { _dummy: () } } #[inline] fn with_current R, R>(f: F) -> Option { - EXECUTOR.with(|current_executor| { - match current_executor.replace(State::Active) { + EXECUTOR.with( + |current_executor| match current_executor.replace(State::Active) { State::Ready(executor_ptr) => { let executor = unsafe { &mut *executor_ptr }; let result = f(executor); current_executor.set(State::Ready(executor_ptr)); Some(result) - }, + } State::Empty | State::Active => None, - } - }) + }, + ) } } @@ -61,10 +59,10 @@ enum State { // default executor is defined and ready to be used Ready(*mut Executor), // default executor is currently active (used to detect recursive calls) - Active + Active, } -thread_local!{ +thread_local! { /// Thread-local tracking the current executor static EXECUTOR: Cell = Cell::new(State::Empty) } @@ -72,9 +70,10 @@ thread_local!{ // ===== impl DefaultExecutor ===== impl super::Executor for DefaultExecutor { - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError> - { + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError> { DefaultExecutor::with_current(|executor| executor.spawn(future)) .unwrap_or_else(|| Err(SpawnError::shutdown())) } @@ -86,7 +85,8 @@ impl super::Executor for DefaultExecutor { } impl future::Executor for DefaultExecutor -where T: Future + Send + 'static, +where + T: Future + Send + 'static, { fn execute(&self, future: T) -> Result<(), future::ExecuteError> { if let Err(e) = super::Executor::status(self) { @@ -146,10 +146,10 @@ where T: Future + Send + 'static, /// # pub fn main() {} /// ``` pub fn spawn(future: T) - where T: Future + Send + 'static, +where + T: Future + Send + 'static, { - DefaultExecutor::current().spawn(Box::new(future)) - .unwrap() + DefaultExecutor::current().spawn(Box::new(future)).unwrap() } /// Set the default executor for the duration of the closure @@ -158,13 +158,15 @@ pub fn spawn(future: T) /// /// This function panics if there already is a default executor set. pub fn with_default(executor: &mut T, enter: &mut Enter, f: F) -> R -where T: Executor, - F: FnOnce(&mut Enter) -> R +where + T: Executor, + F: FnOnce(&mut Enter) -> R, { EXECUTOR.with(|cell| { match cell.get() { - State::Ready(_) | State::Active => - panic!("default executor already set for execution context"), + State::Ready(_) | State::Active => { + panic!("default executor already set for execution context") + } _ => {} } @@ -202,7 +204,7 @@ unsafe fn hide_lt<'a>(p: *mut (Executor + 'a)) -> *mut (Executor + 'static) { #[cfg(test)] mod tests { - use super::{Executor, DefaultExecutor, with_default}; + use super::{with_default, DefaultExecutor, Executor}; #[test] fn default_executor_is_send_and_sync() { diff --git a/tokio-executor/src/lib.rs b/tokio-executor/src/lib.rs index c9a0217c3..db9c1781d 100644 --- a/tokio-executor/src/lib.rs +++ b/tokio-executor/src/lib.rs @@ -134,8 +134,10 @@ pub trait Executor { /// # } /// # fn main() {} /// ``` - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError>; + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError>; /// Provides a best effort **hint** to whether or not `spawn` will succeed. /// @@ -178,9 +180,10 @@ pub trait Executor { } impl Executor for Box { - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError> - { + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError> { (**self).spawn(future) } diff --git a/tokio-executor/src/park.rs b/tokio-executor/src/park.rs index 05ed58d52..073c4fef3 100644 --- a/tokio-executor/src/park.rs +++ b/tokio-executor/src/park.rs @@ -190,7 +190,8 @@ impl ParkThread { /// Get a reference to the `ParkThread` handle for this thread. fn with_current(&self, f: F) -> R - where F: FnOnce(&Parker) -> R, + where + F: FnOnce(&Parker) -> R, { CURRENT_PARKER.with(|inner| f(inner)) } diff --git a/tokio-executor/tests/executor.rs b/tokio-executor/tests/executor.rs index 0c7269fd3..fdfb7735f 100644 --- a/tokio-executor/tests/executor.rs +++ b/tokio-executor/tests/executor.rs @@ -1,15 +1,15 @@ -extern crate tokio_executor; extern crate futures; +extern crate tokio_executor; +use futures::{future::lazy, Future}; use tokio_executor::*; -use futures::{Future, future::lazy}; mod out_of_executor_context { use super::*; fn test(spawn: F) where - F: Fn(Box + Send>) -> Result<(), E>, + F: Fn(Box + Send>) -> Result<(), E>, { let res = spawn(Box::new(lazy(|| Ok(())))); assert!(res.is_err()); diff --git a/tokio-fs/examples/std-echo.rs b/tokio-fs/examples/std-echo.rs index 15ac4004f..f7433fba6 100644 --- a/tokio-fs/examples/std-echo.rs +++ b/tokio-fs/examples/std-echo.rs @@ -2,39 +2,35 @@ #![deny(deprecated, warnings)] extern crate futures; -extern crate tokio_fs; extern crate tokio_codec; +extern crate tokio_fs; extern crate tokio_threadpool; -use tokio_fs::{stdin, stdout, stderr}; use tokio_codec::{FramedRead, FramedWrite, LinesCodec}; +use tokio_fs::{stderr, stdin, stdout}; use tokio_threadpool::Builder; -use futures::{Future, Stream, Sink}; +use futures::{Future, Sink, Stream}; use std::io; pub fn main() -> Result<(), Box> { - let pool = Builder::new() - .pool_size(1) - .build(); + let pool = Builder::new().pool_size(1).build(); pool.spawn({ let input = FramedRead::new(stdin(), LinesCodec::new()); - let output = FramedWrite::new(stdout(), LinesCodec::new()) - .with(|line: String| { - let mut out = "OUT: ".to_string(); - out.push_str(&line); - Ok::<_, io::Error>(out) - }); + let output = FramedWrite::new(stdout(), LinesCodec::new()).with(|line: String| { + let mut out = "OUT: ".to_string(); + out.push_str(&line); + Ok::<_, io::Error>(out) + }); - let error = FramedWrite::new(stderr(), LinesCodec::new()) - .with(|line: String| { - let mut out = "ERR: ".to_string(); - out.push_str(&line); - Ok::<_, io::Error>(out) - }); + let error = FramedWrite::new(stderr(), LinesCodec::new()).with(|line: String| { + let mut out = "ERR: ".to_string(); + out.push_str(&line); + Ok::<_, io::Error>(out) + }); let dst = output.fanout(error); @@ -44,6 +40,8 @@ pub fn main() -> Result<(), Box> { .map_err(|e| panic!("io error = {:?}", e)) }); - pool.shutdown_on_idle().wait().map_err(|_| "failed to shutdown the thread pool")?; + pool.shutdown_on_idle() + .wait() + .map_err(|_| "failed to shutdown the thread pool")?; Ok(()) } diff --git a/tokio-fs/src/create_dir.rs b/tokio-fs/src/create_dir.rs index a174a5d97..7ae71d7f7 100644 --- a/tokio-fs/src/create_dir.rs +++ b/tokio-fs/src/create_dir.rs @@ -17,30 +17,28 @@ pub fn create_dir>(path: P) -> CreateDirFuture

{ #[derive(Debug)] pub struct CreateDirFuture

where - P: AsRef + P: AsRef, { path: P, } impl

CreateDirFuture

where - P: AsRef + P: AsRef, { fn new(path: P) -> CreateDirFuture

{ - CreateDirFuture { - path: path, - } + CreateDirFuture { path: path } } } impl

Future for CreateDirFuture

where - P: AsRef + P: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::create_dir(&self.path) ) + ::blocking_io(|| fs::create_dir(&self.path)) } } diff --git a/tokio-fs/src/create_dir_all.rs b/tokio-fs/src/create_dir_all.rs index 3e3248067..67b0aaf1a 100644 --- a/tokio-fs/src/create_dir_all.rs +++ b/tokio-fs/src/create_dir_all.rs @@ -18,30 +18,28 @@ pub fn create_dir_all>(path: P) -> CreateDirAllFuture

{ #[derive(Debug)] pub struct CreateDirAllFuture

where - P: AsRef + P: AsRef, { path: P, } impl

CreateDirAllFuture

where - P: AsRef + P: AsRef, { fn new(path: P) -> CreateDirAllFuture

{ - CreateDirAllFuture { - path: path, - } + CreateDirAllFuture { path: path } } } impl

Future for CreateDirAllFuture

where - P: AsRef + P: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::create_dir_all(&self.path) ) + ::blocking_io(|| fs::create_dir_all(&self.path)) } } diff --git a/tokio-fs/src/file/create.rs b/tokio-fs/src/file/create.rs index 402741856..e92575ccb 100644 --- a/tokio-fs/src/file/create.rs +++ b/tokio-fs/src/file/create.rs @@ -13,7 +13,8 @@ pub struct CreateFuture

{ } impl

CreateFuture

-where P: AsRef + Send + 'static, +where + P: AsRef + Send + 'static, { pub(crate) fn new(path: P) -> Self { CreateFuture { path } @@ -21,15 +22,14 @@ where P: AsRef + Send + 'static, } impl

Future for CreateFuture

-where P: AsRef + Send + 'static, +where + P: AsRef + Send + 'static, { type Item = File; type Error = io::Error; fn poll(&mut self) -> Poll { - let std = try_ready!(::blocking_io(|| { - StdFile::create(&self.path) - })); + let std = try_ready!(::blocking_io(|| StdFile::create(&self.path))); let file = File::from_std(std); Ok(file.into()) diff --git a/tokio-fs/src/file/metadata.rs b/tokio-fs/src/file/metadata.rs index 3c807613b..e6eaf6c85 100644 --- a/tokio-fs/src/file/metadata.rs +++ b/tokio-fs/src/file/metadata.rs @@ -29,9 +29,7 @@ impl Future for MetadataFuture { type Error = io::Error; fn poll(&mut self) -> Poll { - let metadata = try_ready!(::blocking_io(|| { - StdFile::metadata(self.std()) - })); + let metadata = try_ready!(::blocking_io(|| StdFile::metadata(self.std()))); let file = self.file.take().expect(POLL_AFTER_RESOLVE); Ok((file, metadata).into()) diff --git a/tokio-fs/src/file/mod.rs b/tokio-fs/src/file/mod.rs index 7ab533cd7..13601b39b 100644 --- a/tokio-fs/src/file/mod.rs +++ b/tokio-fs/src/file/mod.rs @@ -21,7 +21,7 @@ use tokio_io::{AsyncRead, AsyncWrite}; use futures::Poll; use std::fs::{File as StdFile, Metadata, Permissions}; -use std::io::{self, Read, Write, Seek}; +use std::io::{self, Read, Seek, Write}; use std::path::Path; /// A reference to an open file on the filesystem. @@ -43,16 +43,16 @@ use std::path::Path; /// /// ```no_run /// extern crate tokio; -/// +/// /// use tokio::prelude::{AsyncWrite, Future}; -/// +/// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| file.poll_write(b"hello, world!")) /// .map(|res| { /// println!("{:?}", res); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); -/// +/// /// tokio::run(task); /// } /// ``` @@ -61,9 +61,9 @@ use std::path::Path; /// /// ```no_run /// extern crate tokio; -/// +/// /// use tokio::prelude::{AsyncRead, Future}; -/// +/// /// fn main() { /// let task = tokio::fs::File::open("foo.txt") /// .and_then(|mut file| { @@ -112,7 +112,8 @@ impl File { /// } /// ``` pub fn open

(path: P) -> OpenFuture

- where P: AsRef + Send + 'static, + where + P: AsRef + Send + 'static, { OpenOptions::new().read(true).open(path) } @@ -151,7 +152,8 @@ impl File { /// } /// ``` pub fn create

(path: P) -> CreateFuture

- where P: AsRef + Send + 'static, + where + P: AsRef + Send + 'static, { CreateFuture::new(path) } @@ -165,7 +167,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use std::fs::File; - /// + /// /// fn main() { /// let std_file = File::open("foo.txt").unwrap(); /// let file = tokio::fs::File::from_std(std_file); @@ -194,7 +196,7 @@ impl File { /// # extern crate tokio; /// use tokio::prelude::Future; /// use std::io::SeekFrom; - /// + /// /// fn main() { /// let task = tokio::fs::File::open("foo.txt") /// // move cursor 6 bytes from the start of the file @@ -202,7 +204,7 @@ impl File { /// .map(|res| { /// println!("{:?}", res); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -223,7 +225,7 @@ impl File { /// # extern crate tokio; /// use tokio::prelude::Future; /// use std::io::SeekFrom; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|file| file.seek(SeekFrom::Start(6))) @@ -231,7 +233,7 @@ impl File { /// // handle returned file .. /// # println!("{:?}", file); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -249,7 +251,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::{AsyncWrite, Future}; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| { @@ -260,7 +262,7 @@ impl File { /// // handle returned result .. /// # println!("{:?}", res); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -282,7 +284,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::{AsyncWrite, Future}; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| { @@ -293,7 +295,7 @@ impl File { /// // handle returned result .. /// # println!("{:?}", res); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -318,7 +320,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| { @@ -328,7 +330,7 @@ impl File { /// // handle returned result .. /// # println!("{:?}", res); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -343,14 +345,14 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|file| file.metadata()) /// .map(|metadata| { /// println!("{:?}", metadata); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -365,7 +367,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| file.poll_metadata()) @@ -373,7 +375,7 @@ impl File { /// // metadata is of type Async::Ready /// println!("{:?}", metadata); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -390,7 +392,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|mut file| file.poll_try_clone()) @@ -398,7 +400,7 @@ impl File { /// // do something with the clone /// # println!("{:?}", clone); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -462,7 +464,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .and_then(|file| file.metadata()) @@ -474,7 +476,7 @@ impl File { /// _ => println!("permissions set!"), /// } /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` @@ -495,7 +497,7 @@ impl File { /// ```no_run /// # extern crate tokio; /// use tokio::prelude::Future; - /// + /// /// fn main() { /// let task = tokio::fs::File::create("foo.txt") /// .map(|file| { @@ -503,7 +505,7 @@ impl File { /// // do something with the std::fs::File /// # println!("{:?}", std_file); /// }).map_err(|err| eprintln!("IO error: {:?}", err)); - /// + /// /// tokio::run(task); /// } /// ``` diff --git a/tokio-fs/src/file/open.rs b/tokio-fs/src/file/open.rs index 197ec237a..68f7abe34 100644 --- a/tokio-fs/src/file/open.rs +++ b/tokio-fs/src/file/open.rs @@ -14,7 +14,8 @@ pub struct OpenFuture

{ } impl

OpenFuture

-where P: AsRef + Send + 'static, +where + P: AsRef + Send + 'static, { pub(crate) fn new(options: StdOpenOptions, path: P) -> Self { OpenFuture { options, path } @@ -22,15 +23,14 @@ where P: AsRef + Send + 'static, } impl

Future for OpenFuture

-where P: AsRef + Send + 'static, +where + P: AsRef + Send + 'static, { type Item = File; type Error = io::Error; fn poll(&mut self) -> Poll { - let std = try_ready!(::blocking_io(|| { - self.options.open(&self.path) - })); + let std = try_ready!(::blocking_io(|| self.options.open(&self.path))); let file = File::from_std(std); Ok(file.into()) diff --git a/tokio-fs/src/file/open_options.rs b/tokio-fs/src/file/open_options.rs index 99cc71c5b..76e0678b5 100644 --- a/tokio-fs/src/file/open_options.rs +++ b/tokio-fs/src/file/open_options.rs @@ -90,7 +90,8 @@ impl OpenOptions { /// /// [`open`]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.open pub fn open

(&self, path: P) -> OpenFuture

- where P: AsRef + Send + 'static + where + P: AsRef + Send + 'static, { OpenFuture::new(self.0.clone(), path) } diff --git a/tokio-fs/src/file/seek.rs b/tokio-fs/src/file/seek.rs index 0765d3db9..373e53ce3 100644 --- a/tokio-fs/src/file/seek.rs +++ b/tokio-fs/src/file/seek.rs @@ -25,12 +25,11 @@ impl Future for SeekFuture { type Error = io::Error; fn poll(&mut self) -> Poll { - let pos = try_ready!( - self.inner - .as_mut() - .expect("Cannot poll `SeekFuture` after it resolves") - .poll_seek(self.pos) - ); + let pos = try_ready!(self + .inner + .as_mut() + .expect("Cannot poll `SeekFuture` after it resolves") + .poll_seek(self.pos)); let inner = self.inner.take().unwrap(); Ok((inner, pos).into()) } diff --git a/tokio-fs/src/hard_link.rs b/tokio-fs/src/hard_link.rs index e8ea51152..697427909 100644 --- a/tokio-fs/src/hard_link.rs +++ b/tokio-fs/src/hard_link.rs @@ -21,7 +21,7 @@ pub fn hard_link, Q: AsRef>(src: P, dst: Q) -> HardLinkFutu pub struct HardLinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { src: P, dst: Q, @@ -30,25 +30,22 @@ where impl HardLinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { fn new(src: P, dst: Q) -> HardLinkFuture { - HardLinkFuture { - src: src, - dst: dst, - } + HardLinkFuture { src: src, dst: dst } } } impl Future for HardLinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::hard_link(&self.src, &self.dst) ) + ::blocking_io(|| fs::hard_link(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/lib.rs b/tokio-fs/src/lib.rs index 95e33be1b..e80bde45f 100644 --- a/tokio-fs/src/lib.rs +++ b/tokio-fs/src/lib.rs @@ -39,16 +39,16 @@ pub mod file; mod hard_link; mod metadata; pub mod os; +mod read; mod read_dir; mod read_link; -mod read; mod remove_dir; mod remove_file; mod rename; mod set_permissions; +mod stderr; mod stdin; mod stdout; -mod stderr; mod symlink_metadata; mod write; @@ -58,27 +58,28 @@ pub use file::File; pub use file::OpenOptions; pub use hard_link::{hard_link, HardLinkFuture}; pub use metadata::{metadata, MetadataFuture}; -pub use read_dir::{read_dir, ReadDirFuture, ReadDir, DirEntry}; -pub use read_link::{read_link, ReadLinkFuture}; pub use read::{read, ReadFile}; +pub use read_dir::{read_dir, DirEntry, ReadDir, ReadDirFuture}; +pub use read_link::{read_link, ReadLinkFuture}; pub use remove_dir::{remove_dir, RemoveDirFuture}; pub use remove_file::{remove_file, RemoveFileFuture}; pub use rename::{rename, RenameFuture}; pub use set_permissions::{set_permissions, SetPermissionsFuture}; +pub use stderr::{stderr, Stderr}; pub use stdin::{stdin, Stdin}; pub use stdout::{stdout, Stdout}; -pub use stderr::{stderr, Stderr}; pub use symlink_metadata::{symlink_metadata, SymlinkMetadataFuture}; pub use write::{write, WriteFile}; -use futures::Poll; use futures::Async::*; +use futures::Poll; use std::io; use std::io::ErrorKind::{Other, WouldBlock}; fn blocking_io(f: F) -> Poll -where F: FnOnce() -> io::Result, +where + F: FnOnce() -> io::Result, { match tokio_threadpool::blocking(f) { Ok(Ready(Ok(v))) => Ok(v.into()), @@ -89,7 +90,8 @@ where F: FnOnce() -> io::Result, } fn would_block(f: F) -> io::Result -where F: FnOnce() -> io::Result, +where + F: FnOnce() -> io::Result, { match tokio_threadpool::blocking(f) { Ok(Ready(Ok(v))) => Ok(v), @@ -103,6 +105,9 @@ where F: FnOnce() -> io::Result, } fn blocking_err() -> io::Error { - io::Error::new(Other, "`blocking` annotated I/O must be called \ - from the context of the Tokio runtime.") + io::Error::new( + Other, + "`blocking` annotated I/O must be called \ + from the context of the Tokio runtime.", + ) } diff --git a/tokio-fs/src/os/unix.rs b/tokio-fs/src/os/unix.rs index 5f8eedeba..9bd8566b8 100644 --- a/tokio-fs/src/os/unix.rs +++ b/tokio-fs/src/os/unix.rs @@ -1,8 +1,8 @@ //! Unix-specific extensions to primitives in the `tokio_fs` module. use std::io; -use std::path::Path; use std::os::unix::fs; +use std::path::Path; use futures::{Future, Poll}; @@ -22,7 +22,7 @@ pub fn symlink, Q: AsRef>(src: P, dst: Q) -> SymlinkFuture< pub struct SymlinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { src: P, dst: Q, @@ -31,25 +31,22 @@ where impl SymlinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { fn new(src: P, dst: Q) -> SymlinkFuture { - SymlinkFuture { - src: src, - dst: dst, - } + SymlinkFuture { src: src, dst: dst } } } impl Future for SymlinkFuture where P: AsRef, - Q: AsRef + Q: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink(&self.src, &self.dst) ) + ::blocking_io(|| fs::symlink(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/os/windows/symlink_dir.rs b/tokio-fs/src/os/windows/symlink_dir.rs index 9806ff3a3..dbf43605f 100644 --- a/tokio-fs/src/os/windows/symlink_dir.rs +++ b/tokio-fs/src/os/windows/symlink_dir.rs @@ -1,6 +1,6 @@ use std::io; -use std::path::Path; use std::os::windows::fs; +use std::path::Path; use futures::{Future, Poll}; @@ -21,7 +21,7 @@ pub fn symlink_dir, Q: AsRef>(src: P, dst: Q) -> SymlinkDir pub struct SymlinkDirFuture where P: AsRef, - Q: AsRef + Q: AsRef, { src: P, dst: Q, @@ -30,25 +30,22 @@ where impl SymlinkDirFuture where P: AsRef, - Q: AsRef + Q: AsRef, { fn new(src: P, dst: Q) -> SymlinkDirFuture { - SymlinkDirFuture { - src: src, - dst: dst, - } + SymlinkDirFuture { src: src, dst: dst } } } impl Future for SymlinkDirFuture where P: AsRef, - Q: AsRef + Q: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink_dir(&self.src, &self.dst) ) + ::blocking_io(|| fs::symlink_dir(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/os/windows/symlink_file.rs b/tokio-fs/src/os/windows/symlink_file.rs index 583b61587..e27a10064 100644 --- a/tokio-fs/src/os/windows/symlink_file.rs +++ b/tokio-fs/src/os/windows/symlink_file.rs @@ -1,6 +1,6 @@ use std::io; -use std::path::Path; use std::os::windows::fs; +use std::path::Path; use futures::{Future, Poll}; @@ -21,7 +21,7 @@ pub fn symlink_file, Q: AsRef>(src: P, dst: Q) -> SymlinkFi pub struct SymlinkFileFuture where P: AsRef, - Q: AsRef + Q: AsRef, { src: P, dst: Q, @@ -30,25 +30,22 @@ where impl SymlinkFileFuture where P: AsRef, - Q: AsRef + Q: AsRef, { fn new(src: P, dst: Q) -> SymlinkFileFuture { - SymlinkFileFuture { - src: src, - dst: dst, - } + SymlinkFileFuture { src: src, dst: dst } } } impl Future for SymlinkFileFuture where P: AsRef, - Q: AsRef + Q: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::symlink_file(&self.src, &self.dst) ) + ::blocking_io(|| fs::symlink_file(&self.src, &self.dst)) } } diff --git a/tokio-fs/src/read.rs b/tokio-fs/src/read.rs index 7b42ae881..50d1dd7f5 100644 --- a/tokio-fs/src/read.rs +++ b/tokio-fs/src/read.rs @@ -1,7 +1,7 @@ -use {file, File}; use futures::{Async, Future, Poll}; use std::{io, mem, path::Path}; use tokio_io; +use {file, File}; /// Creates a future which will open a file for reading and read the entire /// contents into a buffer and return said buffer. diff --git a/tokio-fs/src/read_dir.rs b/tokio-fs/src/read_dir.rs index 3818c7102..05629d790 100644 --- a/tokio-fs/src/read_dir.rs +++ b/tokio-fs/src/read_dir.rs @@ -1,5 +1,5 @@ use std::ffi::OsString; -use std::fs::{self, DirEntry as StdDirEntry, ReadDir as StdReadDir, FileType, Metadata}; +use std::fs::{self, DirEntry as StdDirEntry, FileType, Metadata, ReadDir as StdReadDir}; use std::io; #[cfg(unix)] use std::os::unix::fs::DirEntryExt; @@ -30,12 +30,10 @@ where impl

ReadDirFuture

where - P: AsRef + Send + 'static + P: AsRef + Send + 'static, { fn new(path: P) -> ReadDirFuture

{ - ReadDirFuture { - path: path, - } + ReadDirFuture { path: path } } } @@ -75,12 +73,10 @@ impl Stream for ReadDir { type Error = io::Error; fn poll(&mut self) -> Poll, Self::Error> { - ::blocking_io(|| { - match self.0.next() { - Some(Err(err)) => Err(err), - Some(Ok(item)) => Ok(Some(DirEntry(item))), - None => Ok(None) - } + ::blocking_io(|| match self.0.next() { + Some(Err(err)) => Err(err), + Some(Ok(item)) => Ok(Some(DirEntry(item))), + None => Ok(None), }) } } diff --git a/tokio-fs/src/read_link.rs b/tokio-fs/src/read_link.rs index 5e5bf2a30..927c3c658 100644 --- a/tokio-fs/src/read_link.rs +++ b/tokio-fs/src/read_link.rs @@ -17,30 +17,28 @@ pub fn read_link>(path: P) -> ReadLinkFuture

{ #[derive(Debug)] pub struct ReadLinkFuture

where - P: AsRef + P: AsRef, { path: P, } impl

ReadLinkFuture

where - P: AsRef + P: AsRef, { fn new(path: P) -> ReadLinkFuture

{ - ReadLinkFuture { - path: path, - } + ReadLinkFuture { path: path } } } impl

Future for ReadLinkFuture

where - P: AsRef + P: AsRef, { type Item = PathBuf; type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::read_link(&self.path) ) + ::blocking_io(|| fs::read_link(&self.path)) } } diff --git a/tokio-fs/src/remove_dir.rs b/tokio-fs/src/remove_dir.rs index 5aa73bfb5..171466620 100644 --- a/tokio-fs/src/remove_dir.rs +++ b/tokio-fs/src/remove_dir.rs @@ -17,30 +17,28 @@ pub fn remove_dir>(path: P) -> RemoveDirFuture

{ #[derive(Debug)] pub struct RemoveDirFuture

where - P: AsRef + P: AsRef, { path: P, } impl

RemoveDirFuture

where - P: AsRef + P: AsRef, { fn new(path: P) -> RemoveDirFuture

{ - RemoveDirFuture { - path: path, - } + RemoveDirFuture { path: path } } } impl

Future for RemoveDirFuture

where - P: AsRef + P: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::remove_dir(&self.path) ) + ::blocking_io(|| fs::remove_dir(&self.path)) } } diff --git a/tokio-fs/src/remove_file.rs b/tokio-fs/src/remove_file.rs index f61741857..da273f686 100644 --- a/tokio-fs/src/remove_file.rs +++ b/tokio-fs/src/remove_file.rs @@ -21,30 +21,28 @@ pub fn remove_file>(path: P) -> RemoveFileFuture

{ #[derive(Debug)] pub struct RemoveFileFuture

where - P: AsRef + P: AsRef, { path: P, } impl

RemoveFileFuture

where - P: AsRef + P: AsRef, { fn new(path: P) -> RemoveFileFuture

{ - RemoveFileFuture { - path: path, - } + RemoveFileFuture { path: path } } } impl

Future for RemoveFileFuture

where - P: AsRef + P: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::remove_file(&self.path) ) + ::blocking_io(|| fs::remove_file(&self.path)) } } diff --git a/tokio-fs/src/rename.rs b/tokio-fs/src/rename.rs index 210f53bb5..aaa8a4946 100644 --- a/tokio-fs/src/rename.rs +++ b/tokio-fs/src/rename.rs @@ -21,7 +21,7 @@ pub fn rename, Q: AsRef>(from: P, to: Q) -> RenameFuture where P: AsRef, - Q: AsRef + Q: AsRef, { from: P, to: Q, @@ -30,25 +30,22 @@ where impl RenameFuture where P: AsRef, - Q: AsRef + Q: AsRef, { fn new(from: P, to: Q) -> RenameFuture { - RenameFuture { - from: from, - to: to, - } + RenameFuture { from: from, to: to } } } impl Future for RenameFuture where P: AsRef, - Q: AsRef + Q: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::rename(&self.from, &self.to) ) + ::blocking_io(|| fs::rename(&self.from, &self.to)) } } diff --git a/tokio-fs/src/set_permissions.rs b/tokio-fs/src/set_permissions.rs index a85044862..75f9d0fdd 100644 --- a/tokio-fs/src/set_permissions.rs +++ b/tokio-fs/src/set_permissions.rs @@ -17,7 +17,7 @@ pub fn set_permissions>(path: P, perm: fs::Permissions) -> SetPer #[derive(Debug)] pub struct SetPermissionsFuture

where - P: AsRef + P: AsRef, { path: P, perm: fs::Permissions, @@ -25,7 +25,7 @@ where impl

SetPermissionsFuture

where - P: AsRef + P: AsRef, { fn new(path: P, perm: fs::Permissions) -> SetPermissionsFuture

{ SetPermissionsFuture { @@ -37,12 +37,12 @@ where impl

Future for SetPermissionsFuture

where - P: AsRef + P: AsRef, { type Item = (); type Error = io::Error; fn poll(&mut self) -> Poll { - ::blocking_io(|| fs::set_permissions(&self.path, self.perm.clone()) ) + ::blocking_io(|| fs::set_permissions(&self.path, self.perm.clone())) } } diff --git a/tokio-fs/src/stderr.rs b/tokio-fs/src/stderr.rs index cf6439075..24c1dcb1c 100644 --- a/tokio-fs/src/stderr.rs +++ b/tokio-fs/src/stderr.rs @@ -1,8 +1,8 @@ -use tokio_io::{AsyncWrite}; +use tokio_io::AsyncWrite; use futures::Poll; -use std::io::{self, Write, Stderr as StdStderr}; +use std::io::{self, Stderr as StdStderr, Write}; /// A handle to the standard error stream of a process. /// @@ -42,4 +42,3 @@ impl AsyncWrite for Stderr { Ok(().into()) } } - diff --git a/tokio-fs/src/stdin.rs b/tokio-fs/src/stdin.rs index 2284f886f..ac04c43fe 100644 --- a/tokio-fs/src/stdin.rs +++ b/tokio-fs/src/stdin.rs @@ -1,4 +1,4 @@ -use tokio_io::{AsyncRead}; +use tokio_io::AsyncRead; use std::io::{self, Read, Stdin as StdStdin}; diff --git a/tokio-fs/src/stdout.rs b/tokio-fs/src/stdout.rs index 1c4cd5ad0..0c2bdc54f 100644 --- a/tokio-fs/src/stdout.rs +++ b/tokio-fs/src/stdout.rs @@ -1,8 +1,8 @@ -use tokio_io::{AsyncWrite}; +use tokio_io::AsyncWrite; use futures::Poll; -use std::io::{self, Write, Stdout as StdStdout}; +use std::io::{self, Stdout as StdStdout, Write}; /// A handle to the standard output stream of a process. /// diff --git a/tokio-fs/src/write.rs b/tokio-fs/src/write.rs index 17d55552d..3f49cc01c 100644 --- a/tokio-fs/src/write.rs +++ b/tokio-fs/src/write.rs @@ -1,7 +1,7 @@ -use {file, File}; use futures::{Async, Future, Poll}; -use std::{io, mem, path::Path, fmt}; +use std::{fmt, io, mem, path::Path}; use tokio_io; +use {file, File}; /// Creates a future that will open a file for writing and write the entire /// contents of `contents` to it. diff --git a/tokio-io/src/_tokio_codec/framed.rs b/tokio-io/src/_tokio_codec/framed.rs index 614a45e2b..d290575e7 100644 --- a/tokio-io/src/_tokio_codec/framed.rs +++ b/tokio-io/src/_tokio_codec/framed.rs @@ -1,15 +1,15 @@ #![allow(deprecated)] -use std::io::{self, Read, Write}; use std::fmt; +use std::io::{self, Read, Write}; -use {AsyncRead, AsyncWrite}; -use codec::{Decoder, Encoder}; use super::framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2}; use super::framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2}; +use codec::{Decoder, Encoder}; +use {AsyncRead, AsyncWrite}; -use futures::{Stream, Sink, StartSend, Poll}; -use bytes::{BytesMut}; +use bytes::BytesMut; +use futures::{Poll, Sink, StartSend, Stream}; /// A unified `Stream` and `Sink` interface to an underlying I/O object, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -22,8 +22,9 @@ pub struct Framed { pub struct Fuse(pub T, pub U); impl Framed -where T: AsyncRead + AsyncWrite, - U: Decoder + Encoder, +where + T: AsyncRead + AsyncWrite, + U: Decoder + Encoder, { /// Provides a `Stream` and `Sink` interface for reading and writing to this /// `Io` object, using `Decode` and `Encode` to read and write the raw data. @@ -70,10 +71,12 @@ impl Framed { /// If you want to work more directly with the streams and sink, consider /// calling `split` on the `Framed` returned by this method, which will /// break them into separate objects, allowing them to interact more easily. - pub fn from_parts(parts: FramedParts) -> Framed - { + pub fn from_parts(parts: FramedParts) -> Framed { Framed { - inner: framed_read2_with_buffer(framed_write2_with_buffer(Fuse(parts.io, parts.codec), parts.write_buf), parts.read_buf), + inner: framed_read2_with_buffer( + framed_write2_with_buffer(Fuse(parts.io, parts.codec), parts.write_buf), + parts.read_buf, + ), } } @@ -145,8 +148,9 @@ impl Framed { } impl Stream for Framed - where T: AsyncRead, - U: Decoder, +where + T: AsyncRead, + U: Decoder, { type Item = U::Item; type Error = U::Error; @@ -157,17 +161,15 @@ impl Stream for Framed } impl Sink for Framed - where T: AsyncWrite, - U: Encoder, - U::Error: From, +where + T: AsyncWrite, + U: Encoder, + U::Error: From, { type SinkItem = U::Item; type SinkError = U::Error; - fn start_send(&mut self, - item: Self::SinkItem) - -> StartSend - { + fn start_send(&mut self, item: Self::SinkItem) -> StartSend { self.inner.get_mut().start_send(item) } @@ -181,14 +183,15 @@ impl Sink for Framed } impl fmt::Debug for Framed - where T: fmt::Debug, - U: fmt::Debug, +where + T: fmt::Debug, + U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Framed") - .field("io", &self.inner.get_ref().get_ref().0) - .field("codec", &self.inner.get_ref().get_ref().1) - .finish() + .field("io", &self.inner.get_ref().get_ref().0) + .field("codec", &self.inner.get_ref().get_ref().1) + .finish() } } diff --git a/tokio-io/src/_tokio_codec/framed_read.rs b/tokio-io/src/_tokio_codec/framed_read.rs index 279b1a3bc..2e2f06b8c 100644 --- a/tokio-io/src/_tokio_codec/framed_read.rs +++ b/tokio-io/src/_tokio_codec/framed_read.rs @@ -2,12 +2,12 @@ use std::fmt; -use AsyncRead; -use codec::Decoder; use super::framed::Fuse; +use codec::Decoder; +use AsyncRead; -use futures::{Async, Poll, Stream, Sink, StartSend}; use bytes::BytesMut; +use futures::{Async, Poll, Sink, StartSend, Stream}; /// A `Stream` of messages decoded from an `AsyncRead`. pub struct FramedRead { @@ -26,8 +26,9 @@ const INITIAL_CAPACITY: usize = 8 * 1024; // ===== impl FramedRead ===== impl FramedRead - where T: AsyncRead, - D: Decoder, +where + T: AsyncRead, + D: Decoder, { /// Creates a new `FramedRead` with the given `decoder`. pub fn new(inner: T, decoder: D) -> FramedRead { @@ -79,8 +80,9 @@ impl FramedRead { } impl Stream for FramedRead - where T: AsyncRead, - D: Decoder, +where + T: AsyncRead, + D: Decoder, { type Item = D::Item; type Error = D::Error; @@ -91,15 +93,13 @@ impl Stream for FramedRead } impl Sink for FramedRead - where T: Sink, +where + T: Sink, { type SinkItem = T::SinkItem; type SinkError = T::SinkError; - fn start_send(&mut self, - item: Self::SinkItem) - -> StartSend - { + fn start_send(&mut self, item: Self::SinkItem) -> StartSend { self.inner.inner.0.start_send(item) } @@ -113,8 +113,9 @@ impl Sink for FramedRead } impl fmt::Debug for FramedRead - where T: fmt::Debug, - D: fmt::Debug, +where + T: fmt::Debug, + D: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FramedRead") @@ -170,7 +171,8 @@ impl FramedRead2 { } impl Stream for FramedRead2 - where T: AsyncRead + Decoder, +where + T: AsyncRead + Decoder, { type Item = T::Item; type Error = T::Error; diff --git a/tokio-io/src/_tokio_codec/framed_write.rs b/tokio-io/src/_tokio_codec/framed_write.rs index 8ba75092d..ff8f6a8e7 100644 --- a/tokio-io/src/_tokio_codec/framed_write.rs +++ b/tokio-io/src/_tokio_codec/framed_write.rs @@ -1,14 +1,14 @@ #![allow(deprecated)] -use std::io::{self, Read}; use std::fmt; +use std::io::{self, Read}; -use {AsyncRead, AsyncWrite}; -use codec::{Decoder, Encoder}; use super::framed::Fuse; +use codec::{Decoder, Encoder}; +use {AsyncRead, AsyncWrite}; -use futures::{Async, AsyncSink, Poll, Stream, Sink, StartSend}; use bytes::BytesMut; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; /// A `Sink` of frames encoded to an `AsyncWrite`. pub struct FramedWrite { @@ -24,8 +24,9 @@ const INITIAL_CAPACITY: usize = 8 * 1024; const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY; impl FramedWrite - where T: AsyncWrite, - E: Encoder, +where + T: AsyncWrite, + E: Encoder, { /// Creates a new `FramedWrite` with the given `encoder`. pub fn new(inner: T, encoder: E) -> FramedWrite { @@ -77,8 +78,9 @@ impl FramedWrite { } impl Sink for FramedWrite - where T: AsyncWrite, - E: Encoder, +where + T: AsyncWrite, + E: Encoder, { type SinkItem = E::Item; type SinkError = E::Error; @@ -97,7 +99,8 @@ impl Sink for FramedWrite } impl Stream for FramedWrite - where T: Stream, +where + T: Stream, { type Item = T::Item; type Error = T::Error; @@ -108,15 +111,16 @@ impl Stream for FramedWrite } impl fmt::Debug for FramedWrite - where T: fmt::Debug, - U: fmt::Debug, +where + T: fmt::Debug, + U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FramedWrite") - .field("inner", &self.inner.get_ref().0) - .field("encoder", &self.inner.get_ref().1) - .field("buffer", &self.inner.buffer) - .finish() + .field("inner", &self.inner.get_ref().0) + .field("encoder", &self.inner.get_ref().1) + .field("buffer", &self.inner.buffer) + .finish() } } @@ -159,7 +163,8 @@ impl FramedWrite2 { } impl Sink for FramedWrite2 - where T: AsyncWrite + Encoder, +where + T: AsyncWrite + Encoder, { type SinkItem = T::Item; type SinkError = T::Error; @@ -189,8 +194,12 @@ impl Sink for FramedWrite2 let n = try_ready!(self.inner.poll_write(&self.buffer)); if n == 0 { - return Err(io::Error::new(io::ErrorKind::WriteZero, "failed to \ - write frame to transport").into()); + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "failed to \ + write frame to transport", + ) + .into()); } // TODO: Add a way to `bytes` to do this w/o returning the drained diff --git a/tokio-io/src/allow_std.rs b/tokio-io/src/allow_std.rs index 46b0376b5..af39ac219 100644 --- a/tokio-io/src/allow_std.rs +++ b/tokio-io/src/allow_std.rs @@ -1,6 +1,6 @@ -use {AsyncRead, AsyncWrite}; use futures::{Async, Poll}; use std::{fmt, io}; +use {AsyncRead, AsyncWrite}; /// A simple wrapper type which allows types that only implement /// `std::io::Read` or `std::io::Write` to be used in contexts which expect @@ -37,7 +37,10 @@ impl AllowStdIo { } } -impl io::Write for AllowStdIo where T: io::Write { +impl io::Write for AllowStdIo +where + T: io::Write, +{ fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } @@ -52,13 +55,19 @@ impl io::Write for AllowStdIo where T: io::Write { } } -impl AsyncWrite for AllowStdIo where T: io::Write { +impl AsyncWrite for AllowStdIo +where + T: io::Write, +{ fn shutdown(&mut self) -> Poll<(), io::Error> { Ok(Async::Ready(())) } } -impl io::Read for AllowStdIo where T: io::Read { +impl io::Read for AllowStdIo +where + T: io::Read, +{ fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } @@ -75,7 +84,10 @@ impl io::Read for AllowStdIo where T: io::Read { } } -impl AsyncRead for AllowStdIo where T: io::Read { +impl AsyncRead for AllowStdIo +where + T: io::Read, +{ // TODO: override prepare_uninitialized_buffer once `Read::initializer` is stable. // See rust-lang/rust #42788 } diff --git a/tokio-io/src/async_read.rs b/tokio-io/src/async_read.rs index 8dbc8b6ce..f136ccea8 100644 --- a/tokio-io/src/async_read.rs +++ b/tokio-io/src/async_read.rs @@ -1,11 +1,11 @@ -use std::io as std_io; use bytes::BufMut; use futures::{Async, Poll}; +use std::io as std_io; -use {framed, split, AsyncWrite}; #[allow(deprecated)] use codec::{Decoder, Encoder, Framed}; use split::{ReadHalf, WriteHalf}; +use {framed, split, AsyncWrite}; /// Read bytes asynchronously. /// @@ -80,9 +80,7 @@ pub trait AsyncRead: std_io::Read { fn poll_read(&mut self, buf: &mut [u8]) -> Poll { match self.read(buf) { Ok(t) => Ok(Async::Ready(t)), - Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => { - return Ok(Async::NotReady) - } + Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => return Ok(Async::NotReady), Err(e) => return Err(e.into()), } } @@ -94,7 +92,8 @@ pub trait AsyncRead: std_io::Read { /// will be advanced if any bytes were read. Note that this method typically /// will not reallocate the buffer provided. fn read_buf(&mut self, buf: &mut B) -> Poll - where Self: Sized, + where + Self: Sized, { if !buf.has_remaining_mut() { return Ok(Async::Ready(0)); @@ -134,7 +133,8 @@ pub trait AsyncRead: std_io::Read { #[deprecated(since = "0.1.7", note = "Use tokio_codec::Decoder::framed instead")] #[allow(deprecated)] fn framed(self, codec: T) -> Framed - where Self: AsyncWrite + Sized, + where + Self: AsyncWrite + Sized, { framed::framed(self, codec) } @@ -144,7 +144,8 @@ pub trait AsyncRead: std_io::Read { /// The two halves returned implement the `Read` and `Write` traits, /// respectively. fn split(self) -> (ReadHalf, WriteHalf) - where Self: AsyncWrite + Sized, + where + Self: AsyncWrite + Sized, { split::split(self) } diff --git a/tokio-io/src/async_write.rs b/tokio-io/src/async_write.rs index 6fcf418a0..0a09480e8 100644 --- a/tokio-io/src/async_write.rs +++ b/tokio-io/src/async_write.rs @@ -1,6 +1,6 @@ -use std::io as std_io; use bytes::Buf; use futures::{Async, Poll}; +use std::io as std_io; use AsyncRead; @@ -46,9 +46,7 @@ pub trait AsyncWrite: std_io::Write { fn poll_write(&mut self, buf: &[u8]) -> Poll { match self.write(buf) { Ok(t) => Ok(Async::Ready(t)), - Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => { - return Ok(Async::NotReady) - } + Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => return Ok(Async::NotReady), Err(e) => return Err(e.into()), } } @@ -65,9 +63,7 @@ pub trait AsyncWrite: std_io::Write { fn poll_flush(&mut self) -> Poll<(), std_io::Error> { match self.flush() { Ok(t) => Ok(Async::Ready(t)), - Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => { - return Ok(Async::NotReady) - } + Err(ref e) if e.kind() == std_io::ErrorKind::WouldBlock => return Ok(Async::NotReady), Err(e) => return Err(e.into()), } } @@ -137,7 +133,8 @@ pub trait AsyncWrite: std_io::Write { /// Note that this method will advance the `buf` provided automatically by /// the number of bytes written. fn write_buf(&mut self, buf: &mut B) -> Poll - where Self: Sized, + where + Self: Sized, { if !buf.has_remaining() { return Ok(Async::Ready(0)); @@ -179,8 +176,9 @@ impl AsyncRead for std_io::Take { } impl AsyncRead for std_io::Chain - where T: AsyncRead, - U: AsyncRead, +where + T: AsyncRead, + U: AsyncRead, { unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { let (t, u) = self.get_ref(); @@ -203,8 +201,7 @@ impl AsyncRead for std_io::BufReader { } } -impl> AsyncRead for std_io::Cursor { -} +impl> AsyncRead for std_io::Cursor {} impl<'a> AsyncWrite for std_io::Cursor<&'a mut [u8]> { fn shutdown(&mut self) -> Poll<(), std_io::Error> { diff --git a/tokio-io/src/codec/bytes_codec.rs b/tokio-io/src/codec/bytes_codec.rs index c77f5ca53..ecfd15ab9 100644 --- a/tokio-io/src/codec/bytes_codec.rs +++ b/tokio-io/src/codec/bytes_codec.rs @@ -1,7 +1,7 @@ #![allow(deprecated)] -use bytes::{Bytes, BufMut, BytesMut}; -use codec::{Encoder, Decoder}; +use bytes::{BufMut, Bytes, BytesMut}; +use codec::{Decoder, Encoder}; use std::io; /// A simple `Codec` implementation that just ships bytes around. @@ -11,7 +11,9 @@ pub struct BytesCodec(()); impl BytesCodec { /// Creates a new `BytesCodec` for shipping around raw bytes. - pub fn new() -> BytesCodec { BytesCodec(()) } + pub fn new() -> BytesCodec { + BytesCodec(()) + } } impl Decoder for BytesCodec { diff --git a/tokio-io/src/codec/decoder.rs b/tokio-io/src/codec/decoder.rs index eb129a8e9..ec5083a2b 100644 --- a/tokio-io/src/codec/decoder.rs +++ b/tokio-io/src/codec/decoder.rs @@ -1,10 +1,10 @@ -use std::io; use bytes::BytesMut; +use std::io; -use {AsyncWrite, AsyncRead}; use super::encoder::Encoder; +use {AsyncRead, AsyncWrite}; -use ::_tokio_codec::Framed; +use _tokio_codec::Framed; /// Decoding of frames via buffers. /// @@ -85,8 +85,7 @@ pub trait Decoder { if buf.is_empty() { Ok(None) } else { - Err(io::Error::new(io::ErrorKind::Other, - "bytes remaining on stream").into()) + Err(io::Error::new(io::ErrorKind::Other, "bytes remaining on stream").into()) } } } @@ -110,7 +109,8 @@ pub trait Decoder { /// calling `split` on the `Framed` returned by this method, which will /// break them into separate objects, allowing them to interact more easily. fn framed(self, io: T) -> Framed - where Self: Encoder + Sized, + where + Self: Encoder + Sized, { Framed::new(io, self) } diff --git a/tokio-io/src/codec/encoder.rs b/tokio-io/src/codec/encoder.rs index 222990d2e..506508032 100644 --- a/tokio-io/src/codec/encoder.rs +++ b/tokio-io/src/codec/encoder.rs @@ -1,5 +1,5 @@ -use std::io; use bytes::BytesMut; +use std::io; /// Trait of helper objects to write out messages as bytes, for use with /// `FramedWrite`. @@ -21,6 +21,5 @@ pub trait Encoder { /// This method will encode `item` into the byte buffer provided by `dst`. /// The `dst` provided is an internal buffer of the `Framed` instance and /// will be written out when possible. - fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) - -> Result<(), Self::Error>; + fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error>; } diff --git a/tokio-io/src/codec/lines_codec.rs b/tokio-io/src/codec/lines_codec.rs index 7056d5c8c..818397fa5 100644 --- a/tokio-io/src/codec/lines_codec.rs +++ b/tokio-io/src/codec/lines_codec.rs @@ -1,7 +1,7 @@ #![allow(deprecated)] use bytes::{BufMut, BytesMut}; -use codec::{Encoder, Decoder}; +use codec::{Decoder, Encoder}; use std::{io, str}; /// A simple `Codec` implementation that splits up data into lines. @@ -25,10 +25,8 @@ impl LinesCodec { } fn utf8(buf: &[u8]) -> Result<&str, io::Error> { - str::from_utf8(buf).map_err(|_| - io::Error::new( - io::ErrorKind::InvalidData, - "Unable to decode input as UTF8")) + str::from_utf8(buf) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Unable to decode input as UTF8")) } fn without_carriage_return(s: &[u8]) -> &[u8] { @@ -44,12 +42,10 @@ impl Decoder for LinesCodec { type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result, io::Error> { - if let Some(newline_offset) = - buf[self.next_index..].iter().position(|b| *b == b'\n') - { + if let Some(newline_offset) = buf[self.next_index..].iter().position(|b| *b == b'\n') { let newline_index = newline_offset + self.next_index; let line = buf.split_to(newline_index + 1); - let line = &line[..line.len()-1]; + let line = &line[..line.len() - 1]; let line = without_carriage_return(line); let line = utf8(line)?; self.next_index = 0; diff --git a/tokio-io/src/codec/mod.rs b/tokio-io/src/codec/mod.rs index 47c1071cc..663682175 100644 --- a/tokio-io/src/codec/mod.rs +++ b/tokio-io/src/codec/mod.rs @@ -18,14 +18,14 @@ #![doc(hidden)] #![allow(deprecated)] +mod bytes_codec; mod decoder; mod encoder; -mod bytes_codec; mod lines_codec; +pub use self::bytes_codec::BytesCodec; pub use self::decoder::Decoder; pub use self::encoder::Encoder; -pub use self::bytes_codec::BytesCodec; pub use self::lines_codec::LinesCodec; pub use framed::{Framed, FramedParts}; @@ -374,5 +374,5 @@ pub mod length_delimited { //! [`Encoder`]: ../trait.Encoder.html //! [`BytesMut`]: https://docs.rs/bytes/0.4/bytes/struct.BytesMut.html - pub use ::length_delimited::*; + pub use length_delimited::*; } diff --git a/tokio-io/src/framed.rs b/tokio-io/src/framed.rs index b3df25013..aea7b5468 100644 --- a/tokio-io/src/framed.rs +++ b/tokio-io/src/framed.rs @@ -1,15 +1,15 @@ #![allow(deprecated)] -use std::io::{self, Read, Write}; use std::fmt; +use std::io::{self, Read, Write}; -use {AsyncRead, AsyncWrite}; use codec::{Decoder, Encoder}; use framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2}; use framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2}; +use {AsyncRead, AsyncWrite}; -use futures::{Stream, Sink, StartSend, Poll}; -use bytes::{BytesMut}; +use bytes::BytesMut; +use futures::{Poll, Sink, StartSend, Stream}; /// A unified `Stream` and `Sink` interface to an underlying I/O object, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -26,8 +26,9 @@ pub struct Framed { pub struct Fuse(pub T, pub U); pub fn framed(inner: T, codec: U) -> Framed - where T: AsyncRead + AsyncWrite, - U: Decoder + Encoder, +where + T: AsyncRead + AsyncWrite, + U: Decoder + Encoder, { Framed { inner: framed_read2(framed_write2(Fuse(inner, codec))), @@ -55,10 +56,12 @@ impl Framed { /// If you want to work more directly with the streams and sink, consider /// calling `split` on the `Framed` returned by this method, which will /// break them into separate objects, allowing them to interact more easily. - pub fn from_parts(parts: FramedParts, codec: U) -> Framed - { + pub fn from_parts(parts: FramedParts, codec: U) -> Framed { Framed { - inner: framed_read2_with_buffer(framed_write2_with_buffer(Fuse(parts.inner, codec), parts.writebuf), parts.readbuf), + inner: framed_read2_with_buffer( + framed_write2_with_buffer(Fuse(parts.inner, codec), parts.writebuf), + parts.readbuf, + ), } } @@ -100,7 +103,11 @@ impl Framed { pub fn into_parts(self) -> FramedParts { let (inner, readbuf) = self.inner.into_parts(); let (inner, writebuf) = inner.into_parts(); - FramedParts { inner: inner.0, readbuf: readbuf, writebuf: writebuf } + FramedParts { + inner: inner.0, + readbuf: readbuf, + writebuf: writebuf, + } } /// Consumes the `Frame`, returning its underlying I/O stream and the buffer @@ -116,13 +123,21 @@ impl Framed { pub fn into_parts_and_codec(self) -> (FramedParts, U) { let (inner, readbuf) = self.inner.into_parts(); let (inner, writebuf) = inner.into_parts(); - (FramedParts { inner: inner.0, readbuf: readbuf, writebuf: writebuf }, inner.1) + ( + FramedParts { + inner: inner.0, + readbuf: readbuf, + writebuf: writebuf, + }, + inner.1, + ) } } impl Stream for Framed - where T: AsyncRead, - U: Decoder, +where + T: AsyncRead, + U: Decoder, { type Item = U::Item; type Error = U::Error; @@ -133,17 +148,15 @@ impl Stream for Framed } impl Sink for Framed - where T: AsyncWrite, - U: Encoder, - U::Error: From, +where + T: AsyncWrite, + U: Encoder, + U::Error: From, { type SinkItem = U::Item; type SinkError = U::Error; - fn start_send(&mut self, - item: Self::SinkItem) - -> StartSend - { + fn start_send(&mut self, item: Self::SinkItem) -> StartSend { self.inner.get_mut().start_send(item) } @@ -157,14 +170,15 @@ impl Sink for Framed } impl fmt::Debug for Framed - where T: fmt::Debug, - U: fmt::Debug, +where + T: fmt::Debug, + U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Framed") - .field("io", &self.inner.get_ref().get_ref().0) - .field("codec", &self.inner.get_ref().get_ref().1) - .finish() + .field("io", &self.inner.get_ref().get_ref().0) + .field("codec", &self.inner.get_ref().get_ref().1) + .finish() } } @@ -224,12 +238,11 @@ impl Encoder for Fuse { /// It can be used to construct a new `Framed` with a different codec. /// It contains all current buffers and the inner transport. #[derive(Debug)] -pub struct FramedParts -{ +pub struct FramedParts { /// The inner transport used to read bytes to and write bytes to pub inner: T, /// The buffer with read but unprocessed data. pub readbuf: BytesMut, /// A buffer with unprocessed data which are not written yet. - pub writebuf: BytesMut + pub writebuf: BytesMut, } diff --git a/tokio-io/src/framed_read.rs b/tokio-io/src/framed_read.rs index 69b7f4631..17d86aa86 100644 --- a/tokio-io/src/framed_read.rs +++ b/tokio-io/src/framed_read.rs @@ -2,12 +2,12 @@ use std::fmt; -use AsyncRead; use codec::Decoder; use framed::Fuse; +use AsyncRead; -use futures::{Async, Poll, Stream, Sink, StartSend}; use bytes::BytesMut; +use futures::{Async, Poll, Sink, StartSend, Stream}; /// A `Stream` of messages decoded from an `AsyncRead`. #[deprecated(since = "0.1.7", note = "Moved to tokio-codec")] @@ -30,8 +30,9 @@ const INITIAL_CAPACITY: usize = 8 * 1024; // ===== impl FramedRead ===== impl FramedRead - where T: AsyncRead, - D: Decoder, +where + T: AsyncRead, + D: Decoder, { /// Creates a new `FramedRead` with the given `decoder`. pub fn new(inner: T, decoder: D) -> FramedRead { @@ -83,8 +84,9 @@ impl FramedRead { } impl Stream for FramedRead - where T: AsyncRead, - D: Decoder, +where + T: AsyncRead, + D: Decoder, { type Item = D::Item; type Error = D::Error; @@ -95,15 +97,13 @@ impl Stream for FramedRead } impl Sink for FramedRead - where T: Sink, +where + T: Sink, { type SinkItem = T::SinkItem; type SinkError = T::SinkError; - fn start_send(&mut self, - item: Self::SinkItem) - -> StartSend - { + fn start_send(&mut self, item: Self::SinkItem) -> StartSend { self.inner.inner.0.start_send(item) } @@ -117,8 +117,9 @@ impl Sink for FramedRead } impl fmt::Debug for FramedRead - where T: fmt::Debug, - D: fmt::Debug, +where + T: fmt::Debug, + D: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FramedRead") @@ -174,7 +175,8 @@ impl FramedRead2 { } impl Stream for FramedRead2 - where T: AsyncRead + Decoder, +where + T: AsyncRead + Decoder, { type Item = T::Item; type Error = T::Error; diff --git a/tokio-io/src/framed_write.rs b/tokio-io/src/framed_write.rs index 392300ea9..af4bc7f21 100644 --- a/tokio-io/src/framed_write.rs +++ b/tokio-io/src/framed_write.rs @@ -1,14 +1,14 @@ #![allow(deprecated)] -use std::io::{self, Read}; use std::fmt; +use std::io::{self, Read}; -use {AsyncRead, AsyncWrite}; use codec::{Decoder, Encoder}; use framed::Fuse; +use {AsyncRead, AsyncWrite}; -use futures::{Async, AsyncSink, Poll, Stream, Sink, StartSend}; use bytes::BytesMut; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; /// A `Sink` of frames encoded to an `AsyncWrite`. #[deprecated(since = "0.1.7", note = "Moved to tokio-codec")] @@ -28,8 +28,9 @@ const INITIAL_CAPACITY: usize = 8 * 1024; const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY; impl FramedWrite - where T: AsyncWrite, - E: Encoder, +where + T: AsyncWrite, + E: Encoder, { /// Creates a new `FramedWrite` with the given `encoder`. pub fn new(inner: T, encoder: E) -> FramedWrite { @@ -81,8 +82,9 @@ impl FramedWrite { } impl Sink for FramedWrite - where T: AsyncWrite, - E: Encoder, +where + T: AsyncWrite, + E: Encoder, { type SinkItem = E::Item; type SinkError = E::Error; @@ -101,7 +103,8 @@ impl Sink for FramedWrite } impl Stream for FramedWrite - where T: Stream, +where + T: Stream, { type Item = T::Item; type Error = T::Error; @@ -112,15 +115,16 @@ impl Stream for FramedWrite } impl fmt::Debug for FramedWrite - where T: fmt::Debug, - U: fmt::Debug, +where + T: fmt::Debug, + U: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FramedWrite") - .field("inner", &self.inner.get_ref().0) - .field("encoder", &self.inner.get_ref().1) - .field("buffer", &self.inner.buffer) - .finish() + .field("inner", &self.inner.get_ref().0) + .field("encoder", &self.inner.get_ref().1) + .field("buffer", &self.inner.buffer) + .finish() } } @@ -163,7 +167,8 @@ impl FramedWrite2 { } impl Sink for FramedWrite2 - where T: AsyncWrite + Encoder, +where + T: AsyncWrite + Encoder, { type SinkItem = T::Item; type SinkError = T::Error; @@ -193,8 +198,12 @@ impl Sink for FramedWrite2 let n = try_ready!(self.inner.poll_write(&self.buffer)); if n == 0 { - return Err(io::Error::new(io::ErrorKind::WriteZero, "failed to - write frame to transport").into()); + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "failed to + write frame to transport", + ) + .into()); } // TODO: Add a way to `bytes` to do this w/o returning the drained diff --git a/tokio-io/src/io/copy.rs b/tokio-io/src/io/copy.rs index b21dc1c4a..e8a1dac95 100644 --- a/tokio-io/src/io/copy.rs +++ b/tokio-io/src/io/copy.rs @@ -33,8 +33,9 @@ pub struct Copy { /// consumed. On error the error is returned and the I/O objects are consumed as /// well. pub fn copy(reader: R, writer: W) -> Copy - where R: AsyncRead, - W: AsyncWrite, +where + R: AsyncRead, + W: AsyncWrite, { Copy { reader: Some(reader), @@ -48,8 +49,9 @@ pub fn copy(reader: R, writer: W) -> Copy } impl Future for Copy - where R: AsyncRead, - W: AsyncWrite, +where + R: AsyncRead, + W: AsyncWrite, { type Item = (u64, R, W); type Error = io::Error; @@ -74,8 +76,10 @@ impl Future for Copy let writer = self.writer.as_mut().unwrap(); let i = try_ready!(writer.poll_write(&self.buf[self.pos..self.cap])); if i == 0 { - return Err(io::Error::new(io::ErrorKind::WriteZero, - "write zero byte into writer")); + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "write zero byte into writer", + )); } else { self.pos += i; self.amt += i as u64; @@ -89,7 +93,7 @@ impl Future for Copy try_ready!(self.writer.as_mut().unwrap().poll_flush()); let reader = self.reader.take().unwrap(); let writer = self.writer.take().unwrap(); - return Ok((self.amt, reader, writer).into()) + return Ok((self.amt, reader, writer).into()); } } } diff --git a/tokio-io/src/io/flush.rs b/tokio-io/src/io/flush.rs index dabdc6c9c..febc7ee1b 100644 --- a/tokio-io/src/io/flush.rs +++ b/tokio-io/src/io/flush.rs @@ -1,6 +1,6 @@ use std::io; -use futures::{Poll, Future, Async}; +use futures::{Async, Future, Poll}; use AsyncWrite; @@ -23,15 +23,15 @@ pub struct Flush { /// otherwise it will repeatedly call `flush` until it sees `Ok(())`, scheduling /// a retry if `WouldBlock` is seen along the way. pub fn flush(a: A) -> Flush - where A: AsyncWrite, +where + A: AsyncWrite, { - Flush { - a: Some(a), - } + Flush { a: Some(a) } } impl Future for Flush - where A: AsyncWrite, +where + A: AsyncWrite, { type Item = A; type Error = io::Error; @@ -41,4 +41,3 @@ impl Future for Flush Ok(Async::Ready(self.a.take().unwrap())) } } - diff --git a/tokio-io/src/io/mod.rs b/tokio-io/src/io/mod.rs index 95eea0957..763cfaee7 100644 --- a/tokio-io/src/io/mod.rs +++ b/tokio-io/src/io/mod.rs @@ -18,15 +18,15 @@ mod read_until; mod shutdown; mod write_all; -pub use allow_std::AllowStdIo; pub use self::copy::{copy, Copy}; pub use self::flush::{flush, Flush}; -pub use lines::{lines, Lines}; pub use self::read::{read, Read}; pub use self::read_exact::{read_exact, ReadExact}; pub use self::read_to_end::{read_to_end, ReadToEnd}; pub use self::read_until::{read_until, ReadUntil}; pub use self::shutdown::{shutdown, Shutdown}; +pub use self::write_all::{write_all, WriteAll}; +pub use allow_std::AllowStdIo; +pub use lines::{lines, Lines}; pub use split::{ReadHalf, WriteHalf}; pub use window::Window; -pub use self::write_all::{write_all, WriteAll}; diff --git a/tokio-io/src/io/read.rs b/tokio-io/src/io/read.rs index 4c5a96652..632cef4d2 100644 --- a/tokio-io/src/io/read.rs +++ b/tokio-io/src/io/read.rs @@ -7,10 +7,7 @@ use AsyncRead; #[derive(Debug)] enum State { - Pending { - rd: R, - buf: T, - }, + Pending { rd: R, buf: T }, Empty, } @@ -20,10 +17,13 @@ enum State { /// The returned future will resolve to both the I/O stream and the buffer /// as well as the number of bytes read once the read operation is completed. pub fn read(rd: R, buf: T) -> Read - where R: AsyncRead, - T: AsMut<[u8]> +where + R: AsyncRead, + T: AsMut<[u8]>, { - Read { state: State::Pending { rd: rd, buf: buf } } + Read { + state: State::Pending { rd: rd, buf: buf }, + } } /// A future which can be used to easily read available number of bytes to fill @@ -36,15 +36,19 @@ pub struct Read { } impl Future for Read - where R: AsyncRead, - T: AsMut<[u8]> +where + R: AsyncRead, + T: AsMut<[u8]>, { type Item = (R, T, usize); type Error = io::Error; fn poll(&mut self) -> Poll<(R, T, usize), io::Error> { let nread = match self.state { - State::Pending { ref mut rd, ref mut buf } => try_ready!(rd.poll_read(&mut buf.as_mut()[..])), + State::Pending { + ref mut rd, + ref mut buf, + } => try_ready!(rd.poll_read(&mut buf.as_mut()[..])), State::Empty => panic!("poll a Read after it's done"), }; diff --git a/tokio-io/src/io/read_exact.rs b/tokio-io/src/io/read_exact.rs index b1e164403..3b98621ae 100644 --- a/tokio-io/src/io/read_exact.rs +++ b/tokio-io/src/io/read_exact.rs @@ -1,7 +1,7 @@ use std::io; use std::mem; -use futures::{Poll, Future}; +use futures::{Future, Poll}; use AsyncRead; @@ -18,11 +18,7 @@ pub struct ReadExact { #[derive(Debug)] enum State { - Reading { - a: A, - buf: T, - pos: usize, - }, + Reading { a: A, buf: T, pos: usize }, Empty, } @@ -37,8 +33,9 @@ enum State { /// the buffer will be returned, with all data read from the stream appended to /// the buffer. pub fn read_exact(a: A, buf: T) -> ReadExact - where A: AsyncRead, - T: AsMut<[u8]>, +where + A: AsyncRead, + T: AsMut<[u8]>, { ReadExact { state: State::Reading { @@ -54,21 +51,26 @@ fn eof() -> io::Error { } impl Future for ReadExact - where A: AsyncRead, - T: AsMut<[u8]>, +where + A: AsyncRead, + T: AsMut<[u8]>, { type Item = (A, T); type Error = io::Error; fn poll(&mut self) -> Poll<(A, T), io::Error> { match self.state { - State::Reading { ref mut a, ref mut buf, ref mut pos } => { + State::Reading { + ref mut a, + ref mut buf, + ref mut pos, + } => { let buf = buf.as_mut(); while *pos < buf.len() { let n = try_ready!(a.poll_read(&mut buf[*pos..])); *pos += n; if n == 0 { - return Err(eof()) + return Err(eof()); } } } diff --git a/tokio-io/src/io/read_to_end.rs b/tokio-io/src/io/read_to_end.rs index e7869cc19..296af6e30 100644 --- a/tokio-io/src/io/read_to_end.rs +++ b/tokio-io/src/io/read_to_end.rs @@ -1,7 +1,7 @@ use std::io; use std::mem; -use futures::{Poll, Future}; +use futures::{Future, Poll}; use AsyncRead; @@ -18,10 +18,7 @@ pub struct ReadToEnd { #[derive(Debug)] enum State { - Reading { - a: A, - buf: Vec, - }, + Reading { a: A, buf: Vec }, Empty, } @@ -32,30 +29,32 @@ enum State { /// the error yielded. In the case of success both the object and the buffer /// will be returned, with all data read from the stream appended to the buffer. pub fn read_to_end(a: A, buf: Vec) -> ReadToEnd - where A: AsyncRead, +where + A: AsyncRead, { ReadToEnd { - state: State::Reading { - a: a, - buf: buf, - } + state: State::Reading { a: a, buf: buf }, } } impl Future for ReadToEnd - where A: AsyncRead, +where + A: AsyncRead, { type Item = (A, Vec); type Error = io::Error; fn poll(&mut self) -> Poll<(A, Vec), io::Error> { match self.state { - State::Reading { ref mut a, ref mut buf } => { + State::Reading { + ref mut a, + ref mut buf, + } => { // If we get `Ok`, then we know the stream hit EOF and we're done. If we // hit "would block" then all the read data so far is in our buffer, and // otherwise we propagate errors try_nb!(a.read_to_end(buf)); - }, + } State::Empty => panic!("poll ReadToEnd after it's done"), } diff --git a/tokio-io/src/io/read_until.rs b/tokio-io/src/io/read_until.rs index 73c982924..d0be4c944 100644 --- a/tokio-io/src/io/read_until.rs +++ b/tokio-io/src/io/read_until.rs @@ -1,7 +1,7 @@ use std::io::{self, BufRead}; use std::mem; -use futures::{Poll, Future}; +use futures::{Future, Poll}; use AsyncRead; @@ -18,11 +18,7 @@ pub struct ReadUntil { #[derive(Debug)] enum State { - Reading { - a: A, - byte: u8, - buf: Vec, - }, + Reading { a: A, byte: u8, buf: Vec }, Empty, } @@ -37,32 +33,38 @@ enum State { /// /// [`BufRead::read_until`]: https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_until pub fn read_until(a: A, byte: u8, buf: Vec) -> ReadUntil - where A: AsyncRead + BufRead, +where + A: AsyncRead + BufRead, { ReadUntil { state: State::Reading { a: a, byte: byte, buf: buf, - } + }, } } impl Future for ReadUntil - where A: AsyncRead + BufRead +where + A: AsyncRead + BufRead, { type Item = (A, Vec); type Error = io::Error; fn poll(&mut self) -> Poll<(A, Vec), io::Error> { match self.state { - State::Reading { ref mut a, byte, ref mut buf } => { + State::Reading { + ref mut a, + byte, + ref mut buf, + } => { // If we get `Ok(n)`, then we know the stream hit EOF or the delimiter. // and just return it, as we are finished. // If we hit "would block" then all the read data so far // is in our buffer, and otherwise we propagate errors. try_nb!(a.read_until(byte, buf)); - }, + } State::Empty => panic!("poll ReadUntil after it's done"), } diff --git a/tokio-io/src/io/shutdown.rs b/tokio-io/src/io/shutdown.rs index 96a8886dd..d963a813a 100644 --- a/tokio-io/src/io/shutdown.rs +++ b/tokio-io/src/io/shutdown.rs @@ -1,6 +1,6 @@ use std::io; -use futures::{Poll, Future, Async}; +use futures::{Async, Future, Poll}; use AsyncWrite; @@ -24,15 +24,15 @@ pub struct Shutdown { /// otherwise it will repeatedly call `shutdown` until it sees `Ok(())`, /// scheduling a retry if `WouldBlock` is seen along the way. pub fn shutdown(a: A) -> Shutdown - where A: AsyncWrite, +where + A: AsyncWrite, { - Shutdown { - a: Some(a), - } + Shutdown { a: Some(a) } } impl Future for Shutdown - where A: AsyncWrite, +where + A: AsyncWrite, { type Item = A; type Error = io::Error; diff --git a/tokio-io/src/io/write_all.rs b/tokio-io/src/io/write_all.rs index 50b11fbc8..ba8af4a22 100644 --- a/tokio-io/src/io/write_all.rs +++ b/tokio-io/src/io/write_all.rs @@ -1,7 +1,7 @@ use std::io; use std::mem; -use futures::{Poll, Future}; +use futures::{Future, Poll}; use AsyncWrite; @@ -17,11 +17,7 @@ pub struct WriteAll { #[derive(Debug)] enum State { - Writing { - a: A, - buf: T, - pos: usize, - }, + Writing { a: A, buf: T, pos: usize }, Empty, } @@ -40,8 +36,9 @@ enum State { /// The `Window` struct is also available in this crate to provide a different /// window into a slice if necessary. pub fn write_all(a: A, buf: T) -> WriteAll - where A: AsyncWrite, - T: AsRef<[u8]>, +where + A: AsyncWrite, + T: AsRef<[u8]>, { WriteAll { state: State::Writing { @@ -57,21 +54,26 @@ fn zero_write() -> io::Error { } impl Future for WriteAll - where A: AsyncWrite, - T: AsRef<[u8]>, +where + A: AsyncWrite, + T: AsRef<[u8]>, { type Item = (A, T); type Error = io::Error; fn poll(&mut self) -> Poll<(A, T), io::Error> { match self.state { - State::Writing { ref mut a, ref buf, ref mut pos } => { + State::Writing { + ref mut a, + ref buf, + ref mut pos, + } => { let buf = buf.as_ref(); while *pos < buf.len() { let n = try_ready!(a.poll_write(&buf[*pos..])); *pos += n; if n == 0 { - return Err(zero_write()) + return Err(zero_write()); } } } diff --git a/tokio-io/src/length_delimited.rs b/tokio-io/src/length_delimited.rs index bf55bc881..f13d51564 100644 --- a/tokio-io/src/length_delimited.rs +++ b/tokio-io/src/length_delimited.rs @@ -2,14 +2,14 @@ use {codec, AsyncRead, AsyncWrite}; -use bytes::{Buf, BufMut, BytesMut, IntoBuf}; use bytes::buf::Chain; +use bytes::{Buf, BufMut, BytesMut, IntoBuf}; -use futures::{Async, AsyncSink, Stream, Sink, StartSend, Poll}; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; -use std::{cmp, fmt}; use std::error::Error as StdError; use std::io::{self, Cursor}; +use std::{cmp, fmt}; /// Configure length delimited `FramedRead`, `FramedWrite`, and `Framed` values. /// @@ -170,8 +170,9 @@ impl Sink for Framed { } impl fmt::Debug for Framed - where T: fmt::Debug, - B::Buf: fmt::Debug, +where + T: fmt::Debug, + B::Buf: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Framed") @@ -309,9 +310,10 @@ impl Decoder { }; if n > self.builder.max_frame_len as u64 { - return Err(io::Error::new(io::ErrorKind::InvalidData, FrameTooBig { - _priv: (), - })); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + FrameTooBig { _priv: () }, + )); } // The check above ensures there is no overflow @@ -327,7 +329,12 @@ impl Decoder { // Error handling match n { Some(n) => n, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, "provided length would overflow after adjustment")), + None => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "provided length would overflow after adjustment", + )); + } } }; @@ -361,15 +368,13 @@ impl codec::Decoder for Decoder { fn decode(&mut self, src: &mut BytesMut) -> io::Result> { let n = match self.state { - DecodeState::Head => { - match try!(self.decode_head(src)) { - Some(n) => { - self.state = DecodeState::Data(n); - n - } - None => return Ok(None), + DecodeState::Head => match try!(self.decode_head(src)) { + Some(n) => { + self.state = DecodeState::Data(n); + n } - } + None => return Ok(None), + }, DecodeState::Data(n) => n, }; @@ -477,9 +482,10 @@ impl FramedWrite { let n = buf.remaining(); if n > self.builder.max_frame_len { - return Err(io::Error::new(io::ErrorKind::InvalidInput, FrameTooBig { - _priv: (), - })); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + FrameTooBig { _priv: () }, + )); } // Adjust `n` with bounds checking @@ -492,7 +498,12 @@ impl FramedWrite { // Error handling let n = match n { Some(n) => n, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, "provided length would overflow after adjustment")), + None => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "provided length would overflow after adjustment", + )); + } }; if self.builder.length_field_is_big_endian { @@ -565,8 +576,9 @@ impl AsyncRead for FramedWrite { } impl fmt::Debug for FramedWrite - where T: fmt::Debug, - B::Buf: fmt::Debug, +where + T: fmt::Debug, + B::Buf: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FramedWrite") @@ -828,13 +840,17 @@ impl Builder { /// # } /// ``` pub fn new_read(&self, upstream: T) -> FramedRead - where T: AsyncRead, + where + T: AsyncRead, { FramedRead { - inner: codec::FramedRead::new(upstream, Decoder { - builder: *self, - state: DecodeState::Head, - }), + inner: codec::FramedRead::new( + upstream, + Decoder { + builder: *self, + state: DecodeState::Head, + }, + ), } } @@ -857,8 +873,9 @@ impl Builder { /// # pub fn main() {} /// ``` pub fn new_write(&self, inner: T) -> FramedWrite - where T: AsyncWrite, - B: IntoBuf, + where + T: AsyncWrite, + B: IntoBuf, { FramedWrite { inner: inner, @@ -886,8 +903,9 @@ impl Builder { /// # pub fn main() {} /// ``` pub fn new_framed(&self, inner: T) -> Framed - where T: AsyncRead + AsyncWrite, - B: IntoBuf + where + T: AsyncRead + AsyncWrite, + B: IntoBuf, { let inner = self.new_read(self.new_write(inner)); Framed { inner: inner } @@ -899,17 +917,16 @@ impl Builder { } fn get_num_skip(&self) -> usize { - self.num_skip.unwrap_or(self.length_field_offset + self.length_field_len) + self.num_skip + .unwrap_or(self.length_field_offset + self.length_field_len) } } - // ===== impl FrameTooBig ===== impl fmt::Debug for FrameTooBig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("FrameTooBig") - .finish() + f.debug_struct("FrameTooBig").finish() } } diff --git a/tokio-io/src/lib.rs b/tokio-io/src/lib.rs index 3d5ef788e..6df7f3c86 100644 --- a/tokio-io/src/lib.rs +++ b/tokio-io/src/lib.rs @@ -34,18 +34,21 @@ pub type IoStream = Box + Send>; /// it indicates `WouldBlock` or otherwise `Err` is returned. #[macro_export] macro_rules! try_nb { - ($e:expr) => (match $e { - Ok(t) => t, - Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => { - return Ok(::futures::Async::NotReady) + ($e:expr) => { + match $e { + Ok(t) => t, + Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => { + return Ok(::futures::Async::NotReady); + } + Err(e) => return Err(e.into()), } - Err(e) => return Err(e.into()), - }) + }; } -pub mod io; pub mod codec; +pub mod io; +pub mod _tokio_codec; mod allow_std; mod async_read; mod async_write; @@ -56,7 +59,6 @@ mod length_delimited; mod lines; mod split; mod window; -pub mod _tokio_codec; pub use self::async_read::AsyncRead; pub use self::async_write::AsyncWrite; diff --git a/tokio-io/src/lines.rs b/tokio-io/src/lines.rs index 6263a1607..8e59ff8fa 100644 --- a/tokio-io/src/lines.rs +++ b/tokio-io/src/lines.rs @@ -20,7 +20,8 @@ pub struct Lines { /// lines that the object contains. The returned stream will reach its end once /// `a` reaches EOF. pub fn lines(a: A) -> Lines - where A: AsyncRead + BufRead, +where + A: AsyncRead + BufRead, { Lines { io: a, @@ -39,7 +40,8 @@ impl Lines { } impl Stream for Lines - where A: AsyncRead + BufRead, +where + A: AsyncRead + BufRead, { type Item = String; type Error = io::Error; @@ -47,7 +49,7 @@ impl Stream for Lines fn poll(&mut self) -> Poll, io::Error> { let n = try_nb!(self.io.read_line(&mut self.line)); if n == 0 && self.line.len() == 0 { - return Ok(None.into()) + return Ok(None.into()); } if self.line.ends_with("\n") { self.line.pop(); diff --git a/tokio-io/src/split.rs b/tokio-io/src/split.rs index bd69d2008..7f743e8f7 100644 --- a/tokio-io/src/split.rs +++ b/tokio-io/src/split.rs @@ -1,8 +1,8 @@ use std::io::{self, Read, Write}; -use futures::{Async, Poll}; -use futures::sync::BiLock; use bytes::{Buf, BufMut}; +use futures::sync::BiLock; +use futures::{Async, Poll}; use {AsyncRead, AsyncWrite}; @@ -66,7 +66,8 @@ impl AsyncWrite for WriteHalf { } fn write_buf(&mut self, buf: &mut B) -> Poll - where Self: Sized, + where + Self: Sized, { let mut l = try_ready!(wrap_as_io(self.handle.poll_lock())); l.write_buf(buf) @@ -83,8 +84,8 @@ mod tests { use super::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf}; use bytes::{BytesMut, IntoBuf}; - use futures::{Async, Poll, future::lazy, future::ok}; use futures::sync::BiLock; + use futures::{future::lazy, future::ok, Async, Poll}; use std::io::{self, Read, Write}; @@ -138,7 +139,8 @@ mod tests { assert!(rx.read_buf(&mut buf).unwrap().is_ready()); ok::<(), ()>(()) - })).unwrap(); + })) + .unwrap(); } #[test] @@ -166,6 +168,7 @@ mod tests { assert!(tx.write_buf(&mut buf).unwrap().is_ready()); ok::<(), ()>(()) - })).unwrap(); + })) + .unwrap(); } } diff --git a/tokio-io/tests/async_read.rs b/tokio-io/tests/async_read.rs index 7aa9b1d21..604e99fd4 100644 --- a/tokio-io/tests/async_read.rs +++ b/tokio-io/tests/async_read.rs @@ -1,10 +1,10 @@ -extern crate tokio_io; extern crate bytes; extern crate futures; +extern crate tokio_io; -use tokio_io::AsyncRead; -use bytes::{BytesMut, BufMut}; +use bytes::{BufMut, BytesMut}; use futures::Async; +use tokio_io::AsyncRead; use std::io::{self, Read}; diff --git a/tokio-io/tests/length_delimited.rs b/tokio-io/tests/length_delimited.rs index f3796654a..c99bbf089 100644 --- a/tokio-io/tests/length_delimited.rs +++ b/tokio-io/tests/length_delimited.rs @@ -1,17 +1,17 @@ // This file is testing deprecated code. #![allow(deprecated)] -extern crate tokio_io; extern crate futures; +extern crate tokio_io; -use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::length_delimited::*; +use tokio_io::{AsyncRead, AsyncWrite}; -use futures::{Stream, Sink, Poll}; use futures::Async::*; +use futures::{Poll, Sink, Stream}; -use std::io; use std::collections::VecDeque; +use std::io; macro_rules! mock { ($($x:expr,)*) => {{ @@ -21,7 +21,6 @@ macro_rules! mock { }}; } - #[test] fn read_empty_io_yields_nothing() { let mut io = FramedRead::new(mock!()); @@ -41,11 +40,9 @@ fn read_single_frame_one_packet() { #[test] fn read_single_frame_one_packet_little_endian() { - let mut io = Builder::new() - .little_endian() - .new_read(mock! { - Ok(b"\x09\x00\x00\x00abcdefghi"[..].into()), - }); + let mut io = Builder::new().little_endian().new_read(mock! { + Ok(b"\x09\x00\x00\x00abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(None)); @@ -58,11 +55,9 @@ fn read_single_frame_one_packet_native_endian() { } else { b"\x09\x00\x00\x00abcdefghi" }; - let mut io = Builder::new() - .native_endian() - .new_read(mock! { - Ok(data[..].into()), - }); + let mut io = Builder::new().native_endian().new_read(mock! { + Ok(data[..].into()), + }); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(None)); @@ -146,7 +141,6 @@ fn read_multi_frame_multi_packet_wait() { Err(would_block()), }); - assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), NotReady); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); @@ -196,22 +190,19 @@ fn read_incomplete_payload() { #[test] fn read_max_frame_len() { - let mut io = Builder::new() - .max_frame_length(5) - .new_read(mock! { - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }); + let mut io = Builder::new().max_frame_length(5).new_read(mock! { + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap_err().kind(), io::ErrorKind::InvalidData); } #[test] fn read_update_max_frame_len_at_rest() { - let mut io = Builder::new() - .new_read(mock! { - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }); + let mut io = Builder::new().new_read(mock! { + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); io.set_max_frame_length(5); @@ -220,13 +211,12 @@ fn read_update_max_frame_len_at_rest() { #[test] fn read_update_max_frame_len_in_flight() { - let mut io = Builder::new() - .new_read(mock! { - Ok(b"\x00\x00\x00\x09abcd"[..].into()), - Err(would_block()), - Ok(b"efghi"[..].into()), - Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), - }); + let mut io = Builder::new().new_read(mock! { + Ok(b"\x00\x00\x00\x09abcd"[..].into()), + Err(would_block()), + Ok(b"efghi"[..].into()), + Ok(b"\x00\x00\x00\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), NotReady); io.set_max_frame_length(5); @@ -236,11 +226,9 @@ fn read_update_max_frame_len_in_flight() { #[test] fn read_one_byte_length_field() { - let mut io = Builder::new() - .length_field_length(1) - .new_read(mock! { - Ok(b"\x09abcdefghi"[..].into()), - }); + let mut io = Builder::new().length_field_length(1).new_read(mock! { + Ok(b"\x09abcdefghi"[..].into()), + }); assert_eq!(io.poll().unwrap(), Ready(Some(b"abcdefghi"[..].into()))); assert_eq!(io.poll().unwrap(), Ready(None)); @@ -275,9 +263,15 @@ fn read_single_multi_frame_one_packet_skip_none_adjusted() { Ok(data.into()), }); - assert_eq!(io.poll().unwrap(), Ready(Some(b"xx\x00\x09abcdefghi"[..].into()))); + assert_eq!( + io.poll().unwrap(), + Ready(Some(b"xx\x00\x09abcdefghi"[..].into())) + ); assert_eq!(io.poll().unwrap(), Ready(Some(b"yy\x00\x03123"[..].into()))); - assert_eq!(io.poll().unwrap(), Ready(Some(b"zz\x00\x0bhello world"[..].into()))); + assert_eq!( + io.poll().unwrap(), + Ready(Some(b"zz\x00\x0bhello world"[..].into())) + ); assert_eq!(io.poll().unwrap(), Ready(None)); } @@ -303,13 +297,11 @@ fn read_single_multi_frame_one_packet_length_includes_head() { #[test] fn write_single_frame_length_adjusted() { - let mut io = Builder::new() - .length_adjustment(-2) - .new_write(mock! { - Ok(b"\x00\x00\x00\x0b"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - }); + let mut io = Builder::new().length_adjustment(-2).new_write(mock! { + Ok(b"\x00\x00\x00\x0b"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + }); assert!(io.start_send("abcdefghi").unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); assert!(io.get_ref().calls.is_empty()); @@ -397,29 +389,24 @@ fn write_single_frame_would_block() { #[test] fn write_single_frame_little_endian() { - let mut io = Builder::new() - .little_endian() - .new_write(mock! { - Ok(b"\x09\x00\x00\x00"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - }); + let mut io = Builder::new().little_endian().new_write(mock! { + Ok(b"\x09\x00\x00\x00"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + }); assert!(io.start_send("abcdefghi").unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); assert!(io.get_ref().calls.is_empty()); } - #[test] fn write_single_frame_with_short_length_field() { - let mut io = Builder::new() - .length_field_length(1) - .new_write(mock! { - Ok(b"\x09"[..].into()), - Ok(b"abcdefghi"[..].into()), - Ok(Flush), - }); + let mut io = Builder::new().length_field_length(1).new_write(mock! { + Ok(b"\x09"[..].into()), + Ok(b"abcdefghi"[..].into()), + Ok(Flush), + }); assert!(io.start_send("abcdefghi").unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); @@ -428,56 +415,63 @@ fn write_single_frame_with_short_length_field() { #[test] fn write_max_frame_len() { - let mut io = Builder::new() - .max_frame_length(5) - .new_write(mock! { }); + let mut io = Builder::new().max_frame_length(5).new_write(mock! {}); - assert_eq!(io.start_send("abcdef").unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send("abcdef").unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_zero() { - let mut io = Builder::new() - .new_write(mock! { }); + let mut io = Builder::new().new_write(mock! {}); assert!(io.start_send("abcdef").unwrap().is_ready()); - assert_eq!(io.poll_complete().unwrap_err().kind(), io::ErrorKind::WriteZero); + assert_eq!( + io.poll_complete().unwrap_err().kind(), + io::ErrorKind::WriteZero + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_update_max_frame_len_at_rest() { - let mut io = Builder::new() - .new_write(mock! { - Ok(b"\x00\x00\x00\x06"[..].into()), - Ok(b"abcdef"[..].into()), - Ok(Flush), - }); + let mut io = Builder::new().new_write(mock! { + Ok(b"\x00\x00\x00\x06"[..].into()), + Ok(b"abcdef"[..].into()), + Ok(Flush), + }); assert!(io.start_send("abcdef").unwrap().is_ready()); assert!(io.poll_complete().unwrap().is_ready()); io.set_max_frame_length(5); - assert_eq!(io.start_send("abcdef").unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send("abcdef").unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } #[test] fn write_update_max_frame_len_in_flight() { - let mut io = Builder::new() - .new_write(mock! { - Ok(b"\x00\x00\x00\x06"[..].into()), - Ok(b"ab"[..].into()), - Err(would_block()), - Ok(b"cdef"[..].into()), - Ok(Flush), - }); + let mut io = Builder::new().new_write(mock! { + Ok(b"\x00\x00\x00\x06"[..].into()), + Ok(b"ab"[..].into()), + Err(would_block()), + Ok(b"cdef"[..].into()), + Ok(Flush), + }); assert!(io.start_send("abcdef").unwrap().is_ready()); assert!(!io.poll_complete().unwrap().is_ready()); io.set_max_frame_length(5); assert!(io.poll_complete().unwrap().is_ready()); - assert_eq!(io.start_send("abcdef").unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!( + io.start_send("abcdef").unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); assert!(io.get_ref().calls.is_empty()); } @@ -513,8 +507,7 @@ impl io::Read for Mock { } } -impl AsyncRead for Mock { -} +impl AsyncRead for Mock {} impl io::Write for Mock { fn write(&mut self, src: &[u8]) -> io::Result { @@ -533,9 +526,7 @@ impl io::Write for Mock { fn flush(&mut self) -> io::Result<()> { match self.calls.pop_front() { - Some(Ok(Op::Flush)) => { - Ok(()) - } + Some(Ok(Op::Flush)) => Ok(()), Some(Ok(_)) => panic!(), Some(Err(e)) => Err(e), None => Ok(()), diff --git a/tokio-reactor/benches/basic.rs b/tokio-reactor/benches/basic.rs index c5150f20a..63020d2f7 100644 --- a/tokio-reactor/benches/basic.rs +++ b/tokio-reactor/benches/basic.rs @@ -16,10 +16,10 @@ mod threadpool { use super::*; use std::sync::mpsc; - use test::Bencher; use futures::{future, Async}; - use tokio_reactor::Registration; + use test::Bencher; use tokio::runtime::Runtime; + use tokio_reactor::Registration; #[bench] fn notify_many(b: &mut Bencher) { @@ -42,22 +42,20 @@ mod threadpool { let mut r = Some(r); let tx = tx.clone(); - tokio::spawn(future::poll_fn(move || { - loop { - let is_ready = registration.poll_read_ready().unwrap().is_ready(); + tokio::spawn(future::poll_fn(move || loop { + let is_ready = registration.poll_read_ready().unwrap().is_ready(); - if is_ready { - rem -= 1; + if is_ready { + rem -= 1; - if rem == 0 { - r.take().unwrap(); - tx.send(()).unwrap(); - return Ok(Async::Ready(())); - } - } else { - s.set_readiness(mio::Ready::readable()).unwrap(); - return Ok(Async::NotReady); + if rem == 0 { + r.take().unwrap(); + tx.send(()).unwrap(); + return Ok(Async::Ready(())); } + } else { + s.set_readiness(mio::Ready::readable()).unwrap(); + return Ok(Async::NotReady); } })); @@ -66,7 +64,8 @@ mod threadpool { } Ok(()) - })).unwrap(); + })) + .unwrap(); for _ in 0..tasks { rx.recv().unwrap(); @@ -105,22 +104,20 @@ mod io_pool { let mut r = Some(r); let tx = tx.clone(); - tokio::spawn(future::poll_fn(move || { - loop { - let is_ready = registration.poll_read_ready().unwrap().is_ready(); + tokio::spawn(future::poll_fn(move || loop { + let is_ready = registration.poll_read_ready().unwrap().is_ready(); - if is_ready { - rem -= 1; + if is_ready { + rem -= 1; - if rem == 0 { - r.take().unwrap(); - tx.send(()).unwrap(); - return Ok(Async::Ready(())); - } - } else { - s.set_readiness(mio::Ready::readable()).unwrap(); - return Ok(Async::NotReady); + if rem == 0 { + r.take().unwrap(); + tx.send(()).unwrap(); + return Ok(Async::Ready(())); } + } else { + s.set_readiness(mio::Ready::readable()).unwrap(); + return Ok(Async::NotReady); } })); @@ -129,7 +126,8 @@ mod io_pool { } Ok(()) - })).unwrap(); + })) + .unwrap(); for _ in 0..tasks { rx.recv().unwrap(); diff --git a/tokio-reactor/src/background.rs b/tokio-reactor/src/background.rs index 36eb88de0..d4bfb78aa 100644 --- a/tokio-reactor/src/background.rs +++ b/tokio-reactor/src/background.rs @@ -1,12 +1,12 @@ -use {AtomicTask, Reactor, Handle}; +use {AtomicTask, Handle, Reactor}; -use futures::{Future, Async, Poll, task}; +use futures::{task, Async, Future, Poll}; use std::io; -use std::thread; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; +use std::thread; /// Handle to the reactor running on a background thread. /// @@ -72,14 +72,10 @@ impl Background { let shared2 = shared.clone(); // Start the reactor thread - thread::Builder::new() - .spawn(move || run(reactor, shared2))?; + thread::Builder::new().spawn(move || run(reactor, shared2))?; Ok(Background { - inner: Some(Inner { - handle, - shared, - }), + inner: Some(Inner { handle, shared }), }) } @@ -157,9 +153,10 @@ impl Inner { /// Notify the reactor thread to shutdown once the reactor transitions to an /// idle state. fn shutdown_on_idle(&self) { - self.shared.shutdown - .compare_and_swap(0, SHUTDOWN_IDLE, SeqCst); - self.handle.wakeup(); + self.shared + .shutdown + .compare_and_swap(0, SHUTDOWN_IDLE, SeqCst); + self.handle.wakeup(); } /// Notify the reactor thread to shutdown immediately. @@ -171,7 +168,9 @@ impl Inner { return; } - let act = self.shared.shutdown + let act = self + .shared + .shutdown .compare_and_swap(curr, SHUTDOWN_NOW, SeqCst); if act == curr { diff --git a/tokio-reactor/src/lib.rs b/tokio-reactor/src/lib.rs index cb83d37bf..e2c9d5d86 100644 --- a/tokio-reactor/src/lib.rs +++ b/tokio-reactor/src/lib.rs @@ -53,29 +53,29 @@ mod sharded_rwlock; // ===== Public re-exports ===== pub use self::background::{Background, Shutdown}; -pub use self::registration::Registration; pub use self::poll_evented::PollEvented; +pub use self::registration::Registration; // ===== Private imports ===== use sharded_rwlock::RwLock; use futures::task::Task; -use tokio_executor::Enter; use tokio_executor::park::{Park, Unpark}; +use tokio_executor::Enter; use tokio_sync::task::AtomicTask; -use std::{fmt, usize}; +use std::cell::RefCell; use std::error::Error; use std::io; use std::mem; -use std::cell::RefCell; -use std::sync::atomic::Ordering::{Relaxed, SeqCst}; -use std::sync::atomic::AtomicUsize; -use std::sync::{Arc, Weak}; -use std::time::{Duration, Instant}; #[cfg(all(unix, not(target_os = "fuchsia")))] use std::os::unix::io::{AsRawFd, RawFd}; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::{Relaxed, SeqCst}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; +use std::{fmt, usize}; use log::Level; use mio::event::Evented; @@ -150,7 +150,7 @@ struct Inner { io_dispatch: RwLock>, /// Used to wake up the reactor from a call to `turn` - wakeup: mio::SetReadiness + wakeup: mio::SetReadiness, } struct ScheduledIo { @@ -169,7 +169,7 @@ pub(crate) enum Direction { /// The global fallback reactor. static HANDLE_FALLBACK: AtomicUsize = AtomicUsize::new(0); -thread_local!{ +thread_local! { /// Tracks the reactor for the current execution context. static CURRENT_REACTOR: RefCell> = RefCell::new(None) } @@ -194,7 +194,8 @@ fn _assert_kinds() { /// /// This function panics if there already is a default reactor set. pub fn with_default(handle: &Handle, enter: &mut Enter, f: F) -> R -where F: FnOnce(&mut Enter) -> R +where + F: FnOnce(&mut Enter) -> R, { // Ensure that the executor is removed from the thread-local context // when leaving the scope. This handles cases that involve panicking. @@ -217,8 +218,11 @@ where F: FnOnce(&mut Enter) -> R { let mut current = current.borrow_mut(); - assert!(current.is_none(), "default Tokio reactor already set \ - for execution context"); + assert!( + current.is_none(), + "default Tokio reactor already set \ + for execution context" + ); let handle = match handle.as_priv() { Some(handle) => handle, @@ -241,10 +245,12 @@ impl Reactor { let io = mio::Poll::new()?; let wakeup_pair = mio::Registration::new2(); - io.register(&wakeup_pair.0, - TOKEN_WAKEUP, - mio::Ready::readable(), - mio::PollOpt::level())?; + io.register( + &wakeup_pair.0, + TOKEN_WAKEUP, + mio::Ready::readable(), + mio::PollOpt::level(), + )?; Ok(Reactor { events: mio::Events::with_capacity(1024), @@ -335,9 +341,7 @@ impl Reactor { /// Idle is defined as all tasks that have been spawned have completed, /// either successfully or with an error. pub fn is_idle(&self) -> bool { - self.inner.io_dispatch - .read() - .is_empty() + self.inner.io_dispatch.read().is_empty() } /// Run this reactor on a background thread. @@ -372,7 +376,10 @@ impl Reactor { trace!("event {:?} {:?}", event.readiness(), event.token()); if token == TOKEN_WAKEUP { - self.inner.wakeup.set_readiness(mio::Ready::empty()).unwrap(); + self.inner + .wakeup + .set_readiness(mio::Ready::empty()) + .unwrap(); } else { self.dispatch(token, event.readiness()); } @@ -380,10 +387,12 @@ impl Reactor { if let Some(start) = start { let dur = start.elapsed(); - trace!("loop process - {} events, {}.{:03}s", - events, - dur.as_secs(), - dur.subsec_nanos() / 1_000_000); + trace!( + "loop process - {} events, {}.{:03}s", + events, + dur.as_secs(), + dur.subsec_nanos() / 1_000_000 + ); } Ok(()) @@ -475,9 +484,7 @@ impl Handle { inner: Some(handle), }) .unwrap_or(Handle { - inner: Some(HandlePriv { - inner: Weak::new(), - }) + inner: Some(HandlePriv { inner: Weak::new() }), }) } @@ -537,11 +544,9 @@ impl HandlePriv { /// /// Returns `Err` if no handle is found. pub(crate) fn try_current() -> io::Result { - CURRENT_REACTOR.with(|current| { - match *current.borrow() { - Some(ref handle) => Ok(handle.clone()), - None => HandlePriv::fallback(), - } + CURRENT_REACTOR.with(|current| match *current.borrow() { + Some(ref handle) => Ok(handle.clone()), + None => HandlePriv::fallback(), }) } @@ -557,8 +562,12 @@ impl HandlePriv { if fallback == 0 { let reactor = match Reactor::new() { Ok(reactor) => reactor, - Err(_) => return Err(io::Error::new(io::ErrorKind::Other, - "failed to create reactor")), + Err(_) => { + return Err(io::Error::new( + io::ErrorKind::Other, + "failed to create reactor", + )); + } }; // If we successfully set ourselves as the actual fallback then we @@ -618,9 +627,7 @@ impl HandlePriv { } fn into_usize(self) -> usize { - unsafe { - mem::transmute::, usize>(self.inner) - } + unsafe { mem::transmute::, usize>(self.inner) } } unsafe fn from_usize(val: usize) -> HandlePriv { @@ -645,9 +652,7 @@ impl Inner { /// Register an I/O resource with the reactor. /// /// The registration token is returned. - fn add_source(&self, source: &Evented) - -> io::Result - { + fn add_source(&self, source: &Evented) -> io::Result { // Get an ABA guard value let aba_guard = self.next_aba_guard.fetch_add(1 << TOKEN_SHIFT, Relaxed); @@ -656,8 +661,11 @@ impl Inner { let mut io_dispatch = self.io_dispatch.write(); if io_dispatch.len() == MAX_SOURCES { - return Err(io::Error::new(io::ErrorKind::Other, "reactor at max \ - registered I/O resources")); + return Err(io::Error::new( + io::ErrorKind::Other, + "reactor at max \ + registered I/O resources", + )); } io_dispatch.insert(ScheduledIo { @@ -671,10 +679,12 @@ impl Inner { let token = aba_guard | key; debug!("adding I/O source: {}", token); - self.io.register(source, - mio::Token(token), - mio::Ready::all(), - mio::PollOpt::edge())?; + self.io.register( + source, + mio::Token(token), + mio::Ready::all(), + mio::PollOpt::edge(), + )?; Ok(key) } @@ -735,8 +745,8 @@ impl Direction { #[cfg(unix)] mod platform { - use mio::Ready; use mio::unix::UnixReady; + use mio::Ready; pub fn hup() -> Ready { UnixReady::hup().into() diff --git a/tokio-reactor/src/poll_evented.rs b/tokio-reactor/src/poll_evented.rs index 2352a874a..230f7c342 100644 --- a/tokio-reactor/src/poll_evented.rs +++ b/tokio-reactor/src/poll_evented.rs @@ -140,11 +140,12 @@ macro_rules! poll_ready { Ok(mio::Ready::from_usize(cached).into()) } - }} + }}; } impl PollEvented -where E: Evented +where + E: Evented, { /// Creates a new `PollEvented` associated with the default reactor. pub fn new(io: E) -> PollEvented { @@ -154,7 +155,7 @@ where E: Evented registration: Registration::new(), read_readiness: AtomicUsize::new(0), write_readiness: AtomicUsize::new(0), - } + }, } } @@ -163,7 +164,8 @@ where E: Evented let ret = PollEvented::new(io); if let Some(handle) = handle.as_priv() { - ret.inner.registration + ret.inner + .registration .register_with_priv(ret.io.as_ref().unwrap(), handle)?; } @@ -220,7 +222,10 @@ where E: Evented pub fn poll_read_ready(&self, mask: mio::Ready) -> Poll { assert!(!mask.is_writable(), "cannot poll for write readiness"); poll_ready!( - self, mask, read_readiness, take_read_ready, + self, + mask, + read_readiness, + take_read_ready, self.inner.registration.poll_read_ready() ) } @@ -245,7 +250,9 @@ where E: Evented assert!(!ready.is_writable(), "cannot clear write readiness"); assert!(!::platform::is_hup(&ready), "cannot clear HUP readiness"); - self.inner.read_readiness.fetch_and(!ready.as_usize(), Relaxed); + self.inner + .read_readiness + .fetch_and(!ready.as_usize(), Relaxed); if self.poll_read_ready(ready)?.is_ready() { // Notify the current task @@ -299,7 +306,9 @@ where E: Evented pub fn clear_write_ready(&self) -> io::Result<()> { let ready = mio::Ready::writable(); - self.inner.write_readiness.fetch_and(!ready.as_usize(), Relaxed); + self.inner + .write_readiness + .fetch_and(!ready.as_usize(), Relaxed); if self.poll_write_ready()?.is_ready() { // Notify the current task @@ -311,7 +320,9 @@ where E: Evented /// Ensure that the I/O resource is registered with the reactor. fn register(&self) -> io::Result<()> { - self.inner.registration.register(self.io.as_ref().unwrap())?; + self.inner + .registration + .register(self.io.as_ref().unwrap())?; Ok(()) } } @@ -319,11 +330,12 @@ where E: Evented // ===== Read / Write impls ===== impl Read for PollEvented -where E: Evented + Read, +where + E: Evented + Read, { fn read(&mut self, buf: &mut [u8]) -> io::Result { if let Async::NotReady = self.poll_read_ready(mio::Ready::readable())? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().read(buf); @@ -332,16 +344,17 @@ where E: Evented + Read, self.clear_read_ready(mio::Ready::readable())?; } - return r + return r; } } impl Write for PollEvented -where E: Evented + Write, +where + E: Evented + Write, { fn write(&mut self, buf: &[u8]) -> io::Result { if let Async::NotReady = self.poll_write_ready()? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().write(buf); @@ -350,12 +363,12 @@ where E: Evented + Write, self.clear_write_ready()?; } - return r + return r; } fn flush(&mut self) -> io::Result<()> { if let Async::NotReady = self.poll_write_ready()? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_mut().flush(); @@ -364,17 +377,15 @@ where E: Evented + Write, self.clear_write_ready()?; } - return r + return r; } } -impl AsyncRead for PollEvented -where E: Evented + Read, -{ -} +impl AsyncRead for PollEvented where E: Evented + Read {} impl AsyncWrite for PollEvented -where E: Evented + Write, +where + E: Evented + Write, { fn shutdown(&mut self) -> Poll<(), io::Error> { Ok(().into()) @@ -384,11 +395,13 @@ where E: Evented + Write, // ===== &'a Read / &'a Write impls ===== impl<'a, E> Read for &'a PollEvented -where E: Evented, &'a E: Read, +where + E: Evented, + &'a E: Read, { fn read(&mut self, buf: &mut [u8]) -> io::Result { if let Async::NotReady = self.poll_read_ready(mio::Ready::readable())? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_ref().read(buf); @@ -397,16 +410,18 @@ where E: Evented, &'a E: Read, self.clear_read_ready(mio::Ready::readable())?; } - return r + return r; } } impl<'a, E> Write for &'a PollEvented -where E: Evented, &'a E: Write, +where + E: Evented, + &'a E: Write, { fn write(&mut self, buf: &[u8]) -> io::Result { if let Async::NotReady = self.poll_write_ready()? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_ref().write(buf); @@ -415,12 +430,12 @@ where E: Evented, &'a E: Write, self.clear_write_ready()?; } - return r + return r; } fn flush(&mut self) -> io::Result<()> { if let Async::NotReady = self.poll_write_ready()? { - return Err(io::ErrorKind::WouldBlock.into()) + return Err(io::ErrorKind::WouldBlock.into()); } let r = self.get_ref().flush(); @@ -429,17 +444,21 @@ where E: Evented, &'a E: Write, self.clear_write_ready()?; } - return r + return r; } } impl<'a, E> AsyncRead for &'a PollEvented -where E: Evented, &'a E: Read, +where + E: Evented, + &'a E: Read, { } impl<'a, E> AsyncWrite for &'a PollEvented -where E: Evented, &'a E: Write, +where + E: Evented, + &'a E: Write, { fn shutdown(&mut self) -> Poll<(), io::Error> { Ok(().into()) @@ -455,9 +474,7 @@ fn is_wouldblock(r: &io::Result) -> bool { impl fmt::Debug for PollEvented { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("PollEvented") - .field("io", &self.io) - .finish() + f.debug_struct("PollEvented").field("io", &self.io).finish() } } diff --git a/tokio-reactor/src/registration.rs b/tokio-reactor/src/registration.rs index 1ef843ec5..4ad9f0861 100644 --- a/tokio-reactor/src/registration.rs +++ b/tokio-reactor/src/registration.rs @@ -1,12 +1,12 @@ -use {Handle, HandlePriv, Direction, Task}; +use {Direction, Handle, HandlePriv, Task}; -use futures::{Async, Poll, task}; +use futures::{task, Async, Poll}; use mio::{self, Evented}; -use std::{io, ptr, usize}; use std::cell::UnsafeCell; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::{io, ptr, usize}; /// Associates an I/O resource with the reactor instance that drives it. /// @@ -118,7 +118,8 @@ impl Registration { /// /// If an error is encountered during registration, `Err` is returned. pub fn register(&self, io: &T) -> io::Result - where T: Evented, + where + T: Evented, { self.register2(io, || HandlePriv::try_current()) } @@ -140,7 +141,8 @@ impl Registration { /// /// `Err` is returned if an error is encountered. pub fn deregister(&mut self, io: &T) -> io::Result<()> - where T: Evented, + where + T: Evented, { // The state does not need to be checked and coordination is not // necessary as this function takes `&mut self`. This guarantees a @@ -165,25 +167,26 @@ impl Registration { /// /// If an error is encountered during registration, `Err` is returned. pub fn register_with(&self, io: &T, handle: &Handle) -> io::Result - where T: Evented, + where + T: Evented, { - self.register2(io, || { - match handle.as_priv() { - Some(handle) => Ok(handle.clone()), - None => HandlePriv::try_current(), - } + self.register2(io, || match handle.as_priv() { + Some(handle) => Ok(handle.clone()), + None => HandlePriv::try_current(), }) } pub(crate) fn register_with_priv(&self, io: &T, handle: &HandlePriv) -> io::Result - where T: Evented, + where + T: Evented, { self.register2(io, || Ok(handle.clone())) } fn register2(&self, io: &T, f: F) -> io::Result - where T: Evented, - F: Fn() -> io::Result, + where + T: Evented, + F: Fn() -> io::Result, { let mut state = self.state.load(SeqCst); @@ -204,7 +207,9 @@ impl Registration { // Create the actual registration let (inner, res) = Inner::new(io, handle); - unsafe { *self.inner.get() = Some(inner); } + unsafe { + *self.inner.get() = Some(inner); + } // Transition out of the locked state. This acquires the // current value, potentially having a list of tasks that @@ -298,7 +303,6 @@ impl Registration { /// [`poll_read_ready`]: #method.poll_read_ready pub fn take_read_ready(&self) -> io::Result> { self.poll_ready(Direction::Read, Notify::No) - } /// Poll for events on the I/O resource's write readiness stream. @@ -352,9 +356,7 @@ impl Registration { self.poll_ready(Direction::Write, Notify::No) } - fn poll_ready(&self, direction: Direction, notify: Notify) - -> io::Result> - { + fn poll_ready(&self, direction: Direction, notify: Notify) -> io::Result> { let mut state = self.state.load(SeqCst); // Cache the node pointer @@ -363,8 +365,11 @@ impl Registration { loop { match state { INIT => { - return Err(io::Error::new(io::ErrorKind::Other, "must call `register` - before poll_read_ready")); + return Err(io::Error::new( + io::ErrorKind::Other, + "must call `register` + before poll_read_ready", + )); } READY => { let inner = unsafe { (*self.inner.get()).as_ref().unwrap() }; @@ -422,7 +427,8 @@ unsafe impl Sync for Registration {} impl Inner { fn new(io: &T, handle: HandlePriv) -> (Self, io::Result<()>) - where T: Evented, + where + T: Evented, { let mut res = Ok(()); @@ -440,10 +446,7 @@ impl Inner { } }; - let inner = Inner { - handle, - token, - }; + let inner = Inner { handle, token }; (inner, res) } @@ -467,7 +470,10 @@ impl Inner { fn deregister(&self, io: &E) -> io::Result<()> { if self.token == ERROR { - return Err(io::Error::new(io::ErrorKind::Other, "failed to associate with reactor")); + return Err(io::Error::new( + io::ErrorKind::Other, + "failed to associate with reactor", + )); } let inner = match self.handle.inner() { @@ -478,11 +484,12 @@ impl Inner { inner.deregister_source(io) } - fn poll_ready(&self, direction: Direction, notify: Notify) - -> io::Result> - { + fn poll_ready(&self, direction: Direction, notify: Notify) -> io::Result> { if self.token == ERROR { - return Err(io::Error::new(io::ErrorKind::Other, "failed to associate with reactor")); + return Err(io::Error::new( + io::ErrorKind::Other, + "failed to associate with reactor", + )); } let inner = match self.handle.inner() { @@ -504,8 +511,8 @@ impl Inner { // If HUP were to be cleared when `direction` is `Read`, then when // `poll_ready` is called again with a _`direction` of `Write`, the HUP // state would not be visible. - let mut ready = mask & mio::Ready::from_usize( - sched.readiness.fetch_and(!mask_no_hup, SeqCst)); + let mut ready = + mask & mio::Ready::from_usize(sched.readiness.fetch_and(!mask_no_hup, SeqCst)); if ready.is_empty() && notify == Notify::Yes { debug!("scheduling {:?} for: {}", direction, self.token); @@ -516,8 +523,7 @@ impl Inner { } // Try again - ready = mask & mio::Ready::from_usize( - sched.readiness.fetch_and(!mask_no_hup, SeqCst)); + ready = mask & mio::Ready::from_usize(sched.readiness.fetch_and(!mask_no_hup, SeqCst)); } if ready.is_empty() { diff --git a/tokio-signal/examples/multiple.rs b/tokio-signal/examples/multiple.rs index 98d6edb6a..fa8f1be25 100644 --- a/tokio-signal/examples/multiple.rs +++ b/tokio-signal/examples/multiple.rs @@ -23,8 +23,8 @@ mod platform { println!("Waiting for SIGINT or SIGTERM"); println!( " TIP: use `pkill -sigint multiple` from a second terminal \ - to send a SIGINT to all processes named 'multiple' \ - (i.e. this binary)" + to send a SIGINT to all processes named 'multiple' \ + (i.e. this binary)" ); let (item, _rest) = ::tokio::runtime::current_thread::block_on_all(stream.into_future()) .map_err(|_| "failed to wait for signals")?; @@ -44,7 +44,9 @@ mod platform { #[cfg(not(unix))] mod platform { - pub fn main() -> Result<(), Box<::std::error::Error>> {Ok(())} + pub fn main() -> Result<(), Box<::std::error::Error>> { + Ok(()) + } } fn main() -> Result<(), Box> { diff --git a/tokio-signal/examples/sighup-example.rs b/tokio-signal/examples/sighup-example.rs index 34c7e5600..5edb78624 100644 --- a/tokio-signal/examples/sighup-example.rs +++ b/tokio-signal/examples/sighup-example.rs @@ -16,8 +16,8 @@ mod platform { println!("Waiting for SIGHUPS (Ctrl+C to quit)"); println!( " TIP: use `pkill -sighup sighup-example` from a second terminal \ - to send a SIGHUP to all processes named 'sighup-example' \ - (i.e. this binary)" + to send a SIGHUP to all processes named 'sighup-example' \ + (i.e. this binary)" ); // for_each is a powerful primitive provided by the Futures crate @@ -26,8 +26,8 @@ mod platform { let future = stream.for_each(|the_signal| { println!( "*Got signal {:#x}* I should probably reload my config \ - or something", - the_signal + or something", + the_signal ); Ok(()) }); @@ -43,7 +43,9 @@ mod platform { #[cfg(not(unix))] mod platform { - pub fn main() -> Result<(), Box<::std::error::Error>> {Ok(())} + pub fn main() -> Result<(), Box<::std::error::Error>> { + Ok(()) + } } fn main() -> Result<(), Box> { diff --git a/tokio-signal/src/unix.rs b/tokio-signal/src/unix.rs index 582f62337..8487a114d 100644 --- a/tokio-signal/src/unix.rs +++ b/tokio-signal/src/unix.rs @@ -10,8 +10,8 @@ extern crate mio; extern crate mio_uds; extern crate signal_hook; -use std::io::{self, Error, ErrorKind}; use std::io::prelude::*; +use std::io::{self, Error, ErrorKind}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, Once, ONCE_INIT}; @@ -21,24 +21,28 @@ use futures::future; use futures::sync::mpsc::{channel, Receiver, Sender}; use futures::{Async, Future}; use futures::{Poll, Stream}; -use tokio_reactor::{Handle, PollEvented}; use tokio_io::IoFuture; +use tokio_reactor::{Handle, PollEvented}; -pub use self::libc::{SIGUSR1, SIGUSR2, SIGINT, SIGTERM}; pub use self::libc::{SIGALRM, SIGHUP, SIGPIPE, SIGQUIT, SIGTRAP}; +pub use self::libc::{SIGINT, SIGTERM, SIGUSR1, SIGUSR2}; /// BSD-specific definitions #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd", +))] +pub mod bsd { + #[cfg(any( target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", - target_os = "openbsd", -))] -pub mod bsd { - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", target_os = "netbsd", - target_os = "openbsd"))] + target_os = "openbsd" + ))] pub use super::libc::SIGINFO; } @@ -150,7 +154,10 @@ fn action(slot: &SignalInfo, mut sender: &UnixStream) { /// returning any error along the way if that fails. fn signal_enable(signal: c_int) -> io::Result<()> { if signal_hook::FORBIDDEN.contains(&signal) { - return Err(Error::new(ErrorKind::Other, format!("Refusing to register signal {}", signal))); + return Err(Error::new( + ErrorKind::Other, + format!("Refusing to register signal {}", signal), + )); } let globals = globals(); @@ -173,7 +180,10 @@ fn signal_enable(signal: c_int) -> io::Result<()> { if siginfo.initialized.load(Ordering::Relaxed) { Ok(()) } else { - Err(Error::new(ErrorKind::Other, "Failed to register signal handler")) + Err(Error::new( + ErrorKind::Other, + "Failed to register signal handler", + )) } } @@ -214,9 +224,7 @@ impl Driver { let stream = globals().receiver.try_clone()?; let wakeup = PollEvented::new_with_handle(stream, handle)?; - Ok(Driver { - wakeup: wakeup, - }) + Ok(Driver { wakeup: wakeup }) } /// Drain all data in the global receiver, ensuring we'll get woken up when @@ -229,7 +237,7 @@ impl Driver { loop { match self.wakeup.read(&mut [0; 128]) { Ok(0) => panic!("EOF on self-pipe"), - Ok(_) => {}, + Ok(_) => {} Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => break, Err(e) => panic!("Bad read on self-pipe: {}", e), } @@ -257,10 +265,10 @@ impl Driver { // has gone away then we can remove that slot. for i in (0..recipients.len()).rev() { match recipients[i].try_send(signum) { - Ok(()) => {}, + Ok(()) => {} Err(ref e) if e.is_disconnected() => { recipients.swap_remove(i); - }, + } // Channel is full, ignore the error since the // receiver has already been woken up @@ -268,7 +276,7 @@ impl Driver { // Sanity check in case this error type ever gets // additional variants we have not considered. debug_assert!(e.is_full()); - }, + } } } } @@ -417,15 +425,19 @@ mod tests { #[test] fn dropped_signal_senders_are_cleaned_up() { - let mut rt = self::tokio::runtime::current_thread::Runtime::new() - .expect("failed to init runtime"); + let mut rt = + self::tokio::runtime::current_thread::Runtime::new().expect("failed to init runtime"); let signum = libc::SIGUSR1; - let signal = rt.block_on(Signal::new(signum)) + let signal = rt + .block_on(Signal::new(signum)) .expect("failed to create signal"); { - let recipients = globals().signals[signum as usize].recipients.lock().unwrap(); + let recipients = globals().signals[signum as usize] + .recipients + .lock() + .unwrap(); assert!(!recipients.is_empty()); } @@ -436,7 +448,10 @@ mod tests { } { - let recipients = globals().signals[signum as usize].recipients.lock().unwrap(); + let recipients = globals().signals[signum as usize] + .recipients + .lock() + .unwrap(); assert!(recipients.is_empty()); } } diff --git a/tokio-signal/src/windows.rs b/tokio-signal/src/windows.rs index a318483f3..c30f87362 100644 --- a/tokio-signal/src/windows.rs +++ b/tokio-signal/src/windows.rs @@ -15,15 +15,15 @@ use std::io; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Once, ONCE_INIT}; +use self::winapi::shared::minwindef::*; +use self::winapi::um::wincon::*; use futures::future; use futures::stream::Fuse; use futures::sync::mpsc; use futures::sync::oneshot; use futures::{Async, Future, IntoFuture, Poll, Stream}; -use tokio_reactor::{Handle, PollEvented}; use mio::Ready; -use self::winapi::shared::minwindef::*; -use self::winapi::um::wincon::*; +use tokio_reactor::{Handle, PollEvented}; use IoFuture; diff --git a/tokio-signal/tests/drop_multi_loop.rs b/tokio-signal/tests/drop_multi_loop.rs index 62d8da53f..7228281f4 100644 --- a/tokio-signal/tests/drop_multi_loop.rs +++ b/tokio-signal/tests/drop_multi_loop.rs @@ -10,14 +10,12 @@ const TEST_SIGNAL: libc::c_int = libc::SIGUSR1; #[test] fn dropping_loops_does_not_cause_starvation() { let (mut rt, signal) = { - let mut first_rt = CurrentThreadRuntime::new() - .expect("failed to init first runtime"); + let mut first_rt = CurrentThreadRuntime::new().expect("failed to init first runtime"); let first_signal = run_with_timeout(&mut first_rt, Signal::new(TEST_SIGNAL)) .expect("failed to register first signal"); - let mut second_rt = CurrentThreadRuntime::new() - .expect("failed to init second runtime"); + let mut second_rt = CurrentThreadRuntime::new().expect("failed to init second runtime"); let second_signal = run_with_timeout(&mut second_rt, Signal::new(TEST_SIGNAL)) .expect("failed to register second signal"); @@ -30,10 +28,7 @@ fn dropping_loops_does_not_cause_starvation() { send_signal(TEST_SIGNAL); - let signal_future = signal.into_future() - .map_err(|(e, _)| e); + let signal_future = signal.into_future().map_err(|(e, _)| e); - run_with_timeout(&mut rt, signal_future) - .expect("failed to get signal"); + run_with_timeout(&mut rt, signal_future).expect("failed to get signal"); } - diff --git a/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs b/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs index d8d3ee1d2..9ff289a55 100644 --- a/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs +++ b/tokio-signal/tests/dropping_does_not_deregister_other_instances.rs @@ -12,14 +12,13 @@ fn dropping_signal_does_not_deregister_any_other_instances() { // NB: Deadline requires a timer registration which is provided by // tokio's `current_thread::Runtime`, but isn't available by just using // tokio's default CurrentThread executor which powers `current_thread::block_on_all`. - let mut rt = CurrentThreadRuntime::new() - .expect("failed to init runtime"); + let mut rt = CurrentThreadRuntime::new().expect("failed to init runtime"); // NB: Testing for issue #38: signals should not starve based on ordering let first_duplicate_signal = run_with_timeout(&mut rt, Signal::new(TEST_SIGNAL)) .expect("failed to register first duplicate signal"); - let signal = run_with_timeout(&mut rt, Signal::new(TEST_SIGNAL)) - .expect("failed to register signal"); + let signal = + run_with_timeout(&mut rt, Signal::new(TEST_SIGNAL)).expect("failed to register signal"); let second_duplicate_signal = run_with_timeout(&mut rt, Signal::new(TEST_SIGNAL)) .expect("failed to register second duplicate signal"); diff --git a/tokio-signal/tests/multi_loop.rs b/tokio-signal/tests/multi_loop.rs index 31522abae..42643040e 100644 --- a/tokio-signal/tests/multi_loop.rs +++ b/tokio-signal/tests/multi_loop.rs @@ -22,7 +22,9 @@ fn multi_loop() { let mut rt = CurrentThreadRuntime::new().unwrap(); let signal = run_with_timeout(&mut rt, Signal::new(libc::SIGHUP)).unwrap(); sender.send(()).unwrap(); - run_with_timeout(&mut rt, signal.into_future()).ok().unwrap(); + run_with_timeout(&mut rt, signal.into_future()) + .ok() + .unwrap(); }) }) .collect(); diff --git a/tokio-signal/tests/notify_both.rs b/tokio-signal/tests/notify_both.rs index b45ff6701..b147324f3 100644 --- a/tokio-signal/tests/notify_both.rs +++ b/tokio-signal/tests/notify_both.rs @@ -8,11 +8,11 @@ use support::*; #[test] fn notify_both() { let mut rt = CurrentThreadRuntime::new().unwrap(); - let signal1 = run_with_timeout(&mut rt, Signal::new(libc::SIGUSR2)) - .expect("failed to create signal1"); + let signal1 = + run_with_timeout(&mut rt, Signal::new(libc::SIGUSR2)).expect("failed to create signal1"); - let signal2 = run_with_timeout(&mut rt, Signal::new(libc::SIGUSR2)) - .expect("failed to create signal2"); + let signal2 = + run_with_timeout(&mut rt, Signal::new(libc::SIGUSR2)).expect("failed to create signal2"); send_signal(libc::SIGUSR2); run_with_timeout(&mut rt, signal1.into_future().join(signal2.into_future())) diff --git a/tokio-signal/tests/signal.rs b/tokio-signal/tests/signal.rs index 05318e415..de47fed42 100644 --- a/tokio-signal/tests/signal.rs +++ b/tokio-signal/tests/signal.rs @@ -7,14 +7,11 @@ use support::*; #[test] fn tokio_simple() { - let signal_future = Signal::new(libc::SIGUSR1) - .and_then(|signal| { - send_signal(libc::SIGUSR1); - signal.into_future().map(|_| ()).map_err(|(err, _)| err) - }); + let signal_future = Signal::new(libc::SIGUSR1).and_then(|signal| { + send_signal(libc::SIGUSR1); + signal.into_future().map(|_| ()).map_err(|(err, _)| err) + }); - let mut rt = CurrentThreadRuntime::new() - .expect("failed to init runtime"); - run_with_timeout(&mut rt, signal_future) - .expect("failed"); + let mut rt = CurrentThreadRuntime::new().expect("failed to init runtime"); + run_with_timeout(&mut rt, signal_future).expect("failed"); } diff --git a/tokio-signal/tests/simple.rs b/tokio-signal/tests/simple.rs index d7b5f7920..2d98a02ff 100644 --- a/tokio-signal/tests/simple.rs +++ b/tokio-signal/tests/simple.rs @@ -8,8 +8,8 @@ use support::*; #[test] fn simple() { let mut rt = CurrentThreadRuntime::new().unwrap(); - let signal = run_with_timeout(&mut rt, Signal::new(libc::SIGUSR1)) - .expect("failed to create signal"); + let signal = + run_with_timeout(&mut rt, Signal::new(libc::SIGUSR1)).expect("failed to create signal"); send_signal(libc::SIGUSR1); diff --git a/tokio-signal/tests/support.rs b/tokio-signal/tests/support.rs index 942b6a09a..be0a7cda7 100644 --- a/tokio-signal/tests/support.rs +++ b/tokio-signal/tests/support.rs @@ -1,31 +1,33 @@ #![cfg(unix)] -extern crate libc; extern crate futures; +extern crate libc; extern crate tokio; extern crate tokio_signal; use self::libc::{c_int, getpid, kill}; -use std::time::Duration; use self::tokio::timer::Timeout; +use std::time::Duration; pub use self::futures::{Future, Stream}; pub use self::tokio::runtime::current_thread::{self, Runtime as CurrentThreadRuntime}; pub use self::tokio_signal::unix::Signal; pub fn with_timeout(future: F) -> impl Future { - Timeout::new(future, Duration::from_secs(1)) - .map_err(|e| if e.is_timer() { + Timeout::new(future, Duration::from_secs(1)).map_err(|e| { + if e.is_timer() { panic!("failed to register timer"); } else if e.is_elapsed() { panic!("timed out") } else { e.into_inner().expect("missing inner error") - }) + } + }) } pub fn run_with_timeout(rt: &mut CurrentThreadRuntime, future: F) -> Result - where F: Future +where + F: Future, { rt.block_on(with_timeout(future)) } diff --git a/tokio-signal/tests/twice.rs b/tokio-signal/tests/twice.rs index 33e36511d..c40326096 100644 --- a/tokio-signal/tests/twice.rs +++ b/tokio-signal/tests/twice.rs @@ -11,9 +11,13 @@ fn twice() { let signal = run_with_timeout(&mut rt, Signal::new(libc::SIGUSR1)).unwrap(); send_signal(libc::SIGUSR1); - let (num, signal) = run_with_timeout(&mut rt, signal.into_future()).ok().unwrap(); + let (num, signal) = run_with_timeout(&mut rt, signal.into_future()) + .ok() + .unwrap(); assert_eq!(num, Some(libc::SIGUSR1)); send_signal(libc::SIGUSR1); - run_with_timeout(&mut rt, signal.into_future()).ok().unwrap(); + run_with_timeout(&mut rt, signal.into_future()) + .ok() + .unwrap(); } diff --git a/tokio-sync/benches/mpsc.rs b/tokio-sync/benches/mpsc.rs index bb351d3e5..79822886e 100644 --- a/tokio-sync/benches/mpsc.rs +++ b/tokio-sync/benches/mpsc.rs @@ -1,15 +1,15 @@ #![feature(test)] #![cfg_attr(test, deny(warnings))] -extern crate tokio_sync; extern crate futures; extern crate test; +extern crate tokio_sync; mod tokio { - use tokio_sync::mpsc::*; - use futures::{future, Async, Future, Stream, Sink}; - use test::{self, Bencher}; + use futures::{future, Async, Future, Sink, Stream}; use std::thread; + use test::{self, Bencher}; + use tokio_sync::mpsc::*; #[bench] fn bounded_new(b: &mut Bencher) { @@ -46,7 +46,9 @@ mod tokio { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -58,7 +60,9 @@ mod tokio { assert!(tx.poll_ready().unwrap().is_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -71,7 +75,9 @@ mod tokio { assert!(tx.poll_ready().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -83,7 +89,9 @@ mod tokio { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -99,7 +107,9 @@ mod tokio { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -160,8 +170,7 @@ mod tokio { drop(tx); - let rx = rx.wait() - .take(4 * 1_000); + let rx = rx.wait().take(4 * 1_000); for v in rx { let _ = test::black_box(v); @@ -206,8 +215,7 @@ mod tokio { drop(tx); - let rx = rx.wait() - .take(THREADS * ITERS); + let rx = rx.wait().take(THREADS * ITERS); for v in rx { let _ = test::black_box(v); @@ -223,10 +231,10 @@ mod tokio { } mod legacy { - use futures::{future, Async, Future, Stream, Sink}; use futures::sync::mpsc::*; - use test::{self, Bencher}; + use futures::{future, Async, Future, Sink, Stream}; use std::thread; + use test::{self, Bencher}; #[bench] fn bounded_new(b: &mut Bencher) { @@ -263,7 +271,9 @@ mod legacy { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -275,7 +285,9 @@ mod legacy { assert!(tx.poll_ready().unwrap().is_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -288,7 +300,9 @@ mod legacy { assert!(tx.poll_ready().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -300,7 +314,9 @@ mod legacy { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -316,7 +332,9 @@ mod legacy { assert!(rx.poll().unwrap().is_not_ready()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }) } @@ -376,8 +394,7 @@ mod legacy { drop(tx); - let rx = rx.wait() - .take(4 * 1_000); + let rx = rx.wait().take(4 * 1_000); for v in rx { let _ = test::black_box(v); @@ -422,8 +439,7 @@ mod legacy { drop(tx); - let rx = rx.wait() - .take(THREADS * ITERS); + let rx = rx.wait().take(THREADS * ITERS); for v in rx { let _ = test::black_box(v); diff --git a/tokio-sync/benches/oneshot.rs b/tokio-sync/benches/oneshot.rs index 873eb1e80..b3170ce42 100644 --- a/tokio-sync/benches/oneshot.rs +++ b/tokio-sync/benches/oneshot.rs @@ -1,14 +1,14 @@ #![feature(test)] #![cfg_attr(test, deny(warnings))] -extern crate tokio_sync; extern crate futures; extern crate test; +extern crate tokio_sync; mod tokio { use futures::{future, Async, Future}; + use test::Bencher; use tokio_sync::oneshot; - use test::{Bencher}; #[bench] fn new(b: &mut Bencher) { @@ -43,7 +43,9 @@ mod tokio { assert_eq!(Async::Ready(1), rx.poll().unwrap()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }); } @@ -58,7 +60,7 @@ mod tokio { loop { match f.poll() { Ok(Ready(v)) => return Ok(v), - Ok(_) => {}, + Ok(_) => {} Err(e) => return Err(e), } } @@ -95,7 +97,9 @@ mod tokio { } Ok::<(), ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }); future::lazy(|| { @@ -112,14 +116,16 @@ mod tokio { }); Ok::<(), ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); } } mod legacy { - use futures::{future, Async, Future}; use futures::sync::oneshot; - use test::{Bencher}; + use futures::{future, Async, Future}; + use test::Bencher; #[bench] fn new(b: &mut Bencher) { @@ -154,7 +160,9 @@ mod legacy { assert_eq!(Async::Ready(1), rx.poll().unwrap()); Ok::<_, ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }); } @@ -169,7 +177,7 @@ mod legacy { loop { match f.poll() { Ok(Ready(v)) => return Ok(v), - Ok(_) => {}, + Ok(_) => {} Err(e) => return Err(e), } } @@ -206,7 +214,9 @@ mod legacy { } Ok::<(), ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); }); future::lazy(|| { @@ -223,6 +233,8 @@ mod legacy { }); Ok::<(), ()>(()) - }).wait().unwrap(); + }) + .wait() + .unwrap(); } } diff --git a/tokio-sync/src/lib.rs b/tokio-sync/src/lib.rs index c6ba15706..4cbbbc0ad 100644 --- a/tokio-sync/src/lib.rs +++ b/tokio-sync/src/lib.rs @@ -23,7 +23,7 @@ macro_rules! if_fuzz { } mod loom; -pub mod oneshot; pub mod mpsc; +pub mod oneshot; pub mod semaphore; pub mod task; diff --git a/tokio-sync/src/loom.rs b/tokio-sync/src/loom.rs index 5de8c1107..a4ec82b17 100644 --- a/tokio-sync/src/loom.rs +++ b/tokio-sync/src/loom.rs @@ -1,6 +1,6 @@ pub(crate) mod futures { pub(crate) use futures::task; - pub(crate) use ::task::AtomicTask; + pub(crate) use task::AtomicTask; } pub(crate) mod sync { diff --git a/tokio-sync/src/mpsc/block.rs b/tokio-sync/src/mpsc/block.rs index 912ceeb4a..b59ca5f2a 100644 --- a/tokio-sync/src/mpsc/block.rs +++ b/tokio-sync/src/mpsc/block.rs @@ -1,16 +1,13 @@ use loom::{ self, + sync::atomic::{AtomicPtr, AtomicUsize}, sync::CausalCell, - sync::atomic::{ - AtomicPtr, - AtomicUsize, - }, }; use std::mem::{self, ManuallyDrop}; use std::ops; use std::ptr::{self, NonNull}; -use std::sync::atomic::Ordering::{self, Acquire, Release, AcqRel}; +use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Release}; /// A block in a linked list. /// @@ -133,9 +130,7 @@ impl Block { } // Get the value - let value = self.values[offset].with(|ptr| { - ptr::read(ptr) - }); + let value = self.values[offset].with(|ptr| ptr::read(ptr)); Some(Read::Value(ManuallyDrop::into_inner(value))) } @@ -195,7 +190,8 @@ impl Block { pub(crate) unsafe fn tx_release(&self, tail_position: usize) { // Track the observed tail_position. Any sender targetting a greater // tail_position is guaranteed to not access this block. - self.observed_tail_position.with_mut(|ptr| *ptr = tail_position); + self.observed_tail_position + .with_mut(|ptr| *ptr = tail_position); // Set the released bit, signalling to the receiver that it is safe to // free the block's memory as soon as all slots **prior** to @@ -238,9 +234,8 @@ impl Block { let ret = NonNull::new(self.next.load(ordering)); debug_assert!(unsafe { - ret.map(|block| { - block.as_ref().start_index == self.start_index.wrapping_add(BLOCK_CAP) - }).unwrap_or(true) + ret.map(|block| block.as_ref().start_index == self.start_index.wrapping_add(BLOCK_CAP)) + .unwrap_or(true) }); ret @@ -262,14 +257,16 @@ impl Block { /// To maintain safety, the caller must ensure: /// /// * `block` is not freed until it has been removed from the list. - pub(crate) unsafe fn try_push(&self, block: &mut NonNull>, ordering: Ordering) - -> Result<(), NonNull>> - { - block.as_mut().start_index = - self.start_index.wrapping_add(BLOCK_CAP); + pub(crate) unsafe fn try_push( + &self, + block: &mut NonNull>, + ordering: Ordering, + ) -> Result<(), NonNull>> { + block.as_mut().start_index = self.start_index.wrapping_add(BLOCK_CAP); - let next_ptr = self.next.compare_and_swap( - ptr::null_mut(), block.as_ptr(), ordering); + let next_ptr = self + .next + .compare_and_swap(ptr::null_mut(), block.as_ptr(), ordering); match NonNull::new(next_ptr) { Some(next_ptr) => Err(next_ptr), @@ -295,12 +292,9 @@ impl Block { // Create the new block. It is assumed that the block will become the // next one after `&self`. If this turns out to not be the case, // `start_index` is updated accordingly. - let new_block = Box::new( - Block::new(self.start_index + BLOCK_CAP)); + let new_block = Box::new(Block::new(self.start_index + BLOCK_CAP)); - let mut new_block = unsafe { - NonNull::new_unchecked(Box::into_raw(new_block)) - }; + let mut new_block = unsafe { NonNull::new_unchecked(Box::into_raw(new_block)) }; // Attempt to store the block. The first compare-and-swap attempt is // "unrolled" due to minor differences in logic @@ -314,9 +308,11 @@ impl Block { // // `Release` ensures that the newly allocated block is available to // other threads acquiring the next pointer. - let next = NonNull::new( - self.next.compare_and_swap( - ptr::null_mut(), new_block.as_ptr(), AcqRel)); + let next = NonNull::new(self.next.compare_and_swap( + ptr::null_mut(), + new_block.as_ptr(), + AcqRel, + )); let next = match next { Some(next) => next, @@ -339,9 +335,7 @@ impl Block { // TODO: Should this iteration be capped? loop { - let actual = unsafe { - curr.as_ref().try_push(&mut new_block, AcqRel) - }; + let actual = unsafe { curr.as_ref().try_push(&mut new_block, AcqRel) }; curr = match actual { Ok(_) => { diff --git a/tokio-sync/src/mpsc/bounded.rs b/tokio-sync/src/mpsc/bounded.rs index 2b832d58e..0260c95ab 100644 --- a/tokio-sync/src/mpsc/bounded.rs +++ b/tokio-sync/src/mpsc/bounded.rs @@ -13,7 +13,9 @@ pub struct Sender { impl Clone for Sender { fn clone(&self) -> Self { - Sender { chan: self.chan.clone() } + Sender { + chan: self.chan.clone(), + } } } @@ -144,12 +146,10 @@ impl Stream for Receiver { type Error = RecvError; fn poll(&mut self) -> Poll, Self::Error> { - self.chan.recv() - .map_err(|_| RecvError(())) + self.chan.recv().map_err(|_| RecvError(())) } } - impl Sender { pub(crate) fn new(chan: chan::Tx) -> Sender { Sender { chan } @@ -176,8 +176,7 @@ impl Sender { /// capacity is available; /// - `Err(SendError)` if the receiver has been dropped. pub fn poll_ready(&mut self) -> Poll<(), SendError> { - self.chan.poll_ready() - .map_err(|_| SendError(())) + self.chan.poll_ready().map_err(|_| SendError(())) } /// Attempts to send a message on this `Sender`, returning the message @@ -193,17 +192,15 @@ impl Sink for Sender { type SinkError = SendError; fn start_send(&mut self, msg: T) -> StartSend { - use futures::AsyncSink; use futures::Async::*; + use futures::AsyncSink; match self.poll_ready()? { Ready(_) => { self.try_send(msg).map_err(|_| SendError(()))?; Ok(AsyncSink::Ready) } - NotReady => { - Ok(AsyncSink::NotReady(msg)) - } + NotReady => Ok(AsyncSink::NotReady(msg)), } } @@ -283,7 +280,7 @@ impl From<(T, chan::TrySendError)> for TrySendError { kind: match err { chan::TrySendError::Closed => ErrorKind::Closed, chan::TrySendError::NoPermits => ErrorKind::NoCapacity, - } + }, } } } diff --git a/tokio-sync/src/mpsc/chan.rs b/tokio-sync/src/mpsc/chan.rs index 8a8f2bea2..05a5634de 100644 --- a/tokio-sync/src/mpsc/chan.rs +++ b/tokio-sync/src/mpsc/chan.rs @@ -1,14 +1,14 @@ use super::list; use futures::Poll; -use ::loom::{ +use loom::{ futures::AtomicTask, - sync::{Arc, CausalCell}, sync::atomic::AtomicUsize, + sync::{Arc, CausalCell}, }; -use std::process; use std::fmt; +use std::process; use std::sync::atomic::Ordering::{AcqRel, Relaxed}; /// Channel sender @@ -18,8 +18,9 @@ pub(crate) struct Tx { } impl fmt::Debug for Tx -where S::Permit: fmt::Debug, - S: fmt::Debug +where + S::Permit: fmt::Debug, + S: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Tx") @@ -35,12 +36,11 @@ pub(crate) struct Rx { } impl fmt::Debug for Rx -where S: fmt::Debug +where + S: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Rx") - .field("inner", &self.inner) - .finish() + fmt.debug_struct("Rx").field("inner", &self.inner).finish() } } @@ -95,7 +95,9 @@ struct Chan { rx_fields: CausalCell>, } -impl fmt::Debug for Chan where S: fmt::Debug +impl fmt::Debug for Chan +where + S: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Chan") @@ -117,8 +119,7 @@ struct RxFields { rx_closed: bool, } -impl fmt::Debug for RxFields -{ +impl fmt::Debug for RxFields { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("RxFields") .field("list", &self.list) @@ -273,7 +274,7 @@ where } None => {} // fall through } - } + }; } try_recv!(); @@ -285,8 +286,11 @@ where // second time here. try_recv!(); - debug!("recv; rx_closed = {:?}; is_idle = {:?}", - rx_fields.rx_closed, self.inner.semaphore.is_idle()); + debug!( + "recv; rx_closed = {:?}; is_idle = {:?}", + rx_fields.rx_closed, + self.inner.semaphore.is_idle() + ); if rx_fields.rx_closed && self.inner.semaphore.is_idle() { Ok(Ready(None)) @@ -325,8 +329,7 @@ impl Drop for Chan { self.rx_fields.with_mut(|rx_fields_ptr| { let rx_fields = unsafe { &mut *rx_fields_ptr }; - while let Some(Value(_)) = rx_fields.list.pop(&self.tx) { - } + while let Some(Value(_)) = rx_fields.list.pop(&self.tx) {} }); } } @@ -369,8 +372,7 @@ impl Semaphore for (::semaphore::Semaphore, usize) { } fn poll_acquire(&self, permit: &mut Permit) -> Poll<(), ()> { - permit.poll_acquire(&self.0) - .map_err(|_| ()) + permit.poll_acquire(&self.0).map_err(|_| ()) } fn try_acquire(&self, permit: &mut Permit) -> Result<(), TrySendError> { @@ -395,11 +397,9 @@ use std::usize; impl Semaphore for AtomicUsize { type Permit = (); - fn new_permit() { - } + fn new_permit() {} - fn drop_permit(&self, _permit: &mut ()) { - } + fn drop_permit(&self, _permit: &mut ()) {} fn add_permit(&self) { let prev = self.fetch_sub(2, Release); @@ -416,9 +416,7 @@ impl Semaphore for AtomicUsize { fn poll_acquire(&self, permit: &mut ()) -> Poll<(), ()> { use futures::Async::Ready; - self.try_acquire(permit) - .map(Ready) - .map_err(|_| ()) + self.try_acquire(permit).map(Ready).map_err(|_| ()) } fn try_acquire(&self, _permit: &mut ()) -> Result<(), TrySendError> { @@ -444,8 +442,7 @@ impl Semaphore for AtomicUsize { } } - fn forget(&self, _permit: &mut ()) { - } + fn forget(&self, _permit: &mut ()) {} fn close(&self) { self.fetch_or(1, Release); diff --git a/tokio-sync/src/mpsc/list.rs b/tokio-sync/src/mpsc/list.rs index aedd99547..165f1adc5 100644 --- a/tokio-sync/src/mpsc/list.rs +++ b/tokio-sync/src/mpsc/list.rs @@ -4,12 +4,12 @@ use super::block::{self, Block}; use loom::{ self, - sync::atomic::{AtomicUsize, AtomicPtr}, + sync::atomic::{AtomicPtr, AtomicUsize}, }; use std::fmt; use std::ptr::NonNull; -use std::sync::atomic::Ordering::{Acquire, Release, AcqRel, Relaxed}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; /// List queue transmit handle pub(crate) struct Tx { @@ -59,8 +59,7 @@ impl Tx { pub(crate) fn push(&self, value: T) { // First, claim a slot for the value. `Acquire` is used here to // synchronize with the `fetch_add` in `free_blocks`. - let slot_index = self.tail_position - .fetch_add(1, Acquire); + let slot_index = self.tail_position.fetch_add(1, Acquire); // Load the current block and write the value let block = self.find_block(slot_index); @@ -78,14 +77,11 @@ impl Tx { pub(crate) fn close(&self) { // First, claim a slot for the value. This is the last slot that will be // claimed. - let slot_index = self.tail_position - .fetch_add(1, Acquire); + let slot_index = self.tail_position.fetch_add(1, Acquire); let block = self.find_block(slot_index); - unsafe { - block.as_ref().tx_close() - } + unsafe { block.as_ref().tx_close() } } fn find_block(&self, slot_index: usize) -> NonNull> { @@ -123,7 +119,8 @@ impl Tx { return unsafe { NonNull::new_unchecked(block_ptr) }; } - let next_block = block.load_next(Acquire) + let next_block = block + .load_next(Acquire) // There is no allocated next block, grow the linked list. .unwrap_or_else(|| block.grow()); @@ -146,15 +143,17 @@ impl Tx { // // Acquire is not needed as any "actual" value is not accessed. // At this point, the linked list is walked to acquire blocks. - let actual = self.block_tail.compare_and_swap( - block_ptr, next_block.as_ptr(), Release); + let actual = + self.block_tail + .compare_and_swap(block_ptr, next_block.as_ptr(), Release); if actual == block_ptr { // Synchronize with any senders - let tail_position = - self.tail_position.fetch_add(0, Release); + let tail_position = self.tail_position.fetch_add(0, Release); - unsafe { block.tx_release(tail_position); } + unsafe { + block.tx_release(tail_position); + } } else { // A concurrent sender is also working on advancing // `block_tail` and this thread is falling behind. @@ -207,7 +206,7 @@ impl Tx { } if !reused { - let _ = Box::from_raw(block.as_ptr()); + let _ = Box::from_raw(block.as_ptr()); } } } @@ -286,8 +285,7 @@ impl Rx { // `free_head` to point to the next block. let block = self.free_head; - let observed_tail_position = - block.as_ref().observed_tail_position(); + let observed_tail_position = block.as_ref().observed_tail_position(); let required_index = match observed_tail_position { Some(i) => i, @@ -302,8 +300,7 @@ impl Rx { // guaranteed that the `free_blocks` routine trails the `recv` // routine. Any memory accessed by `free_blocks` has already // been acquired by `recv`. - let next_block = - block.as_ref().load_next(Relaxed); + let next_block = block.as_ref().load_next(Relaxed); // Update the free list head self.free_head = next_block.unwrap(); diff --git a/tokio-sync/src/mpsc/mod.rs b/tokio-sync/src/mpsc/mod.rs index 9d6d05d37..382e9bc68 100644 --- a/tokio-sync/src/mpsc/mod.rs +++ b/tokio-sync/src/mpsc/mod.rs @@ -40,32 +40,16 @@ mod chan; mod list; mod unbounded; -pub use self::bounded::{ - channel, - Receiver, - Sender -}; +pub use self::bounded::{channel, Receiver, Sender}; -pub use self::unbounded::{ - unbounded_channel, - UnboundedReceiver, - UnboundedSender, -}; +pub use self::unbounded::{unbounded_channel, UnboundedReceiver, UnboundedSender}; pub mod error { //! Channel error types - pub use super::bounded::{ - SendError, - TrySendError, - RecvError, - }; + pub use super::bounded::{RecvError, SendError, TrySendError}; - pub use super::unbounded::{ - UnboundedSendError, - UnboundedTrySendError, - UnboundedRecvError, - }; + pub use super::unbounded::{UnboundedRecvError, UnboundedSendError, UnboundedTrySendError}; } /// The number of values a block can contain. diff --git a/tokio-sync/src/mpsc/unbounded.rs b/tokio-sync/src/mpsc/unbounded.rs index 181ad5179..67e61fdb6 100644 --- a/tokio-sync/src/mpsc/unbounded.rs +++ b/tokio-sync/src/mpsc/unbounded.rs @@ -1,7 +1,7 @@ use super::chan; -use loom::sync::atomic::AtomicUsize; use futures::{Poll, Sink, StartSend, Stream}; +use loom::sync::atomic::AtomicUsize; use std::fmt; @@ -15,7 +15,9 @@ pub struct UnboundedSender { impl Clone for UnboundedSender { fn clone(&self) -> Self { - UnboundedSender { chan: self.chan.clone() } + UnboundedSender { + chan: self.chan.clone(), + } } } @@ -97,21 +99,17 @@ impl Stream for UnboundedReceiver { type Error = UnboundedRecvError; fn poll(&mut self) -> Poll, Self::Error> { - self.chan.recv() - .map_err(|_| UnboundedRecvError(())) + self.chan.recv().map_err(|_| UnboundedRecvError(())) } } - impl UnboundedSender { pub(crate) fn new(chan: chan::Tx) -> UnboundedSender { UnboundedSender { chan } } /// Attempts to send a message on this `UnboundedSender` without blocking. - pub fn try_send(&mut self, message: T) - -> Result<(), UnboundedTrySendError> - { + pub fn try_send(&mut self, message: T) -> Result<(), UnboundedTrySendError> { self.chan.try_send(message)?; Ok(()) } diff --git a/tokio-sync/src/oneshot.rs b/tokio-sync/src/oneshot.rs index c304cccb8..f8e825679 100644 --- a/tokio-sync/src/oneshot.rs +++ b/tokio-sync/src/oneshot.rs @@ -2,16 +2,16 @@ use loom::{ futures::task::{self, Task}, - sync::CausalCell, sync::atomic::AtomicUsize, + sync::CausalCell, }; use futures::{Async, Future, Poll}; use std::fmt; use std::mem::{self, ManuallyDrop}; +use std::sync::atomic::Ordering::{self, AcqRel, Acquire}; use std::sync::Arc; -use std::sync::atomic::Ordering::{self, Acquire, AcqRel}; /// Sends a value to the associated `Receiver`. /// @@ -102,7 +102,9 @@ pub fn channel() -> (Sender, Receiver) { rx_task: CausalCell::new(ManuallyDrop::new(unsafe { mem::uninitialized() })), }); - let tx = Sender { inner: Some(inner.clone()) }; + let tx = Sender { + inner: Some(inner.clone()), + }; let rx = Receiver { inner: Some(inner) }; (tx, rx) @@ -121,14 +123,14 @@ impl Sender { pub fn send(mut self, t: T) -> Result<(), T> { let inner = self.inner.take().unwrap(); - inner.value.with_mut(|ptr| { - unsafe { *ptr = Some(t); } + inner.value.with_mut(|ptr| unsafe { + *ptr = Some(t); }); if !inner.complete() { - return Err(inner.value.with_mut(|ptr| { - unsafe { (*ptr).take() }.unwrap() - })); + return Err(inner + .value + .with_mut(|ptr| unsafe { (*ptr).take() }.unwrap())); } Ok(()) @@ -156,9 +158,9 @@ impl Sender { } if state.is_tx_task_set() { - let will_notify = inner.tx_task.with(|ptr| unsafe { - (&*ptr).will_notify_current() - }); + let will_notify = inner + .tx_task + .with(|ptr| unsafe { (&*ptr).will_notify_current() }); if !will_notify { state = State::unset_tx_task(&inner.state); @@ -173,7 +175,9 @@ impl Sender { if !state.is_tx_task_set() { // Attempt to set the task - unsafe { inner.set_tx_task(); } + unsafe { + inner.set_tx_task(); + } // Update the state state = State::set_tx_task(&inner.state); @@ -186,7 +190,6 @@ impl Sender { Ok(Async::NotReady) } - /// Check if the associated [`Receiver`] handle has been dropped. /// /// Unlike [`poll_close`], this function does not register a task for @@ -271,7 +274,7 @@ impl Future for Receiver { type Error = RecvError; fn poll(&mut self) -> Poll { - use futures::Async::{Ready, NotReady}; + use futures::Async::{NotReady, Ready}; // If `inner` is `None`, then `poll()` has already completed. let ret = if let Some(inner) = self.inner.as_ref() { @@ -298,16 +301,14 @@ impl Inner { } if prev.is_rx_task_set() { - self.rx_task.with(|ptr| unsafe { - (&*ptr).notify() - }); + self.rx_task.with(|ptr| unsafe { (&*ptr).notify() }); } true } fn poll_recv(&self) -> Poll { - use futures::Async::{Ready, NotReady}; + use futures::Async::{NotReady, Ready}; // Load the state let mut state = State::load(&self.state, Acquire); @@ -321,9 +322,9 @@ impl Inner { Err(RecvError(())) } else { if state.is_rx_task_set() { - let will_notify = self.rx_task.with(|ptr| unsafe { - (&*ptr).will_notify_current() - }); + let will_notify = self + .rx_task + .with(|ptr| unsafe { (&*ptr).will_notify_current() }); // Check if the task is still the same if !will_notify { @@ -342,7 +343,9 @@ impl Inner { if !state.is_rx_task_set() { // Attempt to set the task - unsafe { self.set_rx_task(); } + unsafe { + self.set_rx_task(); + } // Update the state state = State::set_rx_task(&self.state); @@ -366,41 +369,31 @@ impl Inner { let prev = State::set_closed(&self.state); if prev.is_tx_task_set() && !prev.is_complete() { - self.tx_task.with(|ptr| unsafe { - (&*ptr).notify() - }); + self.tx_task.with(|ptr| unsafe { (&*ptr).notify() }); } } /// Consume the value. This function does not check `state`. unsafe fn consume_value(&self) -> Option { - self.value.with_mut(|ptr| { - (*ptr).take() - }) + self.value.with_mut(|ptr| (*ptr).take()) } unsafe fn drop_rx_task(&self) { - self.rx_task.with_mut(|ptr| { - ManuallyDrop::drop(&mut *ptr) - }) + self.rx_task.with_mut(|ptr| ManuallyDrop::drop(&mut *ptr)) } unsafe fn drop_tx_task(&self) { - self.tx_task.with_mut(|ptr| { - ManuallyDrop::drop(&mut *ptr) - }) + self.tx_task.with_mut(|ptr| ManuallyDrop::drop(&mut *ptr)) } unsafe fn set_rx_task(&self) { - self.rx_task.with_mut(|ptr| { - *ptr = ManuallyDrop::new(task::current()) - }); + self.rx_task + .with_mut(|ptr| *ptr = ManuallyDrop::new(task::current())); } unsafe fn set_tx_task(&self) { - self.tx_task.with_mut(|ptr| { - *ptr = ManuallyDrop::new(task::current()) - }); + self.tx_task + .with_mut(|ptr| *ptr = ManuallyDrop::new(task::current())); } } @@ -412,18 +405,14 @@ impl Drop for Inner { let state = State(*self.state.get_mut()); if state.is_rx_task_set() { - self.rx_task.with_mut(|ptr| { - unsafe { - ManuallyDrop::drop(&mut *ptr); - } + self.rx_task.with_mut(|ptr| unsafe { + ManuallyDrop::drop(&mut *ptr); }); } if state.is_tx_task_set() { - self.tx_task.with_mut(|ptr| { - unsafe { - ManuallyDrop::drop(&mut *ptr); - } + self.tx_task.with_mut(|ptr| unsafe { + ManuallyDrop::drop(&mut *ptr); }); } } @@ -440,8 +429,8 @@ impl fmt::Debug for Inner { } const RX_TASK_SET: usize = 0b00001; -const VALUE_SENT: usize = 0b00010; -const CLOSED: usize = 0b00100; +const VALUE_SENT: usize = 0b00010; +const CLOSED: usize = 0b00100; const TX_TASK_SET: usize = 0b01000; impl State { diff --git a/tokio-sync/src/semaphore.rs b/tokio-sync/src/semaphore.rs index 24c7fa395..8beaa9a6c 100644 --- a/tokio-sync/src/semaphore.rs +++ b/tokio-sync/src/semaphore.rs @@ -11,8 +11,8 @@ use loom::{ futures::AtomicTask, sync::{ + atomic::{AtomicPtr, AtomicUsize}, CausalCell, - atomic::{AtomicUsize, AtomicPtr}, }, yield_now, }; @@ -21,8 +21,8 @@ use futures::Poll; use std::fmt; use std::ptr::{self, NonNull}; +use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed, Release}; use std::sync::Arc; -use std::sync::atomic::Ordering::{self, Acquire, Release, AcqRel, Relaxed}; use std::usize; /// Futures-aware semaphore. @@ -176,9 +176,7 @@ impl Semaphore { } /// Poll for a permit - fn poll_permit(&self, mut permit: Option<&mut Permit>) - -> Poll<(), AcquireError> - { + fn poll_permit(&self, mut permit: Option<&mut Permit>) -> Poll<(), AcquireError> { use futures::Async::*; // Load the current state @@ -201,7 +199,7 @@ impl Semaphore { let waiter = unsafe { Arc::from_raw(waiter.as_ptr()) }; waiter.revert_to_idle(); } - } + }; } loop { @@ -220,7 +218,8 @@ impl Semaphore { if maybe_strong.is_none() { if let Some(ref mut permit) = permit { // Get the Sender's waiter node, or initialize one - let waiter = permit.waiter + let waiter = permit + .waiter .get_or_insert_with(|| Arc::new(WaiterNode::new())); waiter.register(); @@ -259,8 +258,7 @@ impl Semaphore { // Finish pushing unsafe { - prev_waiter.as_ref() - .next.store(waiter.as_ptr(), Release); + prev_waiter.as_ref().next.store(waiter.as_ptr(), Release); } debug!(" + poll_permit -- waiter pushed"); @@ -327,8 +325,10 @@ impl Semaphore { fn add_permits_locked(&self, mut rem: usize, mut closed: bool) { while rem > 0 || closed { - debug!(" + add_permits_locked -- iter; rem = {}; closed = {:?}", - rem, closed); + debug!( + " + add_permits_locked -- iter; rem = {}; closed = {:?}", + rem, closed + ); if closed { SemState::fetch_set_closed(&self.state, AcqRel); @@ -341,13 +341,19 @@ impl Semaphore { let actual = if closed { let actual = self.rx_lock.fetch_sub(n | 1, AcqRel); - debug!(" + add_permits_locked; rx_lock.fetch_sub(n | 1); n = {}; actual={}", n, actual); + debug!( + " + add_permits_locked; rx_lock.fetch_sub(n | 1); n = {}; actual={}", + n, actual + ); closed = false; actual } else { let actual = self.rx_lock.fetch_sub(n, AcqRel); - debug!(" + add_permits_locked; rx_lock.fetch_sub(n); n = {}; actual={}", n, actual); + debug!( + " + add_permits_locked; rx_lock.fetch_sub(n); n = {}; actual={}", + n, actual + ); closed = actual & 1 == 1; actual @@ -389,8 +395,7 @@ impl Semaphore { fn pop(&self, rem: usize, closed: bool) -> Option> { debug!(" + pop; rem = {}", rem); - 'outer: - loop { + 'outer: loop { unsafe { let mut head = self.head.with(|head| *head); let mut next_ptr = head.as_ref().next.load(Acquire); @@ -502,12 +507,10 @@ impl Semaphore { // operation stub.as_ref().next.store(ptr::null_mut(), Relaxed); - // Update the tail to point to the new node. We need to see the previous // node in order to update the next pointer as well as release `task` // to any other threads calling `push`. - let prev = SemState::new_ptr(stub, closed) - .swap(&self.state, AcqRel); + let prev = SemState::new_ptr(stub, closed).swap(&self.state, AcqRel); debug_assert_eq!(closed, prev.is_closed()); @@ -523,9 +526,7 @@ impl Semaphore { } fn stub(&self) -> NonNull { - unsafe { - NonNull::new_unchecked(&*self.stub as *const _ as *mut _) - } + unsafe { NonNull::new_unchecked(&*self.stub as *const _ as *mut _) } } } @@ -574,9 +575,7 @@ impl Permit { /// Try to acquire the permit. If no permits are available, the current task /// is notified once a new permit becomes available. - pub fn poll_acquire(&mut self, semaphore: &Semaphore) - -> Poll<(), AcquireError> - { + pub fn poll_acquire(&mut self, semaphore: &Semaphore) -> Poll<(), AcquireError> { use futures::Async::*; match self.state { @@ -609,9 +608,7 @@ impl Permit { } /// Try to acquire the permit. - pub fn try_acquire(&mut self, semaphore: &Semaphore) - -> Result<(), TryAcquireError> - { + pub fn try_acquire(&mut self, semaphore: &Semaphore) -> Result<(), TryAcquireError> { use futures::Async::*; match self.state { @@ -636,9 +633,7 @@ impl Permit { self.state = PermitState::Acquired; Ok(()) } - NotReady => { - Err(TryAcquireError::no_permits()) - } + NotReady => Err(TryAcquireError::no_permits()), } } @@ -665,10 +660,7 @@ impl Permit { match self.state { PermitState::Idle => false, PermitState::Waiting => { - let ret = self.waiter - .as_ref() - .unwrap() - .cancel_interest(); + let ret = self.waiter.as_ref().unwrap().cancel_interest(); self.state = PermitState::Idle; ret } @@ -709,11 +701,15 @@ impl ::std::error::Error for AcquireError { impl TryAcquireError { fn closed() -> TryAcquireError { - TryAcquireError { kind: ErrorKind::Closed } + TryAcquireError { + kind: ErrorKind::Closed, + } } fn no_permits() -> TryAcquireError { - TryAcquireError { kind: ErrorKind::NoPermits } + TryAcquireError { + kind: ErrorKind::NoPermits, + } } /// Returns true if the error was caused by a closed semaphore. @@ -865,22 +861,18 @@ impl WaiterNode { }; match next.compare_exchange(&self.state, curr, AcqRel, Acquire) { - Ok(_) => { - match curr { - QueuedWaiting => { - debug!(" + notify -- task notified"); - self.task.notify(); - return true; - } - other => { - debug!(" + notify -- not notified; state = {:?}", other); - return false; - } + Ok(_) => match curr { + QueuedWaiting => { + debug!(" + notify -- task notified"); + self.task.notify(); + return true; } - } - Err(actual) => { - curr = actual - } + other => { + debug!(" + notify -- not notified; state = {:?}", other); + return false; + } + }, + Err(actual) => curr = actual, } } } @@ -1003,8 +995,7 @@ impl SemState { /// Returns the waiter, if one is set. fn waiter(&self) -> Option> { if self.is_waiter() { - let waiter = NonNull::new(self.as_ptr()) - .expect("null pointer stored"); + let waiter = NonNull::new(self.as_ptr()).expect("null pointer stored"); Some(waiter) } else { @@ -1047,22 +1038,25 @@ impl SemState { } /// Compare and exchange the current value into the provided cell - fn compare_exchange(&self, - cell: &AtomicUsize, - prev: SemState, - success: Ordering, - failure: Ordering) - -> Result - { + fn compare_exchange( + &self, + cell: &AtomicUsize, + prev: SemState, + success: Ordering, + failure: Ordering, + ) -> Result { debug_assert_eq!(prev.is_closed(), self.is_closed()); let res = cell.compare_exchange(prev.to_usize(), self.to_usize(), success, failure); - debug!(" + SemState::compare_exchange; prev = {}; next = {}; result = {:?}", - prev.to_usize(), self.to_usize(), res); + debug!( + " + SemState::compare_exchange; prev = {}; next = {}; result = {:?}", + prev.to_usize(), + self.to_usize(), + res + ); - res.map(SemState) - .map_err(SemState) + res.map(SemState).map_err(SemState) } fn fetch_set_closed(cell: &AtomicUsize, ordering: Ordering) -> SemState { @@ -1123,13 +1117,13 @@ impl NodeState { cell.store(value.to_usize(), ordering); } - fn compare_exchange(&self, - cell: &AtomicUsize, - prev: NodeState, - success: Ordering, - failure: Ordering) - -> Result - { + fn compare_exchange( + &self, + cell: &AtomicUsize, + prev: NodeState, + success: Ordering, + failure: Ordering, + ) -> Result { cell.compare_exchange(prev.to_usize(), self.to_usize(), success, failure) .map(NodeState::from_usize) .map_err(NodeState::from_usize) diff --git a/tokio-sync/src/task/atomic_task.rs b/tokio-sync/src/task/atomic_task.rs index 06f3a5bbb..2161e0e1c 100644 --- a/tokio-sync/src/task/atomic_task.rs +++ b/tokio-sync/src/task/atomic_task.rs @@ -1,11 +1,11 @@ -use ::loom::{ +use loom::{ futures::task::{self, Task}, - sync::CausalCell, sync::atomic::AtomicUsize, + sync::CausalCell, }; use std::fmt; -use std::sync::atomic::Ordering::{Acquire, Release, AcqRel}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Release}; /// A synchronization primitive for task notification. /// @@ -189,8 +189,9 @@ impl AtomicTask { // // Start by assuming that the state is `REGISTERING` as this // is what we jut set it to. - let res = self.state.compare_exchange( - REGISTERING, WAITING, AcqRel, Acquire); + let res = self + .state + .compare_exchange(REGISTERING, WAITING, AcqRel, Acquire); match res { Ok(_) => {} @@ -230,9 +231,7 @@ impl AtomicTask { // // We just want to maintain memory safety. It is ok to drop the // call to `register`. - debug_assert!( - state == REGISTERING || - state == REGISTERING | NOTIFYING); + debug_assert!(state == REGISTERING || state == REGISTERING | NOTIFYING); } } } @@ -276,9 +275,8 @@ impl AtomicTask { // not. // debug_assert!( - state == REGISTERING || - state == REGISTERING | NOTIFYING || - state == NOTIFYING); + state == REGISTERING || state == REGISTERING | NOTIFYING || state == NOTIFYING + ); None } } @@ -309,7 +307,8 @@ struct CurrentTask; impl Register for CurrentTask { fn register(self, slot: &mut Option) { - let should_update = (&*slot).as_ref() + let should_update = (&*slot) + .as_ref() .map(|prev| !prev.will_notify_current()) .unwrap_or(true); if should_update { diff --git a/tokio-sync/tests/fuzz_atomic_task.rs b/tokio-sync/tests/fuzz_atomic_task.rs index 1ba1a7751..4381a7efb 100644 --- a/tokio-sync/tests/fuzz_atomic_task.rs +++ b/tokio-sync/tests/fuzz_atomic_task.rs @@ -14,11 +14,11 @@ use loom::futures::block_on; use loom::sync::atomic::AtomicUsize; use loom::thread; -use futures::Async; use futures::future::poll_fn; +use futures::Async; -use std::sync::Arc; use std::sync::atomic::Ordering::Relaxed; +use std::sync::Arc; struct Chan { num: AtomicUsize, @@ -52,6 +52,7 @@ fn basic_notification() { } Ok::<_, ()>(Async::NotReady) - })).unwrap(); + })) + .unwrap(); }); } diff --git a/tokio-sync/tests/fuzz_mpsc.rs b/tokio-sync/tests/fuzz_mpsc.rs index a3c7309cf..da83100f2 100644 --- a/tokio-sync/tests/fuzz_mpsc.rs +++ b/tokio-sync/tests/fuzz_mpsc.rs @@ -16,7 +16,7 @@ mod mpsc; #[allow(warnings)] mod semaphore; -use futures::{Stream, future::poll_fn}; +use futures::{future::poll_fn, Stream}; use loom::futures::block_on; use loom::thread; diff --git a/tokio-sync/tests/fuzz_oneshot.rs b/tokio-sync/tests/fuzz_oneshot.rs index 2d3bda96a..bf9d2836f 100644 --- a/tokio-sync/tests/fuzz_oneshot.rs +++ b/tokio-sync/tests/fuzz_oneshot.rs @@ -8,8 +8,8 @@ extern crate loom; mod oneshot; use futures::{Async, Future}; -use loom::thread; use loom::futures::block_on; +use loom::thread; #[test] fn smoke() { @@ -35,30 +35,26 @@ fn changing_rx_task() { }); let rx = thread::spawn(move || { - let t1 = block_on(futures::future::poll_fn(|| { - Ok::<_, ()>(rx.poll().into()) - })).unwrap(); + let t1 = block_on(futures::future::poll_fn(|| Ok::<_, ()>(rx.poll().into()))).unwrap(); match t1 { Ok(Async::Ready(value)) => { // ok assert_eq!(1, value); None - }, - Ok(Async::NotReady) => { - Some(rx) - }, + } + Ok(Async::NotReady) => Some(rx), Err(_) => unreachable!(), } - }).join().unwrap(); - + }) + .join() + .unwrap(); if let Some(rx) = rx { // Previous task parked, use a new task... let value = block_on(rx).unwrap(); assert_eq!(1, value); } - }); } @@ -74,25 +70,21 @@ fn changing_tx_task() { let tx = thread::spawn(move || { let t1 = block_on(futures::future::poll_fn(|| { Ok::<_, ()>(tx.poll_close().into()) - })).unwrap(); + })) + .unwrap(); match t1 { - Ok(Async::Ready(())) => { - None - }, - Ok(Async::NotReady) => { - Some(tx) - }, + Ok(Async::Ready(())) => None, + Ok(Async::NotReady) => Some(tx), Err(_) => unreachable!(), } - }).join().unwrap(); - + }) + .join() + .unwrap(); if let Some(mut tx) = tx { // Previous task parked, use a new task... - block_on(futures::future::poll_fn(move || { - tx.poll_close() - })).unwrap(); + block_on(futures::future::poll_fn(move || tx.poll_close())).unwrap(); } }); } diff --git a/tokio-sync/tests/fuzz_semaphore.rs b/tokio-sync/tests/fuzz_semaphore.rs index aa0480974..e88775af1 100644 --- a/tokio-sync/tests/fuzz_semaphore.rs +++ b/tokio-sync/tests/fuzz_semaphore.rs @@ -11,13 +11,13 @@ mod semaphore; use semaphore::*; -use futures::{future, Future, Async, Poll}; -use loom::thread; +use futures::{future, Async, Future, Poll}; use loom::futures::block_on; +use loom::thread; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; #[test] fn basic_usage() { @@ -38,12 +38,13 @@ fn basic_usage() { type Error = (); fn poll(&mut self) -> Poll<(), ()> { - try_ready!( - self.waiter.poll_acquire(&self.shared.semaphore) + try_ready!(self + .waiter + .poll_acquire(&self.shared.semaphore) .map_err(|_| ())); let actual = self.shared.active.fetch_add(1, SeqCst); - assert!(actual <= NUM-1); + assert!(actual <= NUM - 1); let actual = self.shared.active.fetch_sub(1, SeqCst); assert!(actual <= NUM); @@ -67,14 +68,16 @@ fn basic_usage() { block_on(Actor { waiter: Permit::new(), shared, - }).unwrap(); + }) + .unwrap(); }); } block_on(Actor { waiter: Permit::new(), - shared - }).unwrap(); + shared, + }) + .unwrap(); }); } @@ -91,8 +94,8 @@ fn release() { block_on(future::lazy(|| { permit.poll_acquire(&semaphore).unwrap(); Ok::<_, ()>(()) - - })).unwrap(); + })) + .unwrap(); permit.release(&semaphore); }); @@ -100,9 +103,7 @@ fn release() { let mut permit = Permit::new(); - block_on(future::poll_fn(|| { - permit.poll_acquire(&semaphore) - })).unwrap(); + block_on(future::poll_fn(|| permit.poll_acquire(&semaphore))).unwrap(); permit.release(&semaphore); }); @@ -123,8 +124,7 @@ fn basic_closing() { for _ in 0..2 { block_on(future::poll_fn(|| { - permit.poll_acquire(&semaphore) - .map_err(|_| ()) + permit.poll_acquire(&semaphore).map_err(|_| ()) }))?; permit.release(&semaphore); } @@ -151,8 +151,7 @@ fn concurrent_close() { let mut permit = Permit::new(); block_on(future::poll_fn(|| { - permit.poll_acquire(&semaphore) - .map_err(|_| ()) + permit.poll_acquire(&semaphore).map_err(|_| ()) }))?; permit.release(&semaphore); diff --git a/tokio-sync/tests/mpsc.rs b/tokio-sync/tests/mpsc.rs index f58305e0b..69386ef61 100644 --- a/tokio-sync/tests/mpsc.rs +++ b/tokio-sync/tests/mpsc.rs @@ -4,13 +4,13 @@ extern crate futures; extern crate tokio_mock_task; extern crate tokio_sync; -use tokio_sync::mpsc; use tokio_mock_task::*; +use tokio_sync::mpsc; use futures::prelude::*; -use std::thread; use std::sync::Arc; +use std::thread; trait AssertSend: Send {} impl AssertSend for mpsc::Sender {} @@ -23,17 +23,17 @@ macro_rules! assert_ready { Ok(_) => panic!("not ready"), Err(e) => panic!("error = {:?}", e), } - }} + }}; } macro_rules! assert_not_ready { ($e:expr) => {{ match $e { - Ok(futures::Async::NotReady) => {}, + Ok(futures::Async::NotReady) => {} Ok(futures::Async::Ready(v)) => panic!("ready; value = {:?}", v), Err(e) => panic!("error = {:?}", e), } - }} + }}; } #[test] @@ -212,7 +212,7 @@ fn send_recv_threads() { let (tx, rx) = mpsc::channel::(16); let mut rx = rx.wait(); - thread::spawn(move|| { + thread::spawn(move || { tx.send(1).wait().unwrap(); }); diff --git a/tokio-sync/tests/oneshot.rs b/tokio-sync/tests/oneshot.rs index 2413f909a..46c67a74c 100644 --- a/tokio-sync/tests/oneshot.rs +++ b/tokio-sync/tests/oneshot.rs @@ -4,8 +4,8 @@ extern crate futures; extern crate tokio_mock_task; extern crate tokio_sync; -use tokio_sync::oneshot; use tokio_mock_task::*; +use tokio_sync::oneshot; use futures::prelude::*; @@ -16,20 +16,19 @@ macro_rules! assert_ready { Ok(_) => panic!("not ready"), Err(e) => panic!("error = {:?}", e), } - }} + }}; } macro_rules! assert_not_ready { ($e:expr) => {{ match $e { - Ok(futures::Async::NotReady) => {}, + Ok(futures::Async::NotReady) => {} Ok(futures::Async::Ready(v)) => panic!("ready; value = {:?}", v), Err(e) => panic!("error = {:?}", e), } - }} + }}; } - trait AssertSend: Send {} impl AssertSend for oneshot::Sender {} impl AssertSend for oneshot::Receiver {} diff --git a/tokio-sync/tests/semaphore.rs b/tokio-sync/tests/semaphore.rs index 2249045f2..8cd3533fa 100644 --- a/tokio-sync/tests/semaphore.rs +++ b/tokio-sync/tests/semaphore.rs @@ -4,8 +4,8 @@ extern crate futures; extern crate tokio_mock_task; extern crate tokio_sync; -use tokio_sync::semaphore::{Semaphore, Permit}; use tokio_mock_task::*; +use tokio_sync::semaphore::{Permit, Semaphore}; macro_rules! assert_ready { ($e:expr) => {{ @@ -14,17 +14,17 @@ macro_rules! assert_ready { Ok(_) => panic!("not ready"), Err(e) => panic!("error = {:?}", e), } - }} + }}; } macro_rules! assert_not_ready { ($e:expr) => {{ match $e { - Ok(futures::Async::NotReady) => {}, + Ok(futures::Async::NotReady) => {} Ok(futures::Async::Ready(v)) => panic!("ready; value = {:?}", v), Err(e) => panic!("error = {:?}", e), } - }} + }}; } #[test] diff --git a/tokio-tcp/src/incoming.rs b/tokio-tcp/src/incoming.rs index 7db6414c0..3c6968791 100644 --- a/tokio-tcp/src/incoming.rs +++ b/tokio-tcp/src/incoming.rs @@ -1,9 +1,9 @@ use super::TcpListener; use super::TcpStream; -use std::io; use futures::stream::Stream; -use futures::{Poll, Async}; +use futures::{Async, Poll}; +use std::io; /// Stream returned by the `TcpListener::incoming` function representing the /// stream of sockets received from a listener. diff --git a/tokio-tcp/src/lib.rs b/tokio-tcp/src/lib.rs index e6ebdf245..c8aa4102f 100644 --- a/tokio-tcp/src/lib.rs +++ b/tokio-tcp/src/lib.rs @@ -36,5 +36,5 @@ mod stream; pub use self::incoming::Incoming; pub use self::listener::TcpListener; -pub use self::stream::TcpStream; pub use self::stream::ConnectFuture; +pub use self::stream::TcpStream; diff --git a/tokio-tcp/src/listener.rs b/tokio-tcp/src/listener.rs index 2eb38c72b..f67e7ce9c 100644 --- a/tokio-tcp/src/listener.rs +++ b/tokio-tcp/src/listener.rs @@ -5,7 +5,7 @@ use std::fmt; use std::io; use std::net::{self, SocketAddr}; -use futures::{Poll, Async}; +use futures::{Async, Poll}; use mio; use tokio_reactor::{Handle, PollEvented}; @@ -235,9 +235,7 @@ impl TcpListener { /// # Ok(()) /// # } /// ``` - pub fn from_std(listener: net::TcpListener, handle: &Handle) - -> io::Result - { + pub fn from_std(listener: net::TcpListener, handle: &Handle) -> io::Result { let io = mio::net::TcpListener::from_std(listener)?; let io = PollEvented::new_with_handle(io, handle)?; Ok(TcpListener { io }) @@ -371,8 +369,8 @@ impl fmt::Debug for TcpListener { #[cfg(unix)] mod sys { - use std::os::unix::prelude::*; use super::TcpListener; + use std::os::unix::prelude::*; impl AsRawFd for TcpListener { fn as_raw_fd(&self) -> RawFd { diff --git a/tokio-tcp/src/stream.rs b/tokio-tcp/src/stream.rs index d3766b5a2..0ee2faaf4 100644 --- a/tokio-tcp/src/stream.rs +++ b/tokio-tcp/src/stream.rs @@ -1,11 +1,11 @@ use std::fmt; use std::io::{self, Read, Write}; use std::mem; -use std::net::{self, SocketAddr, Shutdown}; +use std::net::{self, Shutdown, SocketAddr}; use std::time::Duration; use bytes::{Buf, BufMut}; -use futures::{Future, Poll, Async}; +use futures::{Async, Future, Poll}; use iovec::IoVec; use mio; use tokio_io::{AsyncRead, AsyncWrite}; @@ -80,7 +80,7 @@ impl TcpStream { /// # fn main() -> Result<(), Box> { /// let addr = "127.0.0.1:34254".parse::()?; /// let stream = TcpStream::connect(&addr) - /// .map(|stream| + /// .map(|stream| /// println!("successfully connected to {}", stream.local_addr().unwrap())); /// # Ok(()) /// # } @@ -122,9 +122,7 @@ impl TcpStream { /// # Ok(()) /// # } /// ``` - pub fn from_std(stream: net::TcpStream, handle: &Handle) - -> io::Result - { + pub fn from_std(stream: net::TcpStream, handle: &Handle) -> io::Result { let io = mio::net::TcpStream::from_stream(stream)?; let io = PollEvented::new_with_handle(io, handle)?; @@ -149,11 +147,11 @@ impl TcpStream { /// loop. Note that on Windows you must `bind` a socket before it can be /// connected, so if a custom `TcpBuilder` is used it should be bound /// (perhaps to `INADDR_ANY`) before this method is called. - pub fn connect_std(stream: net::TcpStream, - addr: &SocketAddr, - handle: &Handle) - -> ConnectFuture - { + pub fn connect_std( + stream: net::TcpStream, + addr: &SocketAddr, + handle: &Handle, + ) -> ConnectFuture { use self::ConnectFutureState::*; let io = mio::net::TcpStream::connect_stream(stream, addr) @@ -854,7 +852,7 @@ impl<'a> AsyncRead for &'a TcpStream { fn read_buf(&mut self, buf: &mut B) -> Poll { if let Async::NotReady = self.io.poll_read_ready(mio::Ready::readable())? { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } let r = unsafe { @@ -878,10 +876,22 @@ impl<'a> AsyncRead for &'a TcpStream { let b15: &mut [u8] = &mut [0]; let b16: &mut [u8] = &mut [0]; let mut bufs: [&mut IoVec; 16] = [ - b1.into(), b2.into(), b3.into(), b4.into(), - b5.into(), b6.into(), b7.into(), b8.into(), - b9.into(), b10.into(), b11.into(), b12.into(), - b13.into(), b14.into(), b15.into(), b16.into(), + b1.into(), + b2.into(), + b3.into(), + b4.into(), + b5.into(), + b6.into(), + b7.into(), + b8.into(), + b9.into(), + b10.into(), + b11.into(), + b12.into(), + b13.into(), + b14.into(), + b15.into(), + b16.into(), ]; let n = buf.bytes_vec_mut(&mut bufs); self.io.get_ref().read_bufs(&mut bufs[..n]) @@ -889,7 +899,9 @@ impl<'a> AsyncRead for &'a TcpStream { match r { Ok(n) => { - unsafe { buf.advance_mut(n); } + unsafe { + buf.advance_mut(n); + } Ok(Async::Ready(n)) } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { @@ -908,7 +920,7 @@ impl<'a> AsyncWrite for &'a TcpStream { fn write_buf(&mut self, buf: &mut B) -> Poll { if let Async::NotReady = self.io.poll_write_ready()? { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } let r = { @@ -952,7 +964,8 @@ impl Future for ConnectFuture { impl ConnectFutureState { fn poll_inner(&mut self, f: F) -> Poll - where F: FnOnce(&mut PollEvented) -> Poll + where + F: FnOnce(&mut PollEvented) -> Poll, { { let stream = match *self { @@ -962,7 +975,7 @@ impl ConnectFutureState { ConnectFutureState::Error(e) => e, _ => panic!(), }; - return Err(e) + return Err(e); } ConnectFutureState::Empty => panic!("can't poll TCP stream twice"), }; @@ -974,11 +987,11 @@ impl ConnectFutureState { // // If all that succeeded then we ship everything on up. if let Async::NotReady = f(&mut stream.io)? { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } if let Some(e) = try!(stream.io.get_ref().take_error()) { - return Err(e) + return Err(e); } } @@ -1000,8 +1013,8 @@ impl Future for ConnectFutureState { #[cfg(unix)] mod sys { - use std::os::unix::prelude::*; use super::TcpStream; + use std::os::unix::prelude::*; impl AsRawFd for TcpStream { fn as_raw_fd(&self) -> RawFd { diff --git a/tokio-tcp/tests/chain.rs b/tokio-tcp/tests/chain.rs index c4e37f103..e76edff8d 100644 --- a/tokio-tcp/tests/chain.rs +++ b/tokio-tcp/tests/chain.rs @@ -1,21 +1,23 @@ extern crate futures; -extern crate tokio_tcp; extern crate tokio_io; +extern crate tokio_tcp; +use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; -use std::io::{Write, Read}; -use futures::Future; use futures::stream::Stream; +use futures::Future; use tokio_io::io::read_to_end; use tokio_tcp::TcpListener; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] diff --git a/tokio-tcp/tests/echo.rs b/tokio-tcp/tests/echo.rs index cee4556bf..62c1f135e 100644 --- a/tokio-tcp/tests/echo.rs +++ b/tokio-tcp/tests/echo.rs @@ -1,23 +1,25 @@ extern crate env_logger; extern crate futures; -extern crate tokio_tcp; extern crate tokio_io; +extern crate tokio_tcp; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; -use futures::Future; use futures::stream::Stream; -use tokio_tcp::TcpListener; -use tokio_io::AsyncRead; +use futures::Future; use tokio_io::io::copy; +use tokio_io::AsyncRead; +use tokio_tcp::TcpListener; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] diff --git a/tokio-tcp/tests/limit.rs b/tokio-tcp/tests/limit.rs index 8714da9a5..23ec252da 100644 --- a/tokio-tcp/tests/limit.rs +++ b/tokio-tcp/tests/limit.rs @@ -1,21 +1,23 @@ extern crate futures; -extern crate tokio_tcp; extern crate tokio_io; +extern crate tokio_tcp; +use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; -use std::io::{Write, Read}; -use futures::Future; use futures::stream::Stream; +use futures::Future; use tokio_io::io::read_to_end; use tokio_tcp::TcpListener; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] diff --git a/tokio-tcp/tests/stream-buffered.rs b/tokio-tcp/tests/stream-buffered.rs index d1ae8b418..03e512ad6 100644 --- a/tokio-tcp/tests/stream-buffered.rs +++ b/tokio-tcp/tests/stream-buffered.rs @@ -1,23 +1,25 @@ extern crate env_logger; extern crate futures; -extern crate tokio_tcp; extern crate tokio_io; +extern crate tokio_tcp; use std::io::{Read, Write}; use std::net::TcpStream; use std::thread; -use futures::Future; use futures::stream::Stream; +use futures::Future; use tokio_io::io::copy; use tokio_io::AsyncRead; use tokio_tcp::TcpListener; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] @@ -41,12 +43,13 @@ fn echo_server() { assert_eq!(&buf[..msg.len()], msg); }); - let future = srv.incoming() - .map(|s| s.split()) - .map(|(a, b)| copy(a, b).map(|_| ())) - .buffered(10) - .take(2) - .collect(); + let future = srv + .incoming() + .map(|s| s.split()) + .map(|(a, b)| copy(a, b).map(|_| ())) + .buffered(10) + .take(2) + .collect(); t!(future.wait()); diff --git a/tokio-tcp/tests/tcp.rs b/tokio-tcp/tests/tcp.rs index fbbd14c6f..0c1aca9ba 100644 --- a/tokio-tcp/tests/tcp.rs +++ b/tokio-tcp/tests/tcp.rs @@ -1,21 +1,22 @@ extern crate env_logger; +extern crate futures; +extern crate mio; extern crate tokio_io; extern crate tokio_tcp; -extern crate mio; -extern crate futures; -use std::{net, thread}; use std::sync::mpsc::channel; +use std::{net, thread}; use futures::{Future, Stream}; use tokio_tcp::{TcpListener, TcpStream}; - macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] @@ -23,9 +24,7 @@ fn connect() { drop(env_logger::try_init()); let srv = t!(net::TcpListener::bind("127.0.0.1:0")); let addr = t!(srv.local_addr()); - let t = thread::spawn(move || { - t!(srv.accept()).0 - }); + let t = thread::spawn(move || t!(srv.accept()).0); let stream = TcpStream::connect(&addr); let mine = t!(stream.wait()); @@ -42,14 +41,16 @@ fn accept() { let addr = t!(srv.local_addr()); let (tx, rx) = channel(); - let client = srv.incoming().map(move |t| { - tx.send(()).unwrap(); - t - }).into_future().map_err(|e| e.0); + let client = srv + .incoming() + .map(move |t| { + tx.send(()).unwrap(); + t + }) + .into_future() + .map_err(|e| e.0); assert!(rx.try_recv().is_err()); - let t = thread::spawn(move || { - net::TcpStream::connect(&addr).unwrap() - }); + let t = thread::spawn(move || net::TcpStream::connect(&addr).unwrap()); let (mine, _remaining) = t!(client.wait()); let mine = mine.unwrap(); @@ -65,15 +66,17 @@ fn accept2() { let srv = t!(TcpListener::bind(&t!("127.0.0.1:0".parse()))); let addr = t!(srv.local_addr()); - let t = thread::spawn(move || { - net::TcpStream::connect(&addr).unwrap() - }); + let t = thread::spawn(move || net::TcpStream::connect(&addr).unwrap()); let (tx, rx) = channel(); - let client = srv.incoming().map(move |t| { - tx.send(()).unwrap(); - t - }).into_future().map_err(|e| e.0); + let client = srv + .incoming() + .map(move |t| { + tx.send(()).unwrap(); + t + }) + .into_future() + .map_err(|e| e.0); assert!(rx.try_recv().is_err()); let (mine, _remaining) = t!(client.wait()); @@ -86,13 +89,13 @@ mod unix { use tokio_tcp::TcpStream; use env_logger; - use futures::{Future, future}; + use futures::{future, Future}; use mio::unix::UnixReady; use tokio_io::AsyncRead; use std::io::Write; - use std::{net, thread}; use std::time::Duration; + use std::{net, thread}; #[test] fn poll_hup() { @@ -109,21 +112,21 @@ mod unix { let mut stream = t!(TcpStream::connect(&addr).wait()); // Poll for HUP before reading. - future::poll_fn(|| { - stream.poll_read_ready(UnixReady::hup().into()) - }).wait().unwrap(); + future::poll_fn(|| stream.poll_read_ready(UnixReady::hup().into())) + .wait() + .unwrap(); // Same for write half - future::poll_fn(|| { - stream.poll_write_ready() - }).wait().unwrap(); + future::poll_fn(|| stream.poll_write_ready()) + .wait() + .unwrap(); let mut buf = vec![0; 11]; // Read the data - future::poll_fn(|| { - stream.poll_read(&mut buf) - }).wait().unwrap(); + future::poll_fn(|| stream.poll_read(&mut buf)) + .wait() + .unwrap(); assert_eq!(b"hello world", &buf[..]); diff --git a/tokio-threadpool/benches/basic.rs b/tokio-threadpool/benches/basic.rs index e2d43bbd8..70dee74f5 100644 --- a/tokio-threadpool/benches/basic.rs +++ b/tokio-threadpool/benches/basic.rs @@ -1,11 +1,11 @@ #![feature(test)] #![deny(warnings)] -extern crate tokio_threadpool; extern crate futures; extern crate futures_cpupool; extern crate num_cpus; extern crate test; +extern crate tokio_threadpool; const NUM_SPAWN: usize = 10_000; const NUM_YIELD: usize = 1_000; @@ -13,12 +13,12 @@ const TASKS_PER_CPU: usize = 50; mod threadpool { use futures::{future, task, Async}; - use tokio_threadpool::*; use num_cpus; - use test; - use std::sync::{mpsc, Arc}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; + use std::sync::{mpsc, Arc}; + use test; + use tokio_threadpool::*; #[bench] fn spawn_many(b: &mut test::Bencher) { @@ -90,14 +90,14 @@ mod threadpool { // See rust-lang-nursery/futures-rs#617 // mod cpupool { - use futures::{task, Async}; use futures::future::{self, Executor}; + use futures::{task, Async}; use futures_cpupool::*; use num_cpus; - use test; - use std::sync::{mpsc, Arc}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; + use std::sync::{mpsc, Arc}; + use test; #[bench] fn spawn_many(b: &mut test::Bencher) { @@ -119,7 +119,9 @@ mod cpupool { } Ok(()) - })).ok().unwrap(); + })) + .ok() + .unwrap(); } let _ = rx.recv().unwrap(); @@ -151,7 +153,9 @@ mod cpupool { // Not ready Ok(Async::NotReady) } - })).ok().unwrap(); + })) + .ok() + .unwrap(); } for _ in 0..tasks { diff --git a/tokio-threadpool/benches/blocking.rs b/tokio-threadpool/benches/blocking.rs index ea432c885..8ea900eaa 100644 --- a/tokio-threadpool/benches/blocking.rs +++ b/tokio-threadpool/benches/blocking.rs @@ -3,9 +3,9 @@ extern crate futures; extern crate rand; -extern crate tokio_threadpool; -extern crate threadpool; extern crate test; +extern crate threadpool; +extern crate tokio_threadpool; const ITER: usize = 1_000; @@ -13,14 +13,11 @@ mod blocking { use super::*; use futures::future::*; - use tokio_threadpool::{Builder, blocking}; + use tokio_threadpool::{blocking, Builder}; #[bench] fn cpu_bound(b: &mut test::Bencher) { - let pool = Builder::new() - .pool_size(2) - .max_blocking(20) - .build(); + let pool = Builder::new().pool_size(2).max_blocking(20).build(); b.iter(|| { let count_down = Arc::new(CountDown::new(::ITER)); @@ -29,17 +26,12 @@ mod blocking { let count_down = count_down.clone(); pool.spawn(lazy(move || { - poll_fn(|| { - blocking(|| { - perform_complex_computation() + poll_fn(|| blocking(|| perform_complex_computation()).map_err(|_| panic!())) + .and_then(move |_| { + // Do something with the value + count_down.dec(); + Ok(()) }) - .map_err(|_| panic!()) - }) - .and_then(move |_| { - // Do something with the value - count_down.dec(); - Ok(()) - }) })); } @@ -57,10 +49,7 @@ mod message_passing { #[bench] fn cpu_bound(b: &mut test::Bencher) { - let pool = Builder::new() - .pool_size(2) - .max_blocking(20) - .build(); + let pool = Builder::new().pool_size(2).max_blocking(20).build(); let blocking = threadpool::ThreadPool::new(20); @@ -85,7 +74,8 @@ mod message_passing { rx.and_then(move |_| { count_down.dec(); Ok(()) - }).map_err(|_| panic!()) + }) + .map_err(|_| panic!()) })); } @@ -104,9 +94,9 @@ fn perform_complex_computation() -> usize { // Util for waiting until the tasks complete -use std::sync::*; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::*; +use std::sync::*; struct CountDown { rem: AtomicUsize, diff --git a/tokio-threadpool/benches/depth.rs b/tokio-threadpool/benches/depth.rs index d500ad4ae..2d89ac90d 100644 --- a/tokio-threadpool/benches/depth.rs +++ b/tokio-threadpool/benches/depth.rs @@ -1,19 +1,19 @@ #![feature(test)] #![deny(warnings)] -extern crate tokio_threadpool; extern crate futures; extern crate futures_cpupool; extern crate num_cpus; extern crate test; +extern crate tokio_threadpool; const ITER: usize = 20_000; mod us { - use tokio_threadpool::*; use futures::future; - use test; use std::sync::mpsc; + use test; + use tokio_threadpool::*; #[bench] fn chained_spawn(b: &mut test::Bencher) { @@ -24,10 +24,12 @@ mod us { res_tx.send(()).unwrap(); } else { let pool_tx2 = pool_tx.clone(); - pool_tx.spawn(future::lazy(move || { - spawn(pool_tx2, res_tx, n - 1); - Ok(()) - })).unwrap(); + pool_tx + .spawn(future::lazy(move || { + spawn(pool_tx2, res_tx, n - 1); + Ok(()) + })) + .unwrap(); } } @@ -44,8 +46,8 @@ mod cpupool { use futures::future::{self, Executor}; use futures_cpupool::*; use num_cpus; - use test; use std::sync::mpsc; + use test; #[bench] fn chained_spawn(b: &mut test::Bencher) { @@ -59,7 +61,9 @@ mod cpupool { pool.execute(future::lazy(move || { spawn(pool2, res_tx, n - 1); Ok(()) - })).ok().unwrap(); + })) + .ok() + .unwrap(); } } diff --git a/tokio-threadpool/examples/depth.rs b/tokio-threadpool/examples/depth.rs index 7957f09ed..3d376dd38 100644 --- a/tokio-threadpool/examples/depth.rs +++ b/tokio-threadpool/examples/depth.rs @@ -1,9 +1,9 @@ +extern crate env_logger; extern crate futures; extern crate tokio_threadpool; -extern crate env_logger; -use tokio_threadpool::*; use futures::future::{self, Executor}; +use tokio_threadpool::*; use std::sync::mpsc; @@ -22,7 +22,9 @@ fn chained_spawn() { tx.execute(future::lazy(move || { spawn(tx2, res_tx, n - 1); Ok(()) - })).ok().unwrap(); + })) + .ok() + .unwrap(); } } diff --git a/tokio-threadpool/examples/hello.rs b/tokio-threadpool/examples/hello.rs index 3324f862a..87eb688c2 100644 --- a/tokio-threadpool/examples/hello.rs +++ b/tokio-threadpool/examples/hello.rs @@ -1,10 +1,10 @@ +extern crate env_logger; extern crate futures; extern crate tokio_threadpool; -extern crate env_logger; -use tokio_threadpool::*; -use futures::*; use futures::sync::oneshot; +use futures::*; +use tokio_threadpool::*; pub fn main() { let _ = ::env_logger::init(); @@ -12,10 +12,13 @@ pub fn main() { let pool = ThreadPool::new(); let tx = pool.sender().clone(); - let res = oneshot::spawn(future::lazy(|| { - println!("Running on the pool"); - Ok::<_, ()>("complete") - }), &tx); + let res = oneshot::spawn( + future::lazy(|| { + println!("Running on the pool"); + Ok::<_, ()>("complete") + }), + &tx, + ); println!("Result: {:?}", res.wait()); } diff --git a/tokio-threadpool/src/blocking.rs b/tokio-threadpool/src/blocking.rs index 88cdd15fe..9f91234b9 100644 --- a/tokio-threadpool/src/blocking.rs +++ b/tokio-threadpool/src/blocking.rs @@ -122,7 +122,8 @@ pub struct BlockingError { /// } /// ``` pub fn blocking(f: F) -> Poll -where F: FnOnce() -> T, +where + F: FnOnce() -> T, { let res = Worker::with_current(|worker| { let worker = match worker { @@ -148,8 +149,7 @@ where F: FnOnce() -> T, // back ownership of the worker if the worker handoff didn't complete yet. Worker::with_current(|worker| { // Worker must be set since it was above. - worker.unwrap() - .transition_from_blocking(); + worker.unwrap().transition_from_blocking(); }); // Return the result diff --git a/tokio-threadpool/src/builder.rs b/tokio-threadpool/src/builder.rs index 82c7cac65..1cb2ec520 100644 --- a/tokio-threadpool/src/builder.rs +++ b/tokio-threadpool/src/builder.rs @@ -1,21 +1,21 @@ use callback::Callback; use config::{Config, MAX_WORKERS}; use park::{BoxPark, BoxedPark, DefaultPark}; -use shutdown::ShutdownTrigger; use pool::{Pool, MAX_BACKUP}; +use shutdown::ShutdownTrigger; use thread_pool::ThreadPool; use worker::{self, Worker, WorkerId}; +use std::cmp::max; use std::error::Error; use std::fmt; use std::sync::Arc; use std::time::Duration; -use std::cmp::max; use crossbeam_deque::Injector; use num_cpus; -use tokio_executor::Enter; use tokio_executor::park::Park; +use tokio_executor::Enter; /// Builds a thread pool with custom configuration values. /// @@ -93,10 +93,8 @@ impl Builder { pub fn new() -> Builder { let num_cpus = max(1, num_cpus::get()); - let new_park = Box::new(|_: &WorkerId| { - Box::new(BoxedPark::new(DefaultPark::new())) - as BoxPark - }); + let new_park = + Box::new(|_: &WorkerId| Box::new(BoxedPark::new(DefaultPark::new())) as BoxPark); Builder { pool_size: num_cpus, @@ -280,7 +278,8 @@ impl Builder { /// /// [`Worker::run`]: struct.Worker.html#method.run pub fn around_worker(&mut self, f: F) -> &mut Self - where F: Fn(&Worker, &mut Enter) + Send + Sync + 'static + where + F: Fn(&Worker, &mut Enter) + Send + Sync + 'static, { self.config.around_worker = Some(Callback::new(f)); self @@ -307,7 +306,8 @@ impl Builder { /// # } /// ``` pub fn after_start(&mut self, f: F) -> &mut Self - where F: Fn() + Send + Sync + 'static + where + F: Fn() + Send + Sync + 'static, { self.config.after_start = Some(Arc::new(f)); self @@ -333,7 +333,8 @@ impl Builder { /// # } /// ``` pub fn before_stop(&mut self, f: F) -> &mut Self - where F: Fn() + Send + Sync + 'static + where + F: Fn() + Send + Sync + 'static, { self.config.before_stop = Some(Arc::new(f)); self @@ -369,13 +370,12 @@ impl Builder { /// # } /// ``` pub fn custom_park(&mut self, f: F) -> &mut Self - where F: Fn(&WorkerId) -> P + 'static, - P: Park + Send + 'static, - P::Error: Error, + where + F: Fn(&WorkerId) -> P + 'static, + P: Park + Send + 'static, + P::Error: Error, { - self.new_park = Box::new(move |id| { - Box::new(BoxedPark::new(f(id))) - }); + self.new_park = Box::new(move |id| Box::new(BoxedPark::new(f(id)))); self } diff --git a/tokio-threadpool/src/callback.rs b/tokio-threadpool/src/callback.rs index e269872a9..aabf876f4 100644 --- a/tokio-threadpool/src/callback.rs +++ b/tokio-threadpool/src/callback.rs @@ -12,7 +12,8 @@ pub(crate) struct Callback { impl Callback { pub fn new(f: F) -> Self - where F: Fn(&Worker, &mut Enter) + Send + Sync + 'static + where + F: Fn(&Worker, &mut Enter) + Send + Sync + 'static, { Callback { f: Arc::new(f) } } diff --git a/tokio-threadpool/src/lib.rs b/tokio-threadpool/src/lib.rs index 94d86700e..4ea3d6a9f 100644 --- a/tokio-threadpool/src/lib.rs +++ b/tokio-threadpool/src/lib.rs @@ -159,5 +159,5 @@ pub use blocking::{blocking, BlockingError}; pub use builder::Builder; pub use sender::Sender; pub use shutdown::Shutdown; -pub use thread_pool::{ThreadPool, SpawnHandle}; +pub use thread_pool::{SpawnHandle, ThreadPool}; pub use worker::{Worker, WorkerId}; diff --git a/tokio-threadpool/src/park/boxed.rs b/tokio-threadpool/src/park/boxed.rs index bd3671d48..8beaa0bb5 100644 --- a/tokio-threadpool/src/park/boxed.rs +++ b/tokio-threadpool/src/park/boxed.rs @@ -15,7 +15,8 @@ impl BoxedPark { } impl Park for BoxedPark -where T::Error: Error, +where + T::Error: Error, { type Unpark = BoxUnpark; type Error = (); @@ -25,16 +26,20 @@ where T::Error: Error, } fn park(&mut self) -> Result<(), Self::Error> { - self.0.park() - .map_err(|e| { - warn!("calling `park` on worker thread errored -- shutting down thread: {}", e); - }) + self.0.park().map_err(|e| { + warn!( + "calling `park` on worker thread errored -- shutting down thread: {}", + e + ); + }) } fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> { - self.0.park_timeout(duration) - .map_err(|e| { - warn!("calling `park` on worker thread errored -- shutting down thread: {}", e); - }) + self.0.park_timeout(duration).map_err(|e| { + warn!( + "calling `park` on worker thread errored -- shutting down thread: {}", + e + ); + }) } } diff --git a/tokio-threadpool/src/pool/backup.rs b/tokio-threadpool/src/pool/backup.rs index feaff3065..e94e95d6f 100644 --- a/tokio-threadpool/src/pool/backup.rs +++ b/tokio-threadpool/src/pool/backup.rs @@ -1,10 +1,10 @@ use park::DefaultPark; -use worker::{WorkerId}; +use worker::WorkerId; use std::cell::UnsafeCell; use std::fmt; use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::{self, Acquire, AcqRel, Relaxed}; +use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed}; use std::time::{Duration, Instant}; /// State associated with a thread in the thread pool. @@ -100,9 +100,11 @@ impl Backup { }); // The handoff value is equal to `worker_id` - debug_assert_eq!(unsafe { (*self.handoff.get()).as_ref() }, Some(worker_id)); + debug_assert_eq!(unsafe { (*self.handoff.get()).as_ref() }, Some(worker_id)); - unsafe { *self.handoff.get() = None; } + unsafe { + *self.handoff.get() = None; + } } pub fn is_running(&self) -> bool { @@ -167,10 +169,7 @@ impl Backup { return Handoff::Terminated; } - let worker_id = unsafe { - (*self.handoff.get()).take() - .expect("no worker handoff") - }; + let worker_id = unsafe { (*self.handoff.get()).take().expect("no worker handoff") }; return Handoff::Worker(worker_id); } @@ -192,10 +191,10 @@ impl Backup { let mut next = state; next.unset_running(); - let actual = self.state.compare_and_swap( - state.into(), - next.into(), - AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { debug_assert!(!next.is_running()); @@ -226,7 +225,9 @@ impl Backup { #[inline] pub fn set_next_sleeper(&self, val: BackupId) { - unsafe { *self.next_sleeper.get() = val; } + unsafe { + *self.next_sleeper.get() = val; + } } } @@ -271,8 +272,9 @@ impl State { next.set_running(); next.unset_pushed(); - let actual = state.compare_and_swap( - curr.into(), next.into(), AcqRel).into(); + let actual = state + .compare_and_swap(curr.into(), next.into(), AcqRel) + .into(); if actual == curr { return curr; diff --git a/tokio-threadpool/src/pool/backup_stack.rs b/tokio-threadpool/src/pool/backup_stack.rs index aa69e1430..b9a46d08e 100644 --- a/tokio-threadpool/src/pool/backup_stack.rs +++ b/tokio-threadpool/src/pool/backup_stack.rs @@ -1,7 +1,7 @@ use pool::{Backup, BackupId}; use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::{Acquire, AcqRel}; +use std::sync::atomic::Ordering::{AcqRel, Acquire}; #[derive(Debug)] pub(crate) struct BackupStack { @@ -65,8 +65,10 @@ impl BackupStack { entries[id.0].set_next_sleeper(head); next.set_head(id); - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if state == actual { return Ok(()); @@ -110,8 +112,10 @@ impl BackupStack { return Ok(None); } - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual != state { state = actual; @@ -138,8 +142,10 @@ impl BackupStack { next.set_head(next_head); } - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { debug_assert!(entries[head.0].is_pushed()); diff --git a/tokio-threadpool/src/pool/mod.rs b/tokio-threadpool/src/pool/mod.rs index 2326fca04..929178354 100644 --- a/tokio-threadpool/src/pool/mod.rs +++ b/tokio-threadpool/src/pool/mod.rs @@ -4,11 +4,7 @@ mod state; pub(crate) use self::backup::{Backup, BackupId}; pub(crate) use self::backup_stack::MAX_BACKUP; -pub(crate) use self::state::{ - State, - Lifecycle, - MAX_FUTURES, -}; +pub(crate) use self::state::{Lifecycle, State, MAX_FUTURES}; use self::backup::Handoff; use self::backup_stack::BackupStack; @@ -22,8 +18,8 @@ use futures::Poll; use std::cell::Cell; use std::num::Wrapping; -use std::sync::atomic::Ordering::{Acquire, AcqRel}; use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::{AcqRel, Acquire}; use std::sync::{Arc, Weak}; use std::thread; @@ -100,15 +96,15 @@ impl Pool { // // This is `backup + pool_size` because the core thread pool running the // workers is spawned from backup as well. - let backup = (0..total_size).map(|_| { - Backup::new() - }).collect::>().into_boxed_slice(); + let backup = (0..total_size) + .map(|_| Backup::new()) + .collect::>() + .into_boxed_slice(); let backup_stack = BackupStack::new(); for i in (0..backup.len()).rev() { - backup_stack.push(&backup, BackupId(i)) - .unwrap(); + backup_stack.push(&backup, BackupId(i)).unwrap(); } // Initialize the blocking state @@ -174,8 +170,10 @@ impl Pool { } } - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if state == actual { state = next; @@ -299,8 +297,7 @@ impl Pool { } }; - let need_spawn = self.backup[backup_id.0] - .worker_handoff(id.clone()); + let need_spawn = self.backup[backup_id.0].worker_handoff(id.clone()); if !need_spawn { return; @@ -355,8 +352,7 @@ impl Pool { // available for future handoffs. // // This **must** happen before notifying the task. - let res = pool.backup_stack - .push(&pool.backup, backup_id); + let res = pool.backup_stack.push(&pool.backup, backup_id); if res.is_err() { // The pool is being shutdown. @@ -370,8 +366,7 @@ impl Pool { debug_assert!(pool.backup[backup_id.0].is_running()); // Wait for a handoff - let handoff = pool.backup[backup_id.0] - .wait_for_handoff(pool.config.keep_alive); + let handoff = pool.backup[backup_id.0].wait_for_handoff(pool.config.keep_alive); match handoff { Handoff::Worker(id) => { @@ -407,7 +402,8 @@ impl Pool { debug_assert!( worker_state.lifecycle() != Signaled, - "actual={:?}", worker_state.lifecycle(), + "actual={:?}", + worker_state.lifecycle(), ); trace!("signal_work -- notify; idx={}", idx); diff --git a/tokio-threadpool/src/pool/state.rs b/tokio-threadpool/src/pool/state.rs index e8f5d12e4..5ecb514e5 100644 --- a/tokio-threadpool/src/pool/state.rs +++ b/tokio-threadpool/src/pool/state.rs @@ -82,8 +82,7 @@ impl State { } pub fn is_terminated(&self) -> bool { - self.lifecycle() == Lifecycle::ShutdownNow && - self.num_futures() == 0 + self.lifecycle() == Lifecycle::ShutdownNow && self.num_futures() == 0 } } @@ -115,9 +114,10 @@ impl From for Lifecycle { use self::Lifecycle::*; debug_assert!( - src == Running as usize || - src == ShutdownOnIdle as usize || - src == ShutdownNow as usize); + src == Running as usize + || src == ShutdownOnIdle as usize + || src == ShutdownNow as usize + ); unsafe { ::std::mem::transmute(src) } } diff --git a/tokio-threadpool/src/sender.rs b/tokio-threadpool/src/sender.rs index de5f0e077..15befd436 100644 --- a/tokio-threadpool/src/sender.rs +++ b/tokio-threadpool/src/sender.rs @@ -1,11 +1,11 @@ -use pool::{self, Pool, Lifecycle, MAX_FUTURES}; +use pool::{self, Lifecycle, Pool, MAX_FUTURES}; use task::Task; -use std::sync::Arc; use std::sync::atomic::Ordering::{AcqRel, Acquire}; +use std::sync::Arc; -use tokio_executor::{self, SpawnError}; use futures::{future, Future}; +use tokio_executor::{self, SpawnError}; /// Submit futures to the associated thread pool for execution. /// @@ -77,7 +77,8 @@ impl Sender { /// # } /// ``` pub fn spawn(&self, future: F) -> Result<(), SpawnError> - where F: Future + Send + 'static, + where + F: Future + Send + 'static, { let mut s = self; tokio_executor::Executor::spawn(&mut s, Box::new(future)) @@ -104,8 +105,11 @@ impl Sender { next.inc_num_futures(); - let actual = self.pool.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .pool + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { trace!("execute; count={:?}", next.num_futures()); @@ -125,9 +129,10 @@ impl tokio_executor::Executor for Sender { tokio_executor::Executor::status(&s) } - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError> - { + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError> { let mut s = &*self; tokio_executor::Executor::spawn(&mut s, future) } @@ -150,9 +155,10 @@ impl<'a> tokio_executor::Executor for &'a Sender { Ok(()) } - fn spawn(&mut self, future: Box + Send>) - -> Result<(), SpawnError> - { + fn spawn( + &mut self, + future: Box + Send>, + ) -> Result<(), SpawnError> { self.prepare_for_spawn()?; // At this point, the pool has accepted the future, so schedule it for @@ -171,7 +177,8 @@ impl<'a> tokio_executor::Executor for &'a Sender { } impl future::Executor for Sender -where T: Future + Send + 'static, +where + T: Future + Send + 'static, { fn execute(&self, future: T) -> Result<(), future::ExecuteError> { if let Err(e) = tokio_executor::Executor::status(self) { diff --git a/tokio-threadpool/src/shutdown.rs b/tokio-threadpool/src/shutdown.rs index 290cb182c..c3d04a002 100644 --- a/tokio-threadpool/src/shutdown.rs +++ b/tokio-threadpool/src/shutdown.rs @@ -2,8 +2,8 @@ use task::Task; use worker; use crossbeam_deque::Injector; -use futures::{Future, Poll, Async}; use futures::task::AtomicTask; +use futures::{Async, Future, Poll}; use std::sync::{Arc, Mutex}; diff --git a/tokio-threadpool/src/task/blocking.rs b/tokio-threadpool/src/task/blocking.rs index cdf2cefff..ded59edfe 100644 --- a/tokio-threadpool/src/task/blocking.rs +++ b/tokio-threadpool/src/task/blocking.rs @@ -1,14 +1,14 @@ use pool::Pool; -use task::{Task, BlockingState}; +use task::{BlockingState, Task}; -use futures::{Poll, Async}; +use futures::{Async, Poll}; use std::cell::UnsafeCell; use std::fmt; use std::ptr; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::{Acquire, Release, AcqRel, Relaxed}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use std::sync::Arc; use std::thread; /// Manages the state around entering a blocking section and tasks that are @@ -172,10 +172,10 @@ impl Blocking { debug_assert_ne!(curr.0, 0); debug_assert_ne!(next.0, 0); - let actual = self.state.compare_and_swap( - curr.into(), - next.into(), - AcqRel).into(); + let actual = self + .state + .compare_and_swap(curr.into(), next.into(), AcqRel) + .into(); if curr == actual { break; @@ -190,8 +190,7 @@ impl Blocking { // Finish pushing unsafe { - (*prev).next_blocking - .store(ptr as *mut _, Release); + (*prev).next_blocking.store(ptr as *mut _, Release); } // The node was queued to be notified once capacity is made @@ -245,7 +244,6 @@ impl Blocking { pub fn notify_task(&self, pool: &Arc) { let prev = self.lock.fetch_add(1, AcqRel); - if prev != 0 { // Another thread has the lock and will be responsible for notifying // pending tasks. @@ -287,8 +285,7 @@ impl Blocking { /// there are no more tasks to pop, `rem` is used to set the remaining /// capacity. fn pop(&self, rem: usize) -> Option> { - 'outer: - loop { + 'outer: loop { unsafe { let mut tail = *self.tail.get(); let mut next = (*tail).next_blocking.load(Acquire); @@ -330,10 +327,10 @@ impl Blocking { // pops that will come after the current one. after.add_capacity(rem + 1, &self.stub); - let actual: State = self.state.compare_and_swap( - curr.into(), - after.into(), - AcqRel).into(); + let actual: State = self + .state + .compare_and_swap(curr.into(), after.into(), AcqRel) + .into(); if actual == curr { // Successfully returned the remaining capacity diff --git a/tokio-threadpool/src/task/mod.rs b/tokio-threadpool/src/task/mod.rs index fe535b30d..2dd00c591 100644 --- a/tokio-threadpool/src/task/mod.rs +++ b/tokio-threadpool/src/task/mod.rs @@ -9,14 +9,14 @@ use self::state::State; use notifier::Notifier; use pool::Pool; -use futures::{self, Future, Async}; use futures::executor::{self, Spawn}; +use futures::{self, Async, Future}; -use std::{fmt, panic, ptr}; use std::cell::{Cell, UnsafeCell}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; +use std::sync::atomic::{AtomicPtr, AtomicUsize}; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, AtomicPtr}; -use std::sync::atomic::Ordering::{AcqRel, Acquire, Release, Relaxed}; +use std::{fmt, panic, ptr}; /// Harness around a future. /// @@ -103,15 +103,20 @@ impl Task { // Transition task to running state. At this point, the task must be // scheduled. - let actual: State = self.state.compare_and_swap( - Scheduled.into(), Running.into(), AcqRel).into(); + let actual: State = self + .state + .compare_and_swap(Scheduled.into(), Running.into(), AcqRel) + .into(); match actual { - Scheduled => {}, + Scheduled => {} _ => panic!("unexpected task state; {:?}", actual), } - trace!("Task::run; state={:?}", State::from(self.state.load(Relaxed))); + trace!( + "Task::run; state={:?}", + State::from(self.state.load(Relaxed)) + ); // The transition to `Running` done above ensures that a lock on the // future has been obtained. @@ -136,8 +141,10 @@ impl Task { let mut g = Guard(fut, true); - let ret = g.0.as_mut().unwrap() - .poll_future_notify(unpark, self as *const _ as usize); + let ret = + g.0.as_mut() + .unwrap() + .poll_future_notify(unpark, self as *const _ as usize); g.1 = false; @@ -168,8 +175,10 @@ impl Task { // fails, then the task has been unparked concurrent to running, // in which case it transitions immediately back to scheduled // and we return `true`. - let prev: State = self.state.compare_and_swap( - Running.into(), Idle.into(), AcqRel).into(); + let prev: State = self + .state + .compare_and_swap(Running.into(), Idle.into(), AcqRel) + .into(); match prev { Running => Run::Idle, @@ -202,10 +211,10 @@ impl Task { } } - let actual = self.state.compare_and_swap( - state.into(), - Aborted.into(), - AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), Aborted.into(), AcqRel) + .into(); if actual == state { // The future has been aborted. Drop it immediately to free resources and run drop @@ -239,10 +248,10 @@ impl Task { loop { // Scheduling can only be done from the `Idle` state. - let actual = self.state.compare_and_swap( - Idle.into(), - Scheduled.into(), - AcqRel).into(); + let actual = self + .state + .compare_and_swap(Idle.into(), Scheduled.into(), AcqRel) + .into(); match actual { Idle => return true, @@ -250,8 +259,10 @@ impl Task { // The task is already running on another thread. Transition // the state to `Notified`. If this CAS fails, then restart // the logic again from `Idle`. - let actual = self.state.compare_and_swap( - Running.into(), Notified.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(Running.into(), Notified.into(), AcqRel) + .into(); match actual { Idle => continue, diff --git a/tokio-threadpool/src/task/state.rs b/tokio-threadpool/src/task/state.rs index e01501c21..3e00f89bc 100644 --- a/tokio-threadpool/src/task/state.rs +++ b/tokio-threadpool/src/task/state.rs @@ -41,8 +41,10 @@ impl From for State { use self::State::*; debug_assert!( - src >= Idle as usize && - src <= Aborted as usize, "actual={}", src); + src >= Idle as usize && src <= Aborted as usize, + "actual={}", + src + ); unsafe { ::std::mem::transmute(src) } } diff --git a/tokio-threadpool/src/thread_pool.rs b/tokio-threadpool/src/thread_pool.rs index 960ffb780..30f58e96a 100644 --- a/tokio-threadpool/src/thread_pool.rs +++ b/tokio-threadpool/src/thread_pool.rs @@ -3,8 +3,8 @@ use pool::Pool; use sender::Sender; use shutdown::{Shutdown, ShutdownTrigger}; -use futures::{Future, Poll}; use futures::sync::oneshot; +use futures::{Future, Poll}; use std::sync::Arc; @@ -36,10 +36,7 @@ impl ThreadPool { Builder::new().build() } - pub(crate) fn new2( - pool: Arc, - trigger: Arc, - ) -> ThreadPool { + pub(crate) fn new2(pool: Arc, trigger: Arc) -> ThreadPool { ThreadPool { inner: Some(Inner { sender: Sender { pool }, @@ -80,18 +77,19 @@ impl ThreadPool { /// This function panics if the spawn fails. Use [`Sender::spawn`] for a /// version that returns a `Result` instead of panicking. pub fn spawn(&self, future: F) - where F: Future + Send + 'static, + where + F: Future + Send + 'static, { self.sender().spawn(future).unwrap(); } - /// Spawn a future on to the thread pool, return a future representing + /// Spawn a future on to the thread pool, return a future representing /// the produced value. - /// - /// The SpawnHandle returned is a future that is a proxy for future itself. - /// When future completes on this thread pool then the SpawnHandle will itself + /// + /// The SpawnHandle returned is a future that is a proxy for future itself. + /// When future completes on this thread pool then the SpawnHandle will itself /// be resolved. - /// + /// /// # Examples /// /// ```rust @@ -105,7 +103,7 @@ impl ThreadPool { /// let thread_pool = ThreadPool::new(); /// /// let handle = thread_pool.spawn_handle(lazy(|| Ok::<_, ()>(42))); - /// + /// /// let value = handle.wait().unwrap(); /// assert_eq!(value, 42); /// @@ -116,9 +114,9 @@ impl ThreadPool { /// /// # Panics /// - /// This function panics if the spawn fails. + /// This function panics if the spawn fails. pub fn spawn_handle(&self, future: F) -> SpawnHandle - where + where F: Future + Send + 'static, F::Item: Send + 'static, F::Error: Send + 'static, @@ -201,10 +199,10 @@ impl Drop for ThreadPool { } /// Handle returned from ThreadPool::spawn_handle. -/// -/// This handle is a future representing the completion of a different future -/// spawned on to the thread pool. Created through the ThreadPool::spawn_handle -/// function this handle will resolve when the future provided resolves on the +/// +/// This handle is a future representing the completion of a different future +/// spawned on to the thread pool. Created through the ThreadPool::spawn_handle +/// function this handle will resolve when the future provided resolves on the /// thread pool. #[derive(Debug)] pub struct SpawnHandle(oneshot::SpawnHandle); diff --git a/tokio-threadpool/src/worker/entry.rs b/tokio-threadpool/src/worker/entry.rs index e3a363276..0dcf5108b 100644 --- a/tokio-threadpool/src/worker/entry.rs +++ b/tokio-threadpool/src/worker/entry.rs @@ -4,9 +4,9 @@ use worker::state::{State, PUSHED_MASK}; use std::cell::UnsafeCell; use std::fmt; -use std::sync::Arc; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::atomic::Ordering::{Acquire, AcqRel, Relaxed, Release}; +use std::sync::Arc; use std::time::Duration; use crossbeam_deque::{Steal, Stealer, Worker}; @@ -102,9 +102,10 @@ impl WorkerEntry { let mut next = state; next.notify(); - let actual = self.state.compare_and_swap( - state.into(), next.into(), - AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if state == actual { break; @@ -169,8 +170,10 @@ impl WorkerEntry { next.set_lifecycle(Signaled); - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { break; @@ -307,7 +310,9 @@ impl WorkerEntry { #[inline] pub fn set_next_sleeper(&self, val: usize) { - unsafe { *self.next_sleeper.get() = val; } + unsafe { + *self.next_sleeper.get() = val; + } } } diff --git a/tokio-threadpool/src/worker/mod.rs b/tokio-threadpool/src/worker/mod.rs index 939d0063f..d380c5d56 100644 --- a/tokio-threadpool/src/worker/mod.rs +++ b/tokio-threadpool/src/worker/mod.rs @@ -2,24 +2,19 @@ mod entry; mod stack; mod state; -pub(crate) use self::entry::{ - WorkerEntry as Entry, -}; +pub(crate) use self::entry::WorkerEntry as Entry; pub(crate) use self::stack::Stack; -pub(crate) use self::state::{ - State, - Lifecycle, -}; +pub(crate) use self::state::{Lifecycle, State}; -use pool::{self, Pool, BackupId}; use notifier::Notifier; +use pool::{self, BackupId, Pool}; use sender::Sender; use shutdown::ShutdownTrigger; -use task::{self, Task, CanBlock}; +use task::{self, CanBlock, Task}; use tokio_executor; -use futures::{Poll, Async}; +use futures::{Async, Poll}; use std::cell::Cell; use std::marker::PhantomData; @@ -339,8 +334,11 @@ impl Worker { } } - let actual = self.entry().state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .entry() + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { break; @@ -417,8 +415,11 @@ impl Worker { self.run_task(task, notify); - trace!("try_steal_task -- signal_work; self={}; from={}", - self.id.0, idx); + trace!( + "try_steal_task -- signal_work; self={}; from={}", + self.id.0, + idx + ); // Signal other workers that work is available // @@ -485,8 +486,11 @@ impl Worker { let mut next = state; next.dec_num_futures(); - let actual = self.pool.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .pool + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { trace!("task complete; state={:?}", next); @@ -526,11 +530,7 @@ impl Worker { /// /// Great care is needed to ensure that `current_task` is unset in this /// function. - fn run_task2(&self, - task: &Arc, - notify: &Arc) - -> task::Run - { + fn run_task2(&self, task: &Arc, notify: &Arc) -> task::Run { struct Guard<'a> { worker: &'a Worker, } @@ -562,9 +562,7 @@ impl Worker { // Create the guard, this ensures that `current_task` is unset when the // function returns, even if the return is caused by a panic. - let _g = Guard { - worker: self, - }; + let _g = Guard { worker: self }; task.run(notify) } @@ -609,8 +607,11 @@ impl Worker { } } - let actual = self.entry().state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .entry() + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { if state.is_notified() { @@ -668,8 +669,11 @@ impl Worker { let mut next = state; next.set_lifecycle(Running); - let actual = self.entry().state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .entry() + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { return true; diff --git a/tokio-threadpool/src/worker/stack.rs b/tokio-threadpool/src/worker/stack.rs index b0b786ed0..d02c277fe 100644 --- a/tokio-threadpool/src/worker/stack.rs +++ b/tokio-threadpool/src/worker/stack.rs @@ -1,9 +1,9 @@ use config::MAX_WORKERS; use worker; -use std::{fmt, usize}; use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::{Acquire, AcqRel, Relaxed}; +use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed}; +use std::{fmt, usize}; /// Lock-free stack of sleeping workers. /// @@ -90,8 +90,10 @@ impl Stack { entries[idx].set_next_sleeper(head); next.set_head(idx); - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if state == actual { return Ok(()); @@ -112,11 +114,12 @@ impl Stack { /// Returns the index of the popped worker and the worker's observed state. /// /// `None` if the stack is empty. - pub fn pop(&self, entries: &[worker::Entry], - max_lifecycle: worker::Lifecycle, - terminate: bool) - -> Option<(usize, worker::State)> - { + pub fn pop( + &self, + entries: &[worker::Entry], + max_lifecycle: worker::Lifecycle, + terminate: bool, + ) -> Option<(usize, worker::State)> { // Figure out the empty value let terminal = match terminate { true => TERMINATED, @@ -145,8 +148,10 @@ impl Stack { return None; } - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual != state { state = actual; @@ -173,8 +178,10 @@ impl Stack { next.set_head(next_head); } - let actual = self.state.compare_and_swap( - state.into(), next.into(), AcqRel).into(); + let actual = self + .state + .compare_and_swap(state.into(), next.into(), AcqRel) + .into(); if actual == state { // Release ordering is needed to ensure that unsetting the diff --git a/tokio-threadpool/src/worker/state.rs b/tokio-threadpool/src/worker/state.rs index cb9893784..c388f6c99 100644 --- a/tokio-threadpool/src/worker/state.rs +++ b/tokio-threadpool/src/worker/state.rs @@ -108,11 +108,12 @@ impl From for Lifecycle { use self::Lifecycle::*; debug_assert!( - src == Shutdown as usize || - src == Running as usize || - src == Sleeping as usize || - src == Notified as usize || - src == Signaled as usize); + src == Shutdown as usize + || src == Running as usize + || src == Sleeping as usize + || src == Notified as usize + || src == Signaled as usize + ); unsafe { ::std::mem::transmute(src) } } @@ -128,18 +129,12 @@ impl From for usize { #[cfg(test)] mod test { - use super::*; use super::Lifecycle::*; + use super::*; #[test] fn lifecycle_encode() { - let lifecycles = &[ - Shutdown, - Running, - Sleeping, - Notified, - Signaled, - ]; + let lifecycles = &[Shutdown, Running, Sleeping, Notified, Signaled]; for &lifecycle in lifecycles { let mut v: usize = lifecycle.into(); diff --git a/tokio-threadpool/tests/blocking.rs b/tokio-threadpool/tests/blocking.rs index 47a8a9bc9..5fae2af27 100644 --- a/tokio-threadpool/tests/blocking.rs +++ b/tokio-threadpool/tests/blocking.rs @@ -6,24 +6,21 @@ extern crate rand; use tokio_threadpool::*; -use futures::*; use futures::future::{lazy, poll_fn}; +use futures::*; use rand::*; -use std::sync::*; -use std::sync::atomic::*; use std::sync::atomic::Ordering::*; -use std::time::Duration; +use std::sync::atomic::*; +use std::sync::*; use std::thread; +use std::time::Duration; #[test] fn basic() { let _ = ::env_logger::try_init(); - let pool = Builder::new() - .pool_size(1) - .max_blocking(1) - .build(); + let pool = Builder::new().pool_size(1).max_blocking(1).build(); let (tx1, rx1) = mpsc::channel(); let (tx2, rx2) = mpsc::channel(); @@ -32,7 +29,8 @@ fn basic() { let res = blocking(|| { let v = rx1.recv().unwrap(); tx2.send(v).unwrap(); - }).unwrap(); + }) + .unwrap(); assert!(res.is_ready()); Ok(().into()) @@ -50,10 +48,7 @@ fn basic() { fn notify_task_on_capacity() { const BLOCKING: usize = 10; - let pool = Builder::new() - .pool_size(1) - .max_blocking(1) - .build(); + let pool = Builder::new().pool_size(1).max_blocking(1).build(); let rem = Arc::new(AtomicUsize::new(BLOCKING)); let (tx, rx) = mpsc::channel(); @@ -71,7 +66,8 @@ fn notify_task_on_capacity() { if prev == 1 { tx.send(()).unwrap(); } - }).map_err(|e| panic!("blocking err {:?}", e)) + }) + .map_err(|e| panic!("blocking err {:?}", e)) }) })); } @@ -83,17 +79,14 @@ fn notify_task_on_capacity() { #[test] fn capacity_is_use_it_or_lose_it() { - use futures::*; - use futures::Async::*; use futures::sync::oneshot; use futures::task::Task; + use futures::Async::*; + use futures::*; // TODO: Run w/ bigger pool size - let pool = Builder::new() - .pool_size(1) - .max_blocking(1) - .build(); + let pool = Builder::new().pool_size(1).max_blocking(1).build(); let (tx1, rx1) = mpsc::channel(); let (tx2, rx2) = oneshot::channel(); @@ -105,24 +98,24 @@ fn capacity_is_use_it_or_lose_it() { poll_fn(move || { blocking(|| { rx1.recv().unwrap(); - }).map_err(|_| panic!()) + }) + .map_err(|_| panic!()) }) })); pool.spawn(lazy(move || { - rx2 - .map_err(|_| panic!()) - .and_then(|task: Task| { - poll_fn(move || { - blocking(|| { - // Notify the other task - task.notify(); + rx2.map_err(|_| panic!()).and_then(|task: Task| { + poll_fn(move || { + blocking(|| { + // Notify the other task + task.notify(); - // Block until woken - rx3.recv().unwrap(); - }).map_err(|_| panic!()) + // Block until woken + rx3.recv().unwrap(); }) + .map_err(|_| panic!()) }) + }) })); // Spawn a future that will try to block, get notified, then not actually @@ -136,8 +129,7 @@ fn capacity_is_use_it_or_lose_it() { 0 => { i = 1; - let res = blocking(|| unreachable!()) - .map_err(|_| panic!()); + let res = blocking(|| unreachable!()).map_err(|_| panic!()); assert!(res.unwrap().is_not_ready()); @@ -157,8 +149,7 @@ fn capacity_is_use_it_or_lose_it() { return Ok(NotReady); } 2 => { - let res = blocking(|| unreachable!()) - .map_err(|_| panic!()); + let res = blocking(|| unreachable!()).map_err(|_| panic!()); assert!(res.unwrap().is_not_ready()); @@ -177,10 +168,7 @@ fn capacity_is_use_it_or_lose_it() { #[test] fn blocking_thread_does_not_take_over_shutdown_worker_thread() { - let pool = Builder::new() - .pool_size(2) - .max_blocking(1) - .build(); + let pool = Builder::new().pool_size(2).max_blocking(1).build(); let (enter_tx, enter_rx) = mpsc::channel(); let (exit_tx, exit_rx) = mpsc::channel(); @@ -197,7 +185,8 @@ fn blocking_thread_does_not_take_over_shutdown_worker_thread() { enter_tx.send(()).unwrap(); exit_rx.recv().unwrap(); exited.store(true, Relaxed); - }).map_err(|_| panic!()) + }) + .map_err(|_| panic!()) }) })); } @@ -208,13 +197,9 @@ fn blocking_thread_does_not_take_over_shutdown_worker_thread() { // Spawn another task that attempts to block pool.spawn(lazy(move || { poll_fn(move || { - let res = blocking(|| { + let res = blocking(|| {}).unwrap(); - }).unwrap(); - - assert_eq!( - res.is_ready(), - exited.load(Relaxed)); + assert_eq!(res.is_ready(), exited.load(Relaxed)); try_tx.send(res.is_ready()).unwrap(); @@ -242,10 +227,7 @@ fn blocking_one_time_gets_capacity_for_multiple_blocks() { const BLOCKING: usize = 2; for _ in 0..ITER { - let pool = Builder::new() - .pool_size(4) - .max_blocking(1) - .build(); + let pool = Builder::new().pool_size(4).max_blocking(1).build(); let rem = Arc::new(AtomicUsize::new(BLOCKING)); let (tx, rx) = mpsc::channel(); @@ -259,7 +241,8 @@ fn blocking_one_time_gets_capacity_for_multiple_blocks() { // First block let res = blocking(|| { thread::sleep(Duration::from_millis(100)); - }).map_err(|e| panic!("blocking err {:?}", e)); + }) + .map_err(|e| panic!("blocking err {:?}", e)); try_ready!(res); @@ -302,8 +285,12 @@ fn shutdown() { Builder::new() .pool_size(1) .max_blocking(BLOCKING) - .after_start(move || { num_inc.fetch_add(1, Relaxed); }) - .before_stop(move || { num_dec.fetch_add(1, Relaxed); }) + .after_start(move || { + num_inc.fetch_add(1, Relaxed); + }) + .before_stop(move || { + num_dec.fetch_add(1, Relaxed); + }) .build() }; @@ -317,7 +304,8 @@ fn shutdown() { let res = blocking(|| { barrier.wait(); Ok::<_, ()>(()) - }).unwrap(); + }) + .unwrap(); tx.send(()).unwrap(); @@ -394,7 +382,8 @@ fn hammer() { } cnt_block.fetch_add(1, Relaxed); - }).map_err(|_| panic!()) + }) + .map_err(|_| panic!()) }) })); } diff --git a/tokio-threadpool/tests/hammer.rs b/tokio-threadpool/tests/hammer.rs index 7d1e5152a..d9ee41ca6 100644 --- a/tokio-threadpool/tests/hammer.rs +++ b/tokio-threadpool/tests/hammer.rs @@ -3,16 +3,16 @@ extern crate tokio_threadpool; use tokio_threadpool::*; -use futures::{Future, Stream, Sink, Poll}; +use futures::{Future, Poll, Sink, Stream}; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::*; +use std::sync::Arc; #[test] fn hammer() { use futures::future; - use futures::sync::{oneshot, mpsc}; + use futures::sync::{mpsc, oneshot}; const N: usize = 1000; const ITER: usize = 20; @@ -37,7 +37,7 @@ fn hammer() { } } - for _ in 0.. ITER { + for _ in 0..ITER { let pool = Builder::new() // .pool_size(30) .build(); @@ -61,14 +61,13 @@ fn hammer() { rx2 }) .map_err(|e| panic!("e={:?}", e)) - .and_then(|_| { - Ok(()) - }); + .and_then(|_| Ok(())); pool.spawn(Counted { inner: task, cnt: c1.clone(), - }).unwrap(); + }) + .unwrap(); Ok(()) }); @@ -85,17 +84,12 @@ fn hammer() { listen_tx.send(tx).unwrap(); pool.spawn({ - let task = rx - .map_err(|e| panic!("rx err={:?}", e)) - .and_then(|tx| { - tx.send(()).unwrap(); - Ok(()) - }); + let task = rx.map_err(|e| panic!("rx err={:?}", e)).and_then(|tx| { + tx.send(()).unwrap(); + Ok(()) + }); - Counted { - inner: task, - cnt, - } + Counted { inner: task, cnt } }); } diff --git a/tokio-threadpool/tests/threadpool.rs b/tokio-threadpool/tests/threadpool.rs index c9c3a76c1..dd482625d 100644 --- a/tokio-threadpool/tests/threadpool.rs +++ b/tokio-threadpool/tests/threadpool.rs @@ -1,19 +1,19 @@ -extern crate tokio_threadpool; -extern crate tokio_executor; -extern crate futures; extern crate env_logger; +extern crate futures; +extern crate tokio_executor; +extern crate tokio_threadpool; use tokio_executor::park::{Park, Unpark}; -use tokio_threadpool::*; use tokio_threadpool::park::{DefaultPark, DefaultUnpark}; +use tokio_threadpool::*; -use futures::{Poll, Sink, Stream, Async, Future}; use futures::future::lazy; +use futures::{Async, Future, Poll, Sink, Stream}; use std::cell::Cell; -use std::sync::{mpsc, Arc}; -use std::sync::atomic::*; use std::sync::atomic::Ordering::Relaxed; +use std::sync::atomic::*; +use std::sync::{mpsc, Arc}; use std::time::Duration; thread_local!(static FOO: Cell = Cell::new(0)); @@ -56,7 +56,8 @@ fn natural_shutdown_simple_futures() { t.send("one").unwrap(); Ok(()) - })).unwrap(); + })) + .unwrap(); rx }; @@ -68,7 +69,8 @@ fn natural_shutdown_simple_futures() { t.send("two").unwrap(); Ok(()) - })).unwrap(); + })) + .unwrap(); rx }; @@ -223,7 +225,8 @@ fn many_oneshot_futures() { tx.spawn(lazy(move || { cnt.fetch_add(1, Relaxed); Ok(()) - })).unwrap(); + })) + .unwrap(); } // Wait for the pool to shutdown @@ -257,15 +260,17 @@ fn many_multishot_futures() { for _ in 0..CHAIN { let (next_tx, next_rx) = mpsc::channel(10); - let rx = chain_rx - .map_err(|e| panic!("{:?}", e)); + let rx = chain_rx.map_err(|e| panic!("{:?}", e)); // Forward all the messages - pool_tx.spawn(next_tx - .send_all(rx) - .map(|_| ()) - .map_err(|e| panic!("{:?}", e)) - ).unwrap(); + pool_tx + .spawn( + next_tx + .send_all(rx) + .map(|_| ()) + .map_err(|e| panic!("{:?}", e)), + ) + .unwrap(); chain_rx = next_rx; } @@ -321,7 +326,8 @@ fn global_executor_is_configured() { })); Ok(()) - })).unwrap(); + })) + .unwrap(); signal_rx.recv().unwrap(); @@ -339,17 +345,12 @@ fn busy_threadpool_is_not_idle() { use futures::sync::oneshot; // let pool = ThreadPool::new(); - let pool = Builder::new() - .pool_size(4) - .max_blocking(2) - .build(); + let pool = Builder::new().pool_size(4).max_blocking(2).build(); let tx = pool.sender().clone(); let (term_tx, term_rx) = oneshot::channel(); - tx.spawn(term_rx.then(|_| { - Ok(()) - })).unwrap(); + tx.spawn(term_rx.then(|_| Ok(()))).unwrap(); let mut idle = pool.shutdown_on_idle(); @@ -426,7 +427,7 @@ fn multi_threadpool() { #[test] fn eagerly_drops_futures() { - use futures::future::{Future, lazy, empty}; + use futures::future::{empty, lazy, Future}; use futures::task; use std::sync::mpsc; @@ -486,12 +487,10 @@ fn eagerly_drops_futures() { let notify_on_drop = NotifyOnDrop(drop_tx); let pool = tokio_threadpool::Builder::new() - .custom_park(move |_| { - MyPark { - inner: DefaultPark::new(), - park_tx: park_tx.clone(), - unpark_tx: unpark_tx.clone(), - } + .custom_park(move |_| MyPark { + inner: DefaultPark::new(), + park_tx: park_tx.clone(), + unpark_tx: unpark_tx.clone(), }) .build(); @@ -506,7 +505,9 @@ fn eagerly_drops_futures() { // `notify_on_drop` handle. empty::<(), ()>().then(move |_| { // This code path should never be reached. - if true { panic!() } + if true { + panic!() + } // Explicitly drop `notify_on_drop` here, this is mostly to ensure // that the `notify_on_drop` handle gets moved into the task. It diff --git a/tokio-timer/src/atomic.rs b/tokio-timer/src/atomic.rs index 0f74c31d9..d60bd7645 100644 --- a/tokio-timer/src/atomic.rs +++ b/tokio-timer/src/atomic.rs @@ -35,16 +35,16 @@ mod imp { } pub fn compare_and_swap(&self, old: u64, new: u64, ordering: Ordering) -> u64 { - self.inner.compare_and_swap( - old as usize, new as usize, ordering) as u64 + self.inner + .compare_and_swap(old as usize, new as usize, ordering) as u64 } } } #[cfg(not(target_pointer_width = "64"))] mod imp { - use std::sync::Mutex; use std::sync::atomic::Ordering; + use std::sync::Mutex; #[derive(Debug)] pub struct AtomicU64 { diff --git a/tokio-timer/src/clock/clock.rs b/tokio-timer/src/clock/clock.rs index 1e3b5bfe1..9b9de89ef 100644 --- a/tokio-timer/src/clock/clock.rs +++ b/tokio-timer/src/clock/clock.rs @@ -12,7 +12,7 @@ use std::time::Instant; /// /// `Clock` instances return [`Instant`] values corresponding to "now". The source /// of these values is configurable. The default source is [`Instant::now`]. -/// +/// /// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html /// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now #[derive(Default, Clone)] @@ -20,7 +20,7 @@ pub struct Clock { now: Option>, } -thread_local!{ +thread_local! { /// Thread-local tracking the current clock static CLOCK: Cell> = Cell::new(None) } @@ -43,13 +43,9 @@ thread_local!{ /// let now = clock::now(); /// ``` pub fn now() -> Instant { - CLOCK.with(|current| { - match current.get() { - Some(ptr) => { - unsafe { (*ptr).now() } - } - None => Instant::now(), - } + CLOCK.with(|current| match current.get() { + Some(ptr) => unsafe { (*ptr).now() }, + None => Instant::now(), }) } @@ -57,13 +53,9 @@ impl Clock { /// Return a new `Clock` instance that uses the current execution context's /// source of time. pub fn new() -> Clock { - CLOCK.with(|current| { - match current.get() { - Some(ptr) => { - unsafe { (*ptr).clone() } - } - None => Clock::system(), - } + CLOCK.with(|current| match current.get() { + Some(ptr) => unsafe { (*ptr).clone() }, + None => Clock::system(), }) } @@ -76,12 +68,10 @@ impl Clock { /// Return a new `Clock` instance that uses [`Instant::now`] as the source /// of time. - /// + /// /// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now pub fn system() -> Clock { - Clock { - now: None, - } + Clock { now: None } } /// Returns an instant corresponding to "now" by using the instance's source @@ -121,10 +111,14 @@ impl fmt::Debug for Clock { /// /// This function panics if there already is a default clock set. pub fn with_default(clock: &Clock, enter: &mut Enter, f: F) -> R -where F: FnOnce(&mut Enter) -> R +where + F: FnOnce(&mut Enter) -> R, { CLOCK.with(|cell| { - assert!(cell.get().is_none(), "default clock already set for execution context"); + assert!( + cell.get().is_none(), + "default clock already set for execution context" + ); // Ensure that the clock is removed from the thread-local context // when leaving the scope. This handles cases that involve panicking. diff --git a/tokio-timer/src/clock/mod.rs b/tokio-timer/src/clock/mod.rs index 02b650bb3..1791bc758 100644 --- a/tokio-timer/src/clock/mod.rs +++ b/tokio-timer/src/clock/mod.rs @@ -19,5 +19,5 @@ mod clock; mod now; -pub use self::clock::{Clock, now, with_default}; +pub use self::clock::{now, with_default, Clock}; pub use self::now::Now; diff --git a/tokio-timer/src/clock/now.rs b/tokio-timer/src/clock/now.rs index 871fecfa1..18450c830 100644 --- a/tokio-timer/src/clock/now.rs +++ b/tokio-timer/src/clock/now.rs @@ -7,7 +7,7 @@ use std::time::Instant; /// /// Implementations must ensure that calls to `now` return monotonically /// increasing [`Instant`] values. -/// +/// /// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html pub trait Now: Send + Sync + 'static { /// Returns an instant corresponding to "now". diff --git a/tokio-timer/src/deadline.rs b/tokio-timer/src/deadline.rs index 4061533e6..c4c19b8bb 100644 --- a/tokio-timer/src/deadline.rs +++ b/tokio-timer/src/deadline.rs @@ -2,7 +2,7 @@ use Delay; -use futures::{Future, Poll, Async}; +use futures::{Async, Future, Poll}; use std::error; use std::fmt; @@ -42,10 +42,7 @@ impl Deadline { } pub(crate) fn new_with_delay(future: T, delay: Delay) -> Deadline { - Deadline { - future, - delay, - } + Deadline { future, delay } } /// Gets a reference to the underlying future in this deadline. @@ -65,7 +62,8 @@ impl Deadline { } impl Future for Deadline -where T: Future, +where + T: Future, { type Item = T::Item; type Error = DeadlineError; @@ -81,9 +79,7 @@ where T: Future, // Now check the timer match self.delay.poll() { Ok(Async::NotReady) => Ok(Async::NotReady), - Ok(Async::Ready(_)) => { - Err(DeadlineError::elapsed()) - }, + Ok(Async::Ready(_)) => Err(DeadlineError::elapsed()), Err(e) => Err(DeadlineError::timer(e)), } } diff --git a/tokio-timer/src/delay.rs b/tokio-timer/src/delay.rs index 65ba0facc..c48adccd5 100644 --- a/tokio-timer/src/delay.rs +++ b/tokio-timer/src/delay.rs @@ -1,9 +1,9 @@ +use timer::{HandlePriv, Registration}; use Error; -use timer::{Registration, HandlePriv}; use futures::{Future, Poll}; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; /// A future that completes at a specified instant in time. /// diff --git a/tokio-timer/src/delay_queue.rs b/tokio-timer/src/delay_queue.rs index 39bfb268a..1f4b0a17a 100644 --- a/tokio-timer/src/delay_queue.rs +++ b/tokio-timer/src/delay_queue.rs @@ -4,12 +4,12 @@ //! //! [`DelayQueue`]: struct.DelayQueue.html -use {Error, Delay}; use clock::now; -use wheel::{self, Wheel}; use timer::Handle; +use wheel::{self, Wheel}; +use {Delay, Error}; -use futures::{Future, Stream, Poll}; +use futures::{Future, Poll, Stream}; use slab::Slab; use std::cmp; @@ -339,10 +339,12 @@ impl DelayQueue { self.insert_idx(when, key); // Set a new delay if the current's deadline is later than the one of the new item - let should_set_delay = if let Some(ref delay) = self.delay { + let should_set_delay = if let Some(ref delay) = self.delay { let current_exp = self.normalize_deadline(delay.deadline()); current_exp > when - } else { true }; + } else { + true + }; if should_set_delay { self.delay = Some(self.handle.delay(self.start + Duration::from_millis(when))); @@ -414,9 +416,7 @@ impl DelayQueue { // The delay is already expired, store it in the expired queue self.expired.push(key, &mut self.slab); } - Err((_, err)) => { - panic!("invalid deadline; err={:?}", err) - } + Err((_, err)) => panic!("invalid deadline; err={:?}", err), } } @@ -510,15 +510,17 @@ impl DelayQueue { self.slab[key.index].when = when; self.insert_idx(when, key.index); - let next_deadline = self.next_deadline(); + let next_deadline = self.next_deadline(); if let (Some(ref mut delay), Some(deadline)) = (&mut self.delay, next_deadline) { - delay.reset(deadline); + delay.reset(deadline); } } /// Returns the next time poll as determined by the wheel fn next_deadline(&mut self) -> Option { - self.wheel.poll_at().map(|poll_at| self.start + Duration::from_millis(poll_at)) + self.wheel + .poll_at() + .map(|poll_at| self.start + Duration::from_millis(poll_at)) } /// Sets the delay of the item associated with `key` to expire after @@ -691,9 +693,8 @@ impl DelayQueue { if let Some(deadline) = self.next_deadline() { self.delay = Some(self.handle.delay(deadline)); } else { - return Ok(None.into()) + return Ok(None.into()); } - } } @@ -713,18 +714,17 @@ impl Stream for DelayQueue { type Error = Error; fn poll(&mut self) -> Poll, Error> { - let item = try_ready!(self.poll_idx()) - .map(|idx| { - let data = self.slab.remove(idx); - debug_assert!(data.next.is_none()); - debug_assert!(data.prev.is_none()); + let item = try_ready!(self.poll_idx()).map(|idx| { + let data = self.slab.remove(idx); + debug_assert!(data.next.is_none()); + debug_assert!(data.prev.is_none()); - Expired { - key: Key::new(idx), - data: data.inner, - deadline: self.start + Duration::from_millis(data.when), - } - }); + Expired { + key: Key::new(idx), + data: data.inner, + deadline: self.start + Duration::from_millis(data.when), + } + }); Ok(item.into()) } diff --git a/tokio-timer/src/interval.rs b/tokio-timer/src/interval.rs index 80d09600e..019efe6a2 100644 --- a/tokio-timer/src/interval.rs +++ b/tokio-timer/src/interval.rs @@ -2,9 +2,9 @@ use Delay; use clock; -use futures::{Future, Stream, Poll}; +use futures::{Future, Poll, Stream}; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; /// A stream representing notifications at fixed interval #[derive(Debug)] @@ -28,7 +28,10 @@ impl Interval { /// /// This function panics if `duration` is zero. pub fn new(at: Instant, duration: Duration) -> Interval { - assert!(duration > Duration::new(0, 0), "`duration` must be non-zero."); + assert!( + duration > Duration::new(0, 0), + "`duration` must be non-zero." + ); Interval::new_with_delay(Delay::new(at), duration) } @@ -47,10 +50,7 @@ impl Interval { } pub(crate) fn new_with_delay(delay: Delay, duration: Duration) -> Interval { - Interval { - delay, - duration, - } + Interval { delay, duration } } } diff --git a/tokio-timer/src/lib.rs b/tokio-timer/src/lib.rs index 90037b472..b10692079 100644 --- a/tokio-timer/src/lib.rs +++ b/tokio-timer/src/lib.rs @@ -53,9 +53,9 @@ mod wheel; #[doc(hidden)] #[allow(deprecated)] pub use self::deadline::{Deadline, DeadlineError}; +pub use self::delay::Delay; #[doc(inline)] pub use self::delay_queue::DelayQueue; -pub use self::delay::Delay; pub use self::error::Error; pub use self::interval::Interval; #[doc(inline)] @@ -92,5 +92,8 @@ fn ms(duration: Duration, round: Round) -> u64 { Round::Down => duration.subsec_nanos() / NANOS_PER_MILLI, }; - duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64) + duration + .as_secs() + .saturating_mul(MILLIS_PER_SEC) + .saturating_add(millis as u64) } diff --git a/tokio-timer/src/throttle.rs b/tokio-timer/src/throttle.rs index 12e889576..0ab49aaa5 100644 --- a/tokio-timer/src/throttle.rs +++ b/tokio-timer/src/throttle.rs @@ -2,8 +2,8 @@ use {clock, Delay, Error}; -use futures::{Async, Future, Poll, Stream}; use futures::future::Either; +use futures::{Async, Future, Poll, Stream}; use std::{ error::Error as StdError, @@ -65,17 +65,11 @@ impl Stream for Throttle { fn poll(&mut self) -> Poll, Self::Error> { if let Some(ref mut delay) = self.delay { - try_ready!({ - delay.poll() - .map_err(ThrottleError::from_timer_err) - }); + try_ready!({ delay.poll().map_err(ThrottleError::from_timer_err) }); } self.delay = None; - let value = try_ready!({ - self.stream.poll() - .map_err(ThrottleError::from_stream_err) - }); + let value = try_ready!({ self.stream.poll().map_err(ThrottleError::from_stream_err) }); if value.is_some() { self.delay = Some(Delay::new(clock::now() + self.duration)); diff --git a/tokio-timer/src/timeout.rs b/tokio-timer/src/timeout.rs index 783f87853..8ed1b528b 100644 --- a/tokio-timer/src/timeout.rs +++ b/tokio-timer/src/timeout.rs @@ -4,14 +4,14 @@ //! //! [`Timeout`]: struct.Timeout.html -use Delay; use clock::now; +use Delay; -use futures::{Future, Stream, Poll, Async}; +use futures::{Async, Future, Poll, Stream}; use std::error; use std::fmt; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; /// Allows a `Future` or `Stream` to execute for a limited amount of time. /// @@ -127,10 +127,7 @@ impl Timeout { pub fn new(value: T, timeout: Duration) -> Timeout { let delay = Delay::new_timeout(now() + timeout, timeout); - Timeout { - value, - delay, - } + Timeout { value, delay } } /// Gets a reference to the underlying value in this timeout. @@ -168,7 +165,8 @@ impl Timeout { } impl Future for Timeout -where T: Future, +where + T: Future, { type Item = T::Item; type Error = Error; @@ -184,16 +182,15 @@ where T: Future, // Now check the timer match self.delay.poll() { Ok(Async::NotReady) => Ok(Async::NotReady), - Ok(Async::Ready(_)) => { - Err(Error::elapsed()) - }, + Ok(Async::Ready(_)) => Err(Error::elapsed()), Err(e) => Err(Error::timer(e)), } } } impl Stream for Timeout -where T: Stream, +where + T: Stream, { type Item = T::Item; type Error = Error; @@ -205,7 +202,7 @@ where T: Stream, if v.is_some() { self.delay.reset_timeout(); } - return Ok(Async::Ready(v)) + return Ok(Async::Ready(v)); } Ok(Async::NotReady) => {} Err(e) => return Err(Error::inner(e)), @@ -217,7 +214,7 @@ where T: Stream, Ok(Async::Ready(_)) => { self.delay.reset_timeout(); Err(Error::elapsed()) - }, + } Err(e) => Err(Error::timer(e)), } } diff --git a/tokio-timer/src/timer/atomic_stack.rs b/tokio-timer/src/timer/atomic_stack.rs index 81d817a90..4e7d8ed6e 100644 --- a/tokio-timer/src/timer/atomic_stack.rs +++ b/tokio-timer/src/timer/atomic_stack.rs @@ -1,10 +1,10 @@ -use Error; use super::Entry; +use Error; use std::ptr; -use std::sync::Arc; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; /// A stack of `Entry` nodes #[derive(Debug)] @@ -24,7 +24,9 @@ const SHUTDOWN: *mut Entry = 1 as *mut _; impl AtomicStack { pub fn new() -> AtomicStack { - AtomicStack { head: AtomicPtr::new(ptr::null_mut()) } + AtomicStack { + head: AtomicPtr::new(ptr::null_mut()), + } } /// Push an entry onto the stack. diff --git a/tokio-timer/src/timer/entry.rs b/tokio-timer/src/timer/entry.rs index e1a866a9f..40979afae 100644 --- a/tokio-timer/src/timer/entry.rs +++ b/tokio-timer/src/timer/entry.rs @@ -1,17 +1,17 @@ -use Error; use atomic::AtomicU64; use timer::{HandlePriv, Inner}; +use Error; use crossbeam_utils::CachePadded; -use futures::Poll; use futures::task::AtomicTask; +use futures::Poll; use std::cell::UnsafeCell; use std::ptr; -use std::sync::{Arc, Weak}; use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering::{SeqCst, Relaxed}; -use std::time::{Instant, Duration}; +use std::sync::atomic::Ordering::{Relaxed, SeqCst}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; use std::u64; /// Internal state shared between a `Delay` instance and the timer. @@ -109,10 +109,7 @@ const ERROR: u64 = u64::MAX; impl Entry { pub fn new(deadline: Instant, duration: Duration) -> Entry { Entry { - time: CachePadded::new(UnsafeCell::new(Time { - deadline, - duration, - })), + time: CachePadded::new(UnsafeCell::new(Time { deadline, duration })), inner: None, task: AtomicTask::new(), state: AtomicU64::new(0), @@ -147,8 +144,7 @@ impl Entry { Err(_) => { // Could not associate the entry with a timer, transition the // state to error - Arc::get_mut(me).unwrap() - .transition_to_error(); + Arc::get_mut(me).unwrap().transition_to_error(); return; } @@ -168,8 +164,7 @@ impl Entry { None => { // Could not associate the entry with a timer, transition the // state to error - Arc::get_mut(me).unwrap() - .transition_to_error(); + Arc::get_mut(me).unwrap().transition_to_error(); return; } @@ -177,15 +172,13 @@ impl Entry { // Increment the number of active timeouts if inner.increment().is_err() { - Arc::get_mut(me).unwrap() - .transition_to_error(); + Arc::get_mut(me).unwrap().transition_to_error(); return; } // Associate the entry with the timer - Arc::get_mut(me).unwrap() - .inner = Some(handle.into_inner()); + Arc::get_mut(me).unwrap().inner = Some(handle.into_inner()); let when = inner.normalize_deadline(deadline); @@ -216,7 +209,9 @@ impl Entry { } pub fn set_when_internal(&self, when: Option) { - unsafe { (*self.when.get()) = when; } + unsafe { + (*self.when.get()) = when; + } } /// Called by `Timer` to load the current value of `state` for processing @@ -361,8 +356,7 @@ impl Entry { notify = true; } - let actual = entry.state.compare_and_swap( - curr, next, SeqCst); + let actual = entry.state.compare_and_swap(curr, next, SeqCst); if curr == actual { break; @@ -377,8 +371,7 @@ impl Entry { } fn upgrade_inner(&self) -> Option> { - self.inner.as_ref() - .and_then(|inner| inner.upgrade()) + self.inner.as_ref().and_then(|inner| inner.upgrade()) } } diff --git a/tokio-timer/src/timer/handle.rs b/tokio-timer/src/timer/handle.rs index 641437293..ed8f05fd5 100644 --- a/tokio-timer/src/timer/handle.rs +++ b/tokio-timer/src/timer/handle.rs @@ -1,5 +1,5 @@ -use {Error, Delay, Deadline, Interval}; use timer::Inner; +use {Deadline, Delay, Error, Interval}; use tokio_executor::Enter; @@ -44,7 +44,7 @@ pub(crate) struct HandlePriv { inner: Weak, } -thread_local!{ +thread_local! { /// Tracks the timer for the current execution context. static CURRENT_TIMER: RefCell> = RefCell::new(None) } @@ -61,7 +61,8 @@ thread_local!{ /// [`Delay`]: ../struct.Delay.html /// [`Delay::new`]: ../struct.Delay.html#method.new pub fn with_default(handle: &Handle, enter: &mut Enter, f: F) -> R -where F: FnOnce(&mut Enter) -> R +where + F: FnOnce(&mut Enter) -> R, { // Ensure that the timer is removed from the thread-local context // when leaving the scope. This handles cases that involve panicking. @@ -84,10 +85,14 @@ where F: FnOnce(&mut Enter) -> R { let mut current = current.borrow_mut(); - assert!(current.is_none(), "default Tokio timer already set \ - for execution context"); + assert!( + current.is_none(), + "default Tokio timer already set \ + for execution context" + ); - let handle = handle.as_priv() + let handle = handle + .as_priv() .unwrap_or_else(|| panic!("`handle` does not reference a timer")); *current = Some(handle.clone()); @@ -118,23 +123,19 @@ impl Handle { /// [`with_default`]: ../fn.with_default.html /// [type]: # pub fn current() -> Handle { - let private = HandlePriv::try_current() - .unwrap_or_else(|_| { - HandlePriv { inner: Weak::new() } - }); + let private = + HandlePriv::try_current().unwrap_or_else(|_| HandlePriv { inner: Weak::new() }); - Handle { inner: Some(private) } + Handle { + inner: Some(private), + } } /// Create a `Delay` driven by this handle's associated `Timer`. pub fn delay(&self, deadline: Instant) -> Delay { match self.inner { - Some(ref handle_priv) => { - Delay::new_with_handle(deadline, handle_priv.clone()) - } - None => { - Delay::new(deadline) - } + Some(ref handle_priv) => Delay::new_with_handle(deadline, handle_priv.clone()), + None => Delay::new(deadline), } } @@ -165,11 +166,9 @@ impl HandlePriv { /// /// Returns `Err` if no handle is found. pub(crate) fn try_current() -> Result { - CURRENT_TIMER.with(|current| { - match *current.borrow() { - Some(ref handle) => Ok(handle.clone()), - None => Err(Error::shutdown()), - } + CURRENT_TIMER.with(|current| match *current.borrow() { + Some(ref handle) => Ok(handle.clone()), + None => Err(Error::shutdown()), }) } diff --git a/tokio-timer/src/timer/mod.rs b/tokio-timer/src/timer/mod.rs index 1a8ae8125..05b0672e6 100644 --- a/tokio-timer/src/timer/mod.rs +++ b/tokio-timer/src/timer/mod.rs @@ -44,23 +44,23 @@ use self::atomic_stack::AtomicStack; use self::entry::Entry; use self::stack::Stack; -pub use self::handle::{Handle, with_default}; pub(crate) use self::handle::HandlePriv; +pub use self::handle::{with_default, Handle}; pub use self::now::{Now, SystemNow}; pub(crate) use self::registration::Registration; -use Error; use atomic::AtomicU64; use wheel; +use Error; -use tokio_executor::park::{Park, Unpark, ParkThread}; +use tokio_executor::park::{Park, ParkThread, Unpark}; -use std::{cmp, fmt}; -use std::time::{Duration, Instant}; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::sync::Arc; +use std::time::{Duration, Instant}; use std::usize; +use std::{cmp, fmt}; /// Timer implementation that drives [`Delay`], [`Interval`], and [`Timeout`]. /// @@ -171,7 +171,8 @@ const MAX_TIMEOUTS: usize = usize::MAX >> 1; // ===== impl Timer ===== impl Timer -where T: Park +where + T: Park, { /// Create a new `Timer` instance that uses `park` to block the current /// thread. @@ -201,8 +202,9 @@ impl Timer { } impl Timer -where T: Park, - N: Now, +where + T: Park, + N: Now, { /// Create a new `Timer` instance that uses `park` to block the current /// thread and `now` to get the current `Instant`. @@ -268,8 +270,7 @@ where T: Park, let mut poll = wheel::Poll::new(now); while let Some(entry) = self.wheel.poll(&mut poll, &mut ()) { - let when = entry.when_internal() - .expect("invalid internal entry state"); + let when = entry.when_internal().expect("invalid internal entry state"); // Fire the entry entry.fire(when); @@ -345,8 +346,9 @@ impl Default for Timer { } impl Park for Timer -where T: Park, - N: Now, +where + T: Park, + N: Now, { type Unpark = T::Unpark; type Error = T::Error; @@ -483,7 +485,6 @@ impl Inner { impl fmt::Debug for Inner { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("Inner") - .finish() + fmt.debug_struct("Inner").finish() } } diff --git a/tokio-timer/src/timer/now.rs b/tokio-timer/src/timer/now.rs index bc8ca7808..9f23bad71 100644 --- a/tokio-timer/src/timer/now.rs +++ b/tokio-timer/src/timer/now.rs @@ -7,4 +7,4 @@ pub trait Now { fn now(&mut self) -> Instant; } -pub use ::clock::Clock as SystemNow; +pub use clock::Clock as SystemNow; diff --git a/tokio-timer/src/timer/registration.rs b/tokio-timer/src/timer/registration.rs index 81cc3e511..dad1355dc 100644 --- a/tokio-timer/src/timer/registration.rs +++ b/tokio-timer/src/timer/registration.rs @@ -1,11 +1,11 @@ -use Error; use clock::now; -use timer::{HandlePriv, Entry}; +use timer::{Entry, HandlePriv}; +use Error; use futures::Poll; use std::sync::Arc; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; /// Registration with a timer. /// @@ -21,7 +21,9 @@ impl Registration { fn is_send() {} is_send::(); - Registration { entry: Arc::new(Entry::new(deadline, duration)) } + Registration { + entry: Arc::new(Entry::new(deadline, duration)), + } } pub fn deadline(&self) -> Instant { diff --git a/tokio-timer/src/timer/stack.rs b/tokio-timer/src/timer/stack.rs index 9b438fa47..c63eed971 100644 --- a/tokio-timer/src/timer/stack.rs +++ b/tokio-timer/src/timer/stack.rs @@ -49,7 +49,6 @@ impl wheel::Stack for Stack { // Set this entry's next pointer *entry.next_stack.get() = old; - } // Update the head pointer @@ -117,7 +116,6 @@ impl wheel::Stack for Stack { } fn when(item: &Entry, _: &()) -> u64 { - item.when_internal() - .expect("invalid internal state") + item.when_internal().expect("invalid internal state") } } diff --git a/tokio-timer/src/wheel/level.rs b/tokio-timer/src/wheel/level.rs index 4f9aec2da..6bbd128e0 100644 --- a/tokio-timer/src/wheel/level.rs +++ b/tokio-timer/src/wheel/level.rs @@ -43,7 +43,9 @@ impl Level { // contained by the array be `Copy`. So, here we have to manually // initialize every single slot. macro_rules! s { - () => { T::default() }; + () => { + T::default() + }; }; Level { @@ -52,14 +54,70 @@ impl Level { slot: [ // It does not look like the necessary traits are // derived for [T; 64]. - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), - s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), + s!(), ], } } @@ -84,8 +142,15 @@ impl Level { let level_start = now - (now % level_range); let deadline = level_start + slot as u64 * slot_range; - debug_assert!(deadline >= now, "deadline={}; now={}; level={}; slot={}; occupied={:b}", - deadline, now, self.level, slot, self.occupied); + debug_assert!( + deadline >= now, + "deadline={}; now={}; level={}; slot={}; occupied={:b}", + deadline, + now, + self.level, + slot, + self.occupied + ); Some(Expiration { level: self.level, diff --git a/tokio-timer/src/wheel/mod.rs b/tokio-timer/src/wheel/mod.rs index abd79b436..81f92cd88 100644 --- a/tokio-timer/src/wheel/mod.rs +++ b/tokio-timer/src/wheel/mod.rs @@ -1,9 +1,9 @@ mod level; mod stack; -pub(crate) use self::stack::Stack; pub(crate) use self::level::Expiration; use self::level::Level; +pub(crate) use self::stack::Stack; use std::borrow::Borrow; use std::usize; @@ -64,14 +64,9 @@ where { /// Create a new timing wheel pub fn new() -> Wheel { - let levels = (0..NUM_LEVELS) - .map(Level::new) - .collect(); + let levels = (0..NUM_LEVELS).map(Level::new).collect(); - Wheel { - elapsed: 0, - levels, - } + Wheel { elapsed: 0, levels } } /// Return the number of milliseconds that have elapsed since the timing @@ -101,9 +96,12 @@ where /// immediately. /// /// `Err(Invalid)` indicates an invalid `when` argument as been supplied. - pub fn insert(&mut self, when: u64, item: T::Owned, store: &mut T::Store) - -> Result<(), (T::Owned, InsertError)> - { + pub fn insert( + &mut self, + when: u64, + item: T::Owned, + store: &mut T::Store, + ) -> Result<(), (T::Owned, InsertError)> { if when <= self.elapsed { return Err((item, InsertError::Elapsed)); } else if when - self.elapsed > MAX_DURATION { @@ -116,7 +114,8 @@ where self.levels[level].add_entry(when, item, store); debug_assert!({ - self.levels[level].next_expiration(self.elapsed) + self.levels[level] + .next_expiration(self.elapsed) .map(|e| e.deadline >= self.elapsed) .unwrap_or(true) }); @@ -134,23 +133,19 @@ where /// Instant at which to poll pub fn poll_at(&self) -> Option { - self.next_expiration() - .map(|expiration| expiration.deadline) + self.next_expiration().map(|expiration| expiration.deadline) } - pub fn poll(&mut self, poll: &mut Poll, store: &mut T::Store) - -> Option - { + pub fn poll(&mut self, poll: &mut Poll, store: &mut T::Store) -> Option { loop { if poll.expiration.is_none() { - poll.expiration = self.next_expiration() - .and_then(|expiration| { - if expiration.deadline > poll.now { - None - } else { - Some(expiration) - } - }); + poll.expiration = self.next_expiration().and_then(|expiration| { + if expiration.deadline > poll.now { + None + } else { + Some(expiration) + } + }); } match poll.expiration { @@ -181,7 +176,7 @@ where debug_assert!({ let mut res = true; - for l2 in (level+1)..NUM_LEVELS { + for l2 in (level + 1)..NUM_LEVELS { if let Some(e2) = self.levels[l2].next_expiration(self.elapsed) { if e2.deadline < expiration.deadline { res = false; @@ -199,9 +194,11 @@ where None } - pub fn poll_expiration(&mut self, expiration: &Expiration, store: &mut T::Store) - -> Option - { + pub fn poll_expiration( + &mut self, + expiration: &Expiration, + store: &mut T::Store, + ) -> Option { while let Some(item) = self.pop_entry(expiration, store) { if expiration.level == 0 { debug_assert_eq!(T::when(item.borrow(), store), expiration.deadline); @@ -212,8 +209,7 @@ where let next_level = expiration.level - 1; - self.levels[next_level] - .add_entry(when, item, store); + self.levels[next_level].add_entry(when, item, store); } } @@ -221,7 +217,12 @@ where } fn set_elapsed(&mut self, when: u64) { - assert!(self.elapsed <= when, "elapsed={:?}; when={:?}", self.elapsed, when); + assert!( + self.elapsed <= when, + "elapsed={:?}; when={:?}", + self.elapsed, + when + ); if when > self.elapsed { self.elapsed = when; @@ -263,25 +264,46 @@ mod test { #[test] fn test_level_for() { for pos in 1..64 { - assert_eq!(0, level_for(0, pos), "level_for({}) -- binary = {:b}", pos, pos); + assert_eq!( + 0, + level_for(0, pos), + "level_for({}) -- binary = {:b}", + pos, + pos + ); } for level in 1..5 { for pos in level..64 { let a = pos * 64_usize.pow(level as u32); - assert_eq!(level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", a, a); + assert_eq!( + level, + level_for(0, a as u64), + "level_for({}) -- binary = {:b}", + a, + a + ); if pos > level { let a = a - 1; - assert_eq!(level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", a, a); + assert_eq!( + level, + level_for(0, a as u64), + "level_for({}) -- binary = {:b}", + a, + a + ); } if pos < 64 { let a = a + 1; - assert_eq!(level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", a, a); + assert_eq!( + level, + level_for(0, a as u64), + "level_for({}) -- binary = {:b}", + a, + a + ); } } } diff --git a/tokio-timer/tests/deadline.rs b/tokio-timer/tests/deadline.rs index 04cdc013e..8eec79ae7 100644 --- a/tokio-timer/tests/deadline.rs +++ b/tokio-timer/tests/deadline.rs @@ -9,8 +9,8 @@ use support::*; use tokio_timer::*; -use futures::{future, Future}; use futures::sync::oneshot; +use futures::{future, Future}; #[test] fn simultaneous_deadline_future_completion() { diff --git a/tokio-timer/tests/delay.rs b/tokio-timer/tests/delay.rs index a82ec8b49..d21106c63 100644 --- a/tokio-timer/tests/delay.rs +++ b/tokio-timer/tests/delay.rs @@ -6,8 +6,8 @@ extern crate tokio_timer; mod support; use support::*; -use tokio_timer::*; use tokio_timer::timer::Handle; +use tokio_timer::*; use futures::Future; @@ -52,9 +52,7 @@ fn delayed_delay_level_0() { fn sub_ms_delayed_delay() { mocked(|timer, time| { for _ in 0..5 { - let deadline = time.now() - + Duration::from_millis(1) - + Duration::new(0, 1); + let deadline = time.now() + Duration::from_millis(1) + Duration::new(0, 1); let mut delay = Delay::new(deadline); @@ -282,11 +280,7 @@ fn sorta_long_delay() { // The delay has not elapsed. assert_not_ready!(delay); - let cascades = &[ - 262_144, - 262_144 + 9 * 4096, - 262_144 + 9 * 4096 + 15 * 64, - ]; + let cascades = &[262_144, 262_144 + 9 * 4096, 262_144 + 9 * 4096 + 15 * 64]; for &elapsed in cascades { turn(timer, None); diff --git a/tokio-timer/tests/hammer.rs b/tokio-timer/tests/hammer.rs index 42b0d2982..754cac4d1 100644 --- a/tokio-timer/tests/hammer.rs +++ b/tokio-timer/tests/hammer.rs @@ -6,14 +6,14 @@ extern crate tokio_timer; use tokio_executor::park::{Park, Unpark, UnparkThread}; use tokio_timer::*; -use futures::{Future, Stream}; use futures::stream::FuturesUnordered; +use futures::{Future, Stream}; use rand::Rng; use std::cmp; -use std::sync::{Arc, Barrier}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::sync::{Arc, Barrier}; use std::thread; use std::time::{Duration, Instant}; @@ -52,23 +52,20 @@ fn hammer_complete() { barrier.wait(); for _ in 0..PER_THREAD { - let deadline = Instant::now() + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline = + Instant::now() + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); exec.push({ - handle.delay(deadline) - .and_then(move |_| { - let now = Instant::now(); - assert!(now >= deadline, "deadline greater by {:?}", deadline - now); - Ok(()) - }) + handle.delay(deadline).and_then(move |_| { + let now = Instant::now(); + assert!(now >= deadline, "deadline greater by {:?}", deadline - now); + Ok(()) + }) }); } // Run the logic - exec.for_each(|_| Ok(())) - .wait() - .unwrap(); + exec.for_each(|_| Ok(())).wait().unwrap(); if 1 == done.rem.fetch_sub(1, SeqCst) { done.unpark.unpark(); @@ -112,11 +109,11 @@ fn hammer_cancel() { barrier.wait(); for _ in 0..PER_THREAD { - let deadline1 = Instant::now() + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline1 = + Instant::now() + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); - let deadline2 = Instant::now() + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline2 = + Instant::now() + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); let deadline = cmp::min(deadline1, deadline2); @@ -124,24 +121,22 @@ fn hammer_cancel() { let join = handle.deadline(delay, deadline2); exec.push({ - join - .and_then(move |_| { - let now = Instant::now(); - assert!(now >= deadline, "deadline greater by {:?}", deadline - now); - Ok(()) - }) + join.and_then(move |_| { + let now = Instant::now(); + assert!(now >= deadline, "deadline greater by {:?}", deadline - now); + Ok(()) + }) }); } // Run the logic - exec - .or_else(|e| { - assert!(e.is_elapsed()); - Ok::<_, ()>(()) - }) - .for_each(|_| Ok(())) - .wait() - .unwrap(); + exec.or_else(|e| { + assert!(e.is_elapsed()); + Ok::<_, ()>(()) + }) + .for_each(|_| Ok(())) + .wait() + .unwrap(); if 1 == done.rem.fetch_sub(1, SeqCst) { done.unpark.unpark(); @@ -185,17 +180,18 @@ fn hammer_reset() { barrier.wait(); for _ in 0..PER_THREAD { - let deadline1 = Instant::now() + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline1 = + Instant::now() + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); - let deadline2 = deadline1 + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline2 = + deadline1 + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); - let deadline3 = deadline2 + Duration::from_millis( - rng.gen_range(MIN_DELAY, MAX_DELAY)); + let deadline3 = + deadline2 + Duration::from_millis(rng.gen_range(MIN_DELAY, MAX_DELAY)); exec.push({ - handle.delay(deadline1) + handle + .delay(deadline1) // Select over a second delay .select2(handle.delay(deadline2)) .map_err(|e| panic!("boom; err={:?}", e)) @@ -203,7 +199,11 @@ fn hammer_reset() { use futures::future::Either::*; let now = Instant::now(); - assert!(now >= deadline1, "deadline greater by {:?}", deadline1 - now); + assert!( + now >= deadline1, + "deadline greater by {:?}", + deadline1 - now + ); let mut other = match res { A((_, other)) => other, @@ -215,17 +215,18 @@ fn hammer_reset() { }) .and_then(move |_| { let now = Instant::now(); - assert!(now >= deadline3, "deadline greater by {:?}", deadline3 - now); + assert!( + now >= deadline3, + "deadline greater by {:?}", + deadline3 - now + ); Ok(()) }) }); } // Run the logic - exec - .for_each(|_| Ok(())) - .wait() - .unwrap(); + exec.for_each(|_| Ok(())).wait().unwrap(); if 1 == done.rem.fetch_sub(1, SeqCst) { done.unpark.unpark(); diff --git a/tokio-timer/tests/interval.rs b/tokio-timer/tests/interval.rs index 42630b857..27828fc83 100644 --- a/tokio-timer/tests/interval.rs +++ b/tokio-timer/tests/interval.rs @@ -8,7 +8,7 @@ use support::*; use tokio_timer::*; -use futures::{Stream}; +use futures::Stream; #[test] #[should_panic] diff --git a/tokio-timer/tests/queue.rs b/tokio-timer/tests/queue.rs index 3d49bb392..eeba61041 100644 --- a/tokio-timer/tests/queue.rs +++ b/tokio-timer/tests/queue.rs @@ -1,14 +1,14 @@ extern crate futures; extern crate tokio_executor; -extern crate tokio_timer; extern crate tokio_mock_task; +extern crate tokio_timer; #[macro_use] mod support; use support::*; -use tokio_timer::*; use tokio_mock_task::MockTask; +use tokio_timer::*; use futures::Stream; @@ -286,7 +286,6 @@ fn expires_before_last_insert() { let mut queue = DelayQueue::new(); let mut task = MockTask::new(); - let epoch = time.now(); queue.insert_at("foo", epoch + ms(10_000)); @@ -308,7 +307,6 @@ fn expires_before_last_insert() { assert!(task.is_notified()); let entry = assert_ready!(queue).unwrap().into_inner(); assert_eq!(entry, "bar"); - }) } @@ -383,7 +381,6 @@ fn expire_second_key_when_reset_to_expire_earlier() { }) } - #[test] fn reset_first_expiring_item_to_expire_later() { mocked(|timer, time| { diff --git a/tokio-timer/tests/support/mod.rs b/tokio-timer/tests/support/mod.rs index cc30e166e..244d56b81 100644 --- a/tokio-timer/tests/support/mod.rs +++ b/tokio-timer/tests/support/mod.rs @@ -9,7 +9,7 @@ use futures::future::{lazy, Future}; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Mutex}; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; macro_rules! assert_ready { ($f:expr) => {{ @@ -56,7 +56,7 @@ macro_rules! assert_not_ready { macro_rules! assert_elapsed { ($f:expr) => { assert!($f.poll().unwrap_err().is_elapsed()); - } + }; } #[derive(Debug)] @@ -128,13 +128,15 @@ pub fn advance(timer: &mut Timer, duration: Duration) { } pub fn mocked(f: F) -> R -where F: FnOnce(&mut Timer, &mut MockTime) -> R +where + F: FnOnce(&mut Timer, &mut MockTime) -> R, { mocked_with_now(Instant::now(), f) } pub fn mocked_with_now(now: Instant, f: F) -> R -where F: FnOnce(&mut Timer, &mut MockTime) -> R +where + F: FnOnce(&mut Timer, &mut MockTime) -> R, { let mut time = MockTime::new(now); let park = time.mock_park(); @@ -147,9 +149,9 @@ where F: FnOnce(&mut Timer, &mut MockTime) -> R let handle = timer.handle(); ::tokio_timer::with_default(&handle, enter, |_| { - lazy(|| { - Ok::<_, ()>(f(&mut timer, &mut time)) - }).wait().unwrap() + lazy(|| Ok::<_, ()>(f(&mut timer, &mut time))) + .wait() + .unwrap() }) }) } @@ -171,9 +173,7 @@ impl MockTime { pub fn mock_now(&self) -> MockNow { let inner = self.inner.clone(); - MockNow { - inner, - } + MockNow { inner } } pub fn mock_park(&self) -> MockPark { @@ -217,8 +217,7 @@ impl Park for MockPark { fn park(&mut self) -> Result<(), Self::Error> { let mut inner = self.inner.lock().map_err(|_| ())?; - let duration = inner.park_for.take() - .expect("call park_for first"); + let duration = inner.park_for.take().expect("call park_for first"); inner.advance(duration); Ok(()) diff --git a/tokio-timer/tests/throttle.rs b/tokio-timer/tests/throttle.rs index ace947dd1..4ef157ea6 100644 --- a/tokio-timer/tests/throttle.rs +++ b/tokio-timer/tests/throttle.rs @@ -7,18 +7,14 @@ extern crate tokio_timer; mod support; use support::*; -use futures::{ - prelude::*, - sync::mpsc, -}; +use futures::{prelude::*, sync::mpsc}; use tokio::util::StreamExt; #[test] fn throttle() { mocked(|timer, _| { let (tx, rx) = mpsc::unbounded(); - let mut stream = rx.throttle(ms(1)) - .map_err(|e| panic!("{:?}", e)); + let mut stream = rx.throttle(ms(1)).map_err(|e| panic!("{:?}", e)); assert_not_ready!(stream); @@ -40,8 +36,7 @@ fn throttle() { fn throttle_dur_0() { mocked(|_, _| { let (tx, rx) = mpsc::unbounded(); - let mut stream = rx.throttle(ms(0)) - .map_err(|e| panic!("{:?}", e)); + let mut stream = rx.throttle(ms(0)).map_err(|e| panic!("{:?}", e)); assert_not_ready!(stream); diff --git a/tokio-timer/tests/timeout.rs b/tokio-timer/tests/timeout.rs index e7b08bf34..8e10776ae 100644 --- a/tokio-timer/tests/timeout.rs +++ b/tokio-timer/tests/timeout.rs @@ -8,8 +8,8 @@ use support::*; use tokio_timer::*; +use futures::sync::{mpsc, oneshot}; use futures::{future, Future, Stream}; -use futures::sync::{oneshot, mpsc}; #[test] fn simultaneous_deadline_future_completion() { diff --git a/tokio-tls/examples/download-rust-lang.rs b/tokio-tls/examples/download-rust-lang.rs index 4d8780e8c..9d23dc78f 100644 --- a/tokio-tls/examples/download-rust-lang.rs +++ b/tokio-tls/examples/download-rust-lang.rs @@ -14,27 +14,31 @@ use tokio::runtime::Runtime; fn main() -> Result<(), Box> { let mut runtime = Runtime::new()?; - let addr = "www.rust-lang.org:443".to_socket_addrs()?.next().ok_or("failed to resolve www.rust-lang.org")?; + let addr = "www.rust-lang.org:443" + .to_socket_addrs()? + .next() + .ok_or("failed to resolve www.rust-lang.org")?; let socket = TcpStream::connect(&addr); let cx = TlsConnector::builder().build()?; let cx = tokio_tls::TlsConnector::from(cx); let tls_handshake = socket.and_then(move |socket| { - cx.connect("www.rust-lang.org", socket).map_err(|e| { - io::Error::new(io::ErrorKind::Other, e) - }) + cx.connect("www.rust-lang.org", socket) + .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }); let request = tls_handshake.and_then(|socket| { - tokio_io::io::write_all(socket, "\ - GET / HTTP/1.0\r\n\ - Host: www.rust-lang.org\r\n\ - \r\n\ - ".as_bytes()) - }); - let response = request.and_then(|(socket, _)| { - tokio_io::io::read_to_end(socket, Vec::new()) + tokio_io::io::write_all( + socket, + "\ + GET / HTTP/1.0\r\n\ + Host: www.rust-lang.org\r\n\ + \r\n\ + " + .as_bytes(), + ) }); + let response = request.and_then(|(socket, _)| tokio_io::io::read_to_end(socket, Vec::new())); let (_, data) = runtime.block_on(response)?; println!("{}", String::from_utf8_lossy(&data)); diff --git a/tokio-tls/examples/echo.rs b/tokio-tls/examples/echo.rs index 697c14c63..c39d5873b 100644 --- a/tokio-tls/examples/echo.rs +++ b/tokio-tls/examples/echo.rs @@ -16,43 +16,42 @@ fn main() -> Result<(), Box> { // Create the TLS acceptor. let der = include_bytes!("identity.p12"); let cert = Identity::from_pkcs12(der, "mypass")?; - let tls_acceptor = tokio_tls::TlsAcceptor::from( - native_tls::TlsAcceptor::builder(cert).build()?); + let tls_acceptor = + tokio_tls::TlsAcceptor::from(native_tls::TlsAcceptor::builder(cert).build()?); // Iterate incoming connections - let server = tcp.incoming().for_each(move |tcp| { + let server = tcp + .incoming() + .for_each(move |tcp| { + // Accept the TLS connection. + let tls_accept = tls_acceptor + .accept(tcp) + .and_then(move |tls| { + // Split up the read and write halves + let (reader, writer) = tls.split(); - // Accept the TLS connection. - let tls_accept = tls_acceptor.accept(tcp) - .and_then(move |tls| { - // Split up the read and write halves - let (reader, writer) = tls.split(); + // Copy the data back to the client + let conn = io::copy(reader, writer) + // print what happened + .map(|(n, _, _)| println!("wrote {} bytes", n)) + // Handle any errors + .map_err(|err| println!("IO error {:?}", err)); - // Copy the data back to the client - let conn = io::copy(reader, writer) - // print what happened - .map(|(n, _, _)| { - println!("wrote {} bytes", n) - }) - // Handle any errors - .map_err(|err| { - println!("IO error {:?}", err) - }); + // Spawn the future as a concurrent task + tokio::spawn(conn); - // Spawn the future as a concurrent task - tokio::spawn(conn); + Ok(()) + }) + .map_err(|err| { + println!("TLS accept error: {:?}", err); + }); + tokio::spawn(tls_accept); - Ok(()) - }) - .map_err(|err| { - println!("TLS accept error: {:?}", err); - }); - tokio::spawn(tls_accept); - - Ok(()) - }).map_err(|err| { - println!("server error {:?}", err); - }); + Ok(()) + }) + .map_err(|err| { + println!("server error {:?}", err); + }); // Start the runtime and spin up the server tokio::run(server); diff --git a/tokio-tls/src/lib.rs b/tokio-tls/src/lib.rs index 63275c7fe..66bc39648 100644 --- a/tokio-tls/src/lib.rs +++ b/tokio-tls/src/lib.rs @@ -25,8 +25,8 @@ extern crate tokio_io; use std::io::{self, Read, Write}; -use futures::{Poll, Future, Async}; -use native_tls::{HandshakeError, Error}; +use futures::{Async, Future, Poll}; +use native_tls::{Error, HandshakeError}; use tokio_io::{AsyncRead, AsyncWrite}; /// A wrapper around an underlying raw stream which implements the TLS or SSL @@ -101,9 +101,7 @@ impl Write for TlsStream { } } - -impl AsyncRead for TlsStream { -} +impl AsyncRead for TlsStream {} impl AsyncWrite for TlsStream { fn shutdown(&mut self) -> Poll<(), io::Error> { @@ -126,7 +124,8 @@ impl TlsConnector { /// provided here to perform the client half of a connection to a /// TLS-powered server. pub fn connect(&self, domain: &str, stream: S) -> Connect - where S: AsyncRead + AsyncWrite, + where + S: AsyncRead + AsyncWrite, { Connect { inner: MidHandshake { @@ -138,9 +137,7 @@ impl TlsConnector { impl From for TlsConnector { fn from(inner: native_tls::TlsConnector) -> TlsConnector { - TlsConnector { - inner, - } + TlsConnector { inner } } } @@ -156,7 +153,8 @@ impl TlsAcceptor { /// `TcpListener`. That socket is then passed to this function to perform /// the server half of accepting a client connection. pub fn accept(&self, stream: S) -> Accept - where S: AsyncRead + AsyncWrite, + where + S: AsyncRead + AsyncWrite, { Accept { inner: MidHandshake { @@ -168,9 +166,7 @@ impl TlsAcceptor { impl From for TlsAcceptor { fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor { - TlsAcceptor { - inner, - } + TlsAcceptor { inner } } } @@ -200,16 +196,14 @@ impl Future for MidHandshake { match self.inner.take().expect("cannot poll MidHandshake twice") { Ok(stream) => Ok(TlsStream { inner: stream }.into()), Err(HandshakeError::Failure(e)) => Err(e), - Err(HandshakeError::WouldBlock(s)) => { - match s.handshake() { - Ok(stream) => Ok(TlsStream { inner: stream }.into()), - Err(HandshakeError::Failure(e)) => Err(e), - Err(HandshakeError::WouldBlock(s)) => { - self.inner = Some(Err(HandshakeError::WouldBlock(s))); - Ok(Async::NotReady) - } + Err(HandshakeError::WouldBlock(s)) => match s.handshake() { + Ok(stream) => Ok(TlsStream { inner: stream }.into()), + Err(HandshakeError::Failure(e)) => Err(e), + Err(HandshakeError::WouldBlock(s)) => { + self.inner = Some(Err(HandshakeError::WouldBlock(s))); + Ok(Async::NotReady) } - } + }, } } } diff --git a/tokio-tls/tests/bad.rs b/tokio-tls/tests/bad.rs index 4373fd1cf..8b010a2a6 100644 --- a/tokio-tls/tests/bad.rs +++ b/tokio-tls/tests/bad.rs @@ -16,10 +16,12 @@ use tokio::net::TcpStream; use tokio::runtime::Runtime; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } cfg_if! { @@ -100,9 +102,8 @@ fn get_host(host: &'static str) -> Error { let builder = TlsConnector::builder(); let cx = builder.build().unwrap(); let cx = tokio_tls::TlsConnector::from(cx); - cx.connect(host, socket).map_err(|e| { - Error::new(io::ErrorKind::Other, e) - }) + cx.connect(host, socket) + .map_err(|e| Error::new(io::ErrorKind::Other, e)) }); let res = l.block_on(data); diff --git a/tokio-tls/tests/google.rs b/tokio-tls/tests/google.rs index 853ceda5f..aa4fc0f09 100644 --- a/tokio-tls/tests/google.rs +++ b/tokio-tls/tests/google.rs @@ -1,9 +1,9 @@ extern crate env_logger; extern crate futures; extern crate native_tls; +extern crate tokio; extern crate tokio_io; extern crate tokio_tls; -extern crate tokio; #[macro_use] extern crate cfg_if; @@ -13,15 +13,17 @@ use std::net::ToSocketAddrs; use futures::Future; use native_tls::TlsConnector; -use tokio_io::io::{flush, read_to_end, write_all}; use tokio::net::TcpStream; use tokio::runtime::Runtime; +use tokio_io::io::{flush, read_to_end, write_all}; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } cfg_if! { @@ -71,15 +73,15 @@ fn fetch_google() { let mut l = t!(Runtime::new()); let client = TcpStream::connect(&addr); - // Send off the request by first negotiating an SSL handshake, then writing // of our request, then flushing, then finally read off the response. - let data = client.and_then(move |socket| { - let builder = TlsConnector::builder(); - let connector = t!(builder.build()); - let connector = tokio_tls::TlsConnector::from(connector); - connector.connect("google.com", socket).map_err(native2io) - }) + let data = client + .and_then(move |socket| { + let builder = TlsConnector::builder(); + let connector = t!(builder.build()); + let connector = tokio_tls::TlsConnector::from(connector); + connector.connect("google.com", socket).map_err(native2io) + }) .and_then(|socket| write_all(socket, b"GET / HTTP/1.0\r\n\r\n")) .and_then(|(socket, _)| flush(socket)) .and_then(|socket| read_to_end(socket, Vec::new())); @@ -105,12 +107,13 @@ fn wrong_hostname_error() { let mut l = t!(Runtime::new()); let client = TcpStream::connect(&addr); let data = client.and_then(move |socket| { - let builder = TlsConnector::builder(); - let connector = t!(builder.build()); - let connector = tokio_tls::TlsConnector::from(connector); - connector.connect("rust-lang.org", socket) - .map_err(native2io) - }); + let builder = TlsConnector::builder(); + let connector = t!(builder.build()); + let connector = tokio_tls::TlsConnector::from(connector); + connector + .connect("rust-lang.org", socket) + .map_err(native2io) + }); let res = l.block_on(data); assert!(res.is_err()); diff --git a/tokio-tls/tests/smoke.rs b/tokio-tls/tests/smoke.rs index b4e9d2bc2..a617d4d50 100644 --- a/tokio-tls/tests/smoke.rs +++ b/tokio-tls/tests/smoke.rs @@ -11,19 +11,21 @@ extern crate cfg_if; use std::io::{self, Read, Write}; use std::process::Command; -use futures::{Future, Poll}; use futures::stream::Stream; -use tokio_io::{AsyncRead, AsyncWrite}; -use tokio_io::io::{read_to_end, copy, shutdown}; -use tokio::runtime::Runtime; +use futures::{Future, Poll}; +use native_tls::{Identity, TlsAcceptor, TlsConnector}; use tokio::net::{TcpListener, TcpStream}; -use native_tls::{TlsConnector, TlsAcceptor, Identity}; +use tokio::runtime::Runtime; +use tokio_io::io::{copy, read_to_end, shutdown}; +use tokio_io::{AsyncRead, AsyncWrite}; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[allow(dead_code)] @@ -45,7 +47,10 @@ fn openssl_keys() -> &'static Keys { let certfile = path.join("test.crt"); let config = path.join("openssl.config"); - File::create(&config).unwrap().write_all(b"\ + File::create(&config) + .unwrap() + .write_all( + b"\ [req]\n\ distinguished_name=dn\n\ [ dn ]\n\ @@ -55,44 +60,60 @@ fn openssl_keys() -> &'static Keys { subjectAltName = @alt_names [alt_names] DNS.1 = localhost - ").unwrap(); + ", + ) + .unwrap(); let subj = "/C=US/ST=Denial/L=Sprintfield/O=Dis/CN=localhost"; let output = t!(Command::new("openssl") - .arg("req") - .arg("-nodes") - .arg("-x509") - .arg("-newkey").arg("rsa:2048") - .arg("-config").arg(&config) - .arg("-extensions").arg("ext") - .arg("-subj").arg(subj) - .arg("-keyout").arg(&keyfile) - .arg("-out").arg(&certfile) - .arg("-days").arg("1") - .output()); + .arg("req") + .arg("-nodes") + .arg("-x509") + .arg("-newkey") + .arg("rsa:2048") + .arg("-config") + .arg(&config) + .arg("-extensions") + .arg("ext") + .arg("-subj") + .arg(subj) + .arg("-keyout") + .arg(&keyfile) + .arg("-out") + .arg(&certfile) + .arg("-days") + .arg("1") + .output()); assert!(output.status.success()); let crtout = t!(Command::new("openssl") - .arg("x509") - .arg("-outform").arg("der") - .arg("-in").arg(&certfile) - .output()); + .arg("x509") + .arg("-outform") + .arg("der") + .arg("-in") + .arg(&certfile) + .output()); assert!(crtout.status.success()); let keyout = t!(Command::new("openssl") - .arg("rsa") - .arg("-outform").arg("der") - .arg("-in").arg(&keyfile) - .output()); + .arg("rsa") + .arg("-outform") + .arg("der") + .arg("-in") + .arg(&keyfile) + .output()); assert!(keyout.status.success()); let pkcs12out = t!(Command::new("openssl") - .arg("pkcs12") - .arg("-export") - .arg("-nodes") - .arg("-inkey").arg(&keyfile) - .arg("-in").arg(&certfile) - .arg("-password").arg("pass:foobar") - .output()); + .arg("pkcs12") + .arg("-export") + .arg("-nodes") + .arg("-inkey") + .arg(&keyfile) + .arg("-in") + .arg(&certfile) + .arg("-password") + .arg("pass:foobar") + .output()); assert!(pkcs12out.status.success()); let keys = Box::new(Keys { @@ -104,9 +125,7 @@ fn openssl_keys() -> &'static Keys { KEYS = Box::into_raw(keys); } }); - unsafe { - &*KEYS - } + unsafe { &*KEYS } } cfg_if! { @@ -509,24 +528,18 @@ fn client_to_server() { // Create a future to accept one socket, connect the ssl stream, and then // read all the data from it. let socket = srv.incoming().take(1).collect(); - let received = socket.map(|mut socket| { - socket.remove(0) - }).and_then(move |socket| { - server_cx.accept(socket).map_err(native2io) - }).and_then(|socket| { - read_to_end(socket, Vec::new()) - }); + let received = socket + .map(|mut socket| socket.remove(0)) + .and_then(move |socket| server_cx.accept(socket).map_err(native2io)) + .and_then(|socket| read_to_end(socket, Vec::new())); // Create a future to connect to our server, connect the ssl stream, and // then write a bunch of data to it. let client = TcpStream::connect(&addr); - let sent = client.and_then(move |socket| { - client_cx.connect("localhost", socket).map_err(native2io) - }).and_then(|socket| { - copy(io::repeat(9).take(AMT), socket) - }).and_then(|(amt, _repeat, socket)| { - shutdown(socket).map(move |_| amt) - }); + let sent = client + .and_then(move |socket| client_cx.connect("localhost", socket).map_err(native2io)) + .and_then(|socket| copy(io::repeat(9).take(AMT), socket)) + .and_then(|(amt, _repeat, socket)| shutdown(socket).map(move |_| amt)); // Finally, run everything! let (amt, (_, data)) = t!(l.block_on(sent.join(received))); @@ -546,22 +559,16 @@ fn server_to_client() { let (server_cx, client_cx) = contexts(); let socket = srv.incoming().take(1).collect(); - let sent = socket.map(|mut socket| { - socket.remove(0) - }).and_then(move |socket| { - server_cx.accept(socket).map_err(native2io) - }).and_then(|socket| { - copy(io::repeat(9).take(AMT), socket) - }).and_then(|(amt, _repeat, socket)| { - shutdown(socket).map(move |_| amt) - }); + let sent = socket + .map(|mut socket| socket.remove(0)) + .and_then(move |socket| server_cx.accept(socket).map_err(native2io)) + .and_then(|socket| copy(io::repeat(9).take(AMT), socket)) + .and_then(|(amt, _repeat, socket)| shutdown(socket).map(move |_| amt)); let client = TcpStream::connect(&addr); - let received = client.and_then(move |socket| { - client_cx.connect("localhost", socket).map_err(native2io) - }).and_then(|socket| { - read_to_end(socket, Vec::new()) - }); + let received = client + .and_then(move |socket| client_cx.connect("localhost", socket).map_err(native2io)) + .and_then(|socket| read_to_end(socket, Vec::new())); // Finally, run everything! let (amt, (_, data)) = t!(l.block_on(sent.join(received))); @@ -608,23 +615,23 @@ fn one_byte_at_a_time() { let (server_cx, client_cx) = contexts(); let socket = srv.incoming().take(1).collect(); - let sent = socket.map(|mut socket| { - socket.remove(0) - }).and_then(move |socket| { - server_cx.accept(OneByte { inner: socket }).map_err(native2io) - }).and_then(|socket| { - copy(io::repeat(9).take(AMT), socket) - }).and_then(|(amt, _repeat, socket)| { - shutdown(socket).map(move |_| amt) - }); + let sent = socket + .map(|mut socket| socket.remove(0)) + .and_then(move |socket| { + server_cx + .accept(OneByte { inner: socket }) + .map_err(native2io) + }) + .and_then(|socket| copy(io::repeat(9).take(AMT), socket)) + .and_then(|(amt, _repeat, socket)| shutdown(socket).map(move |_| amt)); let client = TcpStream::connect(&addr); - let received = client.and_then(move |socket| { - let socket = OneByte { inner: socket }; - client_cx.connect("localhost", socket).map_err(native2io) - }).and_then(|socket| { - read_to_end(socket, Vec::new()) - }); + let received = client + .and_then(move |socket| { + let socket = OneByte { inner: socket }; + client_cx.connect("localhost", socket).map_err(native2io) + }) + .and_then(|socket| read_to_end(socket, Vec::new())); let (amt, (_, data)) = t!(l.block_on(sent.join(received))); assert_eq!(amt, AMT); diff --git a/tokio-udp/src/frame.rs b/tokio-udp/src/frame.rs index 37097ca37..8662a2d1b 100644 --- a/tokio-udp/src/frame.rs +++ b/tokio-udp/src/frame.rs @@ -1,12 +1,12 @@ use std::io; -use std::net::{SocketAddr, Ipv4Addr, SocketAddrV4}; +use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; -use futures::{Async, Poll, Stream, Sink, StartSend, AsyncSink}; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use super::UdpSocket; +use bytes::{BufMut, BytesMut}; use tokio_codec::{Decoder, Encoder}; -use bytes::{BytesMut, BufMut}; /// A unified `Stream` and `Sink` interface to an underlying `UdpSocket`, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -67,7 +67,7 @@ impl Sink for UdpFramed { if !self.flushed { match try!(self.poll_complete()) { - Async::Ready(()) => {}, + Async::Ready(()) => {} Async::NotReady => return Ok(AsyncSink::NotReady(item)), } } @@ -83,7 +83,7 @@ impl Sink for UdpFramed { fn poll_complete(&mut self) -> Poll<(), C::Error> { if self.flushed { - return Ok(Async::Ready(())) + return Ok(Async::Ready(())); } trace!("flushing frame; length={}", self.wr.len()); @@ -97,8 +97,11 @@ impl Sink for UdpFramed { if wrote_all { Ok(Async::Ready(())) } else { - Err(io::Error::new(io::ErrorKind::Other, - "failed to write entire datagram to socket").into()) + Err(io::Error::new( + io::ErrorKind::Other, + "failed to write entire datagram to socket", + ) + .into()) } } diff --git a/tokio-udp/src/lib.rs b/tokio-udp/src/lib.rs index 740fd9303..aed9df59e 100644 --- a/tokio-udp/src/lib.rs +++ b/tokio-udp/src/lib.rs @@ -30,11 +30,11 @@ extern crate tokio_io; extern crate tokio_reactor; mod frame; -mod socket; -mod send_dgram; mod recv_dgram; +mod send_dgram; +mod socket; pub use self::frame::UdpFramed; -pub use self::socket::UdpSocket; -pub use self::send_dgram::SendDgram; pub use self::recv_dgram::RecvDgram; +pub use self::send_dgram::SendDgram; +pub use self::socket::UdpSocket; diff --git a/tokio-udp/src/recv_dgram.rs b/tokio-udp/src/recv_dgram.rs index 2f3d5f204..5ed63f929 100644 --- a/tokio-udp/src/recv_dgram.rs +++ b/tokio-udp/src/recv_dgram.rs @@ -12,7 +12,7 @@ use futures::{Async, Future, Poll}; #[derive(Debug)] pub struct RecvDgram { /// None means future was completed - state: Option> + state: Option>, } /// A struct is used to represent the full info of RecvDgram. @@ -21,7 +21,7 @@ struct RecvDgramInner { /// Rx socket socket: UdpSocket, /// The received data will be put in the buffer - buffer: T + buffer: T, } /// Components of a `RecvDgram` future, returned from `into_parts`. @@ -32,13 +32,16 @@ pub struct Parts { /// The buffer pub buffer: T, - _priv: () + _priv: (), } impl RecvDgram { /// Create a new future to receive UDP Datagram pub(crate) fn new(socket: UdpSocket, buffer: T) -> RecvDgram { - let inner = RecvDgramInner { socket: socket, buffer: buffer }; + let inner = RecvDgramInner { + socket: socket, + buffer: buffer, + }; RecvDgram { state: Some(inner) } } @@ -69,28 +72,32 @@ impl RecvDgram { /// /// If called after the future has completed. pub fn into_parts(mut self) -> Parts { - let state = self.state + let state = self + .state .take() .expect("into_parts called after completion"); Parts { socket: state.socket, buffer: state.buffer, - _priv: () + _priv: (), } } } impl Future for RecvDgram - where T: AsMut<[u8]>, +where + T: AsMut<[u8]>, { type Item = (UdpSocket, T, usize, SocketAddr); type Error = io::Error; fn poll(&mut self) -> Poll { let (n, addr) = { - let ref mut inner = - self.state.as_mut().expect("RecvDgram polled after completion"); + let ref mut inner = self + .state + .as_mut() + .expect("RecvDgram polled after completion"); try_ready!(inner.socket.poll_recv_from(inner.buffer.as_mut())) }; diff --git a/tokio-udp/src/send_dgram.rs b/tokio-udp/src/send_dgram.rs index 50d650389..ccfa1236f 100644 --- a/tokio-udp/src/send_dgram.rs +++ b/tokio-udp/src/send_dgram.rs @@ -12,7 +12,7 @@ use futures::{Async, Future, Poll}; #[derive(Debug)] pub struct SendDgram { /// None means future was completed - state: Option> + state: Option>, } /// A struct is used to represent the full info of SendDgram. @@ -29,7 +29,11 @@ struct SendDgramInner { impl SendDgram { /// Create a new future to send UDP Datagram pub(crate) fn new(socket: UdpSocket, buffer: T, addr: SocketAddr) -> SendDgram { - let inner = SendDgramInner { socket: socket, buffer: buffer, addr: addr }; + let inner = SendDgramInner { + socket: socket, + buffer: buffer, + addr: addr, + }; SendDgram { state: Some(inner) } } } @@ -39,19 +43,26 @@ fn incomplete_write(reason: &str) -> io::Error { } impl Future for SendDgram - where T: AsRef<[u8]>, +where + T: AsRef<[u8]>, { type Item = (UdpSocket, T); type Error = io::Error; fn poll(&mut self) -> Poll<(UdpSocket, T), io::Error> { { - let ref mut inner = - self.state.as_mut().expect("SendDgram polled after completion"); - let n = try_ready!(inner.socket.poll_send_to(inner.buffer.as_ref(), &inner.addr)); + let ref mut inner = self + .state + .as_mut() + .expect("SendDgram polled after completion"); + let n = try_ready!(inner + .socket + .poll_send_to(inner.buffer.as_ref(), &inner.addr)); if n != inner.buffer.as_ref().len() { - return Err(incomplete_write("failed to send entire message \ - in datagram")) + return Err(incomplete_write( + "failed to send entire message \ + in datagram", + )); } } diff --git a/tokio-udp/src/socket.rs b/tokio-udp/src/socket.rs index 731af300d..e3d3b6863 100644 --- a/tokio-udp/src/socket.rs +++ b/tokio-udp/src/socket.rs @@ -1,8 +1,8 @@ -use super::{SendDgram, RecvDgram}; +use super::{RecvDgram, SendDgram}; -use std::io; -use std::net::{self, SocketAddr, Ipv4Addr, Ipv6Addr}; use std::fmt; +use std::io; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; use futures::{Async, Poll}; use mio; @@ -18,8 +18,7 @@ impl UdpSocket { /// This function will create a new UDP socket and attempt to bind it to /// the `addr` provided. pub fn bind(addr: &SocketAddr) -> io::Result { - mio::net::UdpSocket::bind(addr) - .map(UdpSocket::new) + mio::net::UdpSocket::bind(addr).map(UdpSocket::new) } fn new(socket: mio::net::UdpSocket) -> UdpSocket { @@ -38,8 +37,7 @@ impl UdpSocket { /// `reuse_address` or binding to multiple addresses. /// /// Use `Handle::default()` to lazily bind to an event loop, just like `bind` does. - pub fn from_std(socket: net::UdpSocket, - handle: &Handle) -> io::Result { + pub fn from_std(socket: net::UdpSocket, handle: &Handle) -> io::Result { let io = mio::net::UdpSocket::from_socket(socket)?; let io = PollEvented::new_with_handle(io, handle)?; Ok(UdpSocket { io }) @@ -196,7 +194,8 @@ impl UdpSocket { /// should be broadly applicable to accepting data which can be converted /// to a slice. pub fn send_dgram(self, buf: T, addr: &SocketAddr) -> SendDgram - where T: AsRef<[u8]>, + where + T: AsRef<[u8]>, { SendDgram::new(self, buf, *addr) } @@ -244,7 +243,8 @@ impl UdpSocket { /// should be broadly applicable to accepting data which can be converted /// to a slice. pub fn recv_dgram(self, buf: T) -> RecvDgram - where T: AsMut<[u8]>, + where + T: AsMut<[u8]>, { RecvDgram::new(self, buf) } @@ -389,9 +389,7 @@ impl UdpSocket { /// address of the local interface with which the system should join the /// multicast group. If it's equal to `INADDR_ANY` then an appropriate /// interface is chosen by the system. - pub fn join_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { self.io.get_ref().join_multicast_v4(multiaddr, interface) } @@ -400,9 +398,7 @@ impl UdpSocket { /// This function specifies a new multicast group for this socket to join. /// The address must be a valid multicast address, and `interface` is the /// index of the interface to join/leave (or 0 to indicate any interface). - pub fn join_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { self.io.get_ref().join_multicast_v6(multiaddr, interface) } @@ -411,9 +407,7 @@ impl UdpSocket { /// For more information about this option, see [`join_multicast_v4`]. /// /// [`join_multicast_v4`]: #method.join_multicast_v4 - pub fn leave_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { self.io.get_ref().leave_multicast_v4(multiaddr, interface) } @@ -422,9 +416,7 @@ impl UdpSocket { /// For more information about this option, see [`join_multicast_v6`]. /// /// [`join_multicast_v6`]: #method.join_multicast_v6 - pub fn leave_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { self.io.get_ref().leave_multicast_v6(multiaddr, interface) } } @@ -437,8 +429,8 @@ impl fmt::Debug for UdpSocket { #[cfg(all(unix))] mod sys { - use std::os::unix::prelude::*; use super::UdpSocket; + use std::os::unix::prelude::*; impl AsRawFd for UdpSocket { fn as_raw_fd(&self) -> RawFd { diff --git a/tokio-udp/tests/udp.rs b/tokio-udp/tests/udp.rs index bbd96a9b6..aadd15ca8 100644 --- a/tokio-udp/tests/udp.rs +++ b/tokio-udp/tests/udp.rs @@ -1,6 +1,6 @@ extern crate futures; -extern crate tokio_udp; extern crate tokio_codec; +extern crate tokio_udp; #[macro_use] extern crate tokio_io; extern crate bytes; @@ -9,17 +9,19 @@ extern crate env_logger; use std::io; use std::net::SocketAddr; -use futures::{Future, Poll, Stream, Sink}; +use futures::{Future, Poll, Sink, Stream}; -use tokio_udp::{UdpSocket, UdpFramed}; -use tokio_codec::{Encoder, Decoder}; -use bytes::{BytesMut, BufMut}; +use bytes::{BufMut, BytesMut}; +use tokio_codec::{Decoder, Encoder}; +use tokio_udp::{UdpFramed, UdpSocket}; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } fn send_messages(send: S, recv: R) { @@ -45,7 +47,7 @@ fn send_messages(send: S, recv: R) { #[test] fn send_to_and_recv_from() { - send_messages(SendTo {}, RecvFrom {}); + send_messages(SendTo {}, RecvFrom {}); } #[test] @@ -61,7 +63,12 @@ trait SendFn { struct SendTo {} impl SendFn for SendTo { - fn send(&self, socket: &mut UdpSocket, buf: &[u8], addr: &SocketAddr) -> Result { + fn send( + &self, + socket: &mut UdpSocket, + buf: &[u8], + addr: &SocketAddr, + ) -> Result { socket.send_to(buf, addr) } } @@ -70,7 +77,12 @@ impl SendFn for SendTo { struct Send {} impl SendFn for Send { - fn send(&self, socket: &mut UdpSocket, buf: &[u8], addr: &SocketAddr) -> Result { + fn send( + &self, + socket: &mut UdpSocket, + buf: &[u8], + addr: &SocketAddr, + ) -> Result { socket.connect(addr).expect("could not connect"); socket.send(buf) } @@ -99,7 +111,9 @@ impl Future for SendMessage { type Error = io::Error; fn poll(&mut self) -> Poll { - let n = try_nb!(self.send.send(self.socket.as_mut().unwrap(), &self.data[..], &self.addr)); + let n = try_nb!(self + .send + .send(self.socket.as_mut().unwrap(), &self.data[..], &self.addr)); assert_eq!(n, self.data.len()); @@ -115,8 +129,12 @@ trait RecvFn { struct RecvFrom {} impl RecvFn for RecvFrom { - fn recv(&self, socket: &mut UdpSocket, buf: &mut [u8], - expected_addr: &SocketAddr) -> Result { + fn recv( + &self, + socket: &mut UdpSocket, + buf: &mut [u8], + expected_addr: &SocketAddr, + ) -> Result { socket.recv_from(buf).map(|(s, addr)| { assert_eq!(addr, *expected_addr); s @@ -128,7 +146,12 @@ impl RecvFn for RecvFrom { struct Recv {} impl RecvFn for Recv { - fn recv(&self, socket: &mut UdpSocket, buf: &mut [u8], _: &SocketAddr) -> Result { + fn recv( + &self, + socket: &mut UdpSocket, + buf: &mut [u8], + _: &SocketAddr, + ) -> Result { socket.recv(buf) } } @@ -141,8 +164,12 @@ struct RecvMessage { } impl RecvMessage { - fn new(socket: UdpSocket, recv: R, expected_addr: SocketAddr, - expected_data: &'static [u8]) -> RecvMessage { + fn new( + socket: UdpSocket, + recv: R, + expected_addr: SocketAddr, + expected_data: &'static [u8], + ) -> RecvMessage { RecvMessage { socket: Some(socket), recv: recv, @@ -158,8 +185,11 @@ impl Future for RecvMessage { fn poll(&mut self) -> Poll { let mut buf = vec![0u8; 10 + self.expected_data.len() * 10]; - let n = try_nb!(self.recv.recv(&mut self.socket.as_mut().unwrap(), &mut buf[..], - &self.expected_addr)); + let n = try_nb!(self.recv.recv( + &mut self.socket.as_mut().unwrap(), + &mut buf[..], + &self.expected_addr + )); assert_eq!(n, self.expected_data.len()); assert_eq!(&buf[..self.expected_data.len()], &self.expected_data[..]); diff --git a/tokio-uds/src/frame.rs b/tokio-uds/src/frame.rs index 49c8948c6..dbcf039e4 100644 --- a/tokio-uds/src/frame.rs +++ b/tokio-uds/src/frame.rs @@ -2,12 +2,12 @@ use std::io; use std::os::unix::net::SocketAddr; use std::path::Path; -use futures::{Async, Poll, Stream, Sink, StartSend, AsyncSink}; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use super::UnixDatagram; +use bytes::{BufMut, BytesMut}; use tokio_codec::{Decoder, Encoder}; -use bytes::{BytesMut, BufMut}; /// A unified `Stream` and `Sink` interface to an underlying `UnixDatagram`, using /// the `Encoder` and `Decoder` traits to encode and decode frames. @@ -67,7 +67,7 @@ impl, C: Encoder> Sink for UnixDatagramFramed { if !self.flushed { match try!(self.poll_complete()) { - Async::Ready(()) => {}, + Async::Ready(()) => {} Async::NotReady => return Ok(AsyncSink::NotReady(item)), } } @@ -83,14 +83,19 @@ impl, C: Encoder> Sink for UnixDatagramFramed { fn poll_complete(&mut self) -> Poll<(), C::Error> { if self.flushed { - return Ok(Async::Ready(())) + return Ok(Async::Ready(())); } let n = { let out_path = match self.out_addr { Some(ref out_path) => out_path.as_ref(), - None => return Err(io::Error::new(io::ErrorKind::Other, - "internal error: addr not available while data not flushed").into()), + None => { + return Err(io::Error::new( + io::ErrorKind::Other, + "internal error: addr not available while data not flushed", + ) + .into()); + } }; trace!("flushing frame; length={}", self.wr.len()); @@ -107,8 +112,11 @@ impl, C: Encoder> Sink for UnixDatagramFramed { self.out_addr = None; Ok(Async::Ready(())) } else { - Err(io::Error::new(io::ErrorKind::Other, - "failed to write entire datagram to socket").into()) + Err(io::Error::new( + io::ErrorKind::Other, + "failed to write entire datagram to socket", + ) + .into()) } } diff --git a/tokio-uds/src/incoming.rs b/tokio-uds/src/incoming.rs index 28d4d7683..472fcf9bf 100644 --- a/tokio-uds/src/incoming.rs +++ b/tokio-uds/src/incoming.rs @@ -1,6 +1,6 @@ use {UnixListener, UnixStream}; -use futures::{Stream, Poll}; +use futures::{Poll, Stream}; use std::io; @@ -24,4 +24,3 @@ impl Stream for Incoming { Ok(Some(try_ready!(self.inner.poll_accept()).0).into()) } } - diff --git a/tokio-uds/src/lib.rs b/tokio-uds/src/lib.rs index 4c02185a8..feacf2f97 100644 --- a/tokio-uds/src/lib.rs +++ b/tokio-uds/src/lib.rs @@ -34,5 +34,5 @@ pub use incoming::Incoming; pub use listener::UnixListener; pub use recv_dgram::RecvDgram; pub use send_dgram::SendDgram; -pub use stream::{UnixStream, ConnectFuture}; +pub use stream::{ConnectFuture, UnixStream}; pub use ucred::UCred; diff --git a/tokio-uds/src/recv_dgram.rs b/tokio-uds/src/recv_dgram.rs index 390202f38..8bb616801 100644 --- a/tokio-uds/src/recv_dgram.rs +++ b/tokio-uds/src/recv_dgram.rs @@ -20,23 +20,17 @@ pub struct RecvDgram { /// avoided. #[derive(Debug)] enum State { - Receiving { - sock: UnixDatagram, - buf: T, - }, + Receiving { sock: UnixDatagram, buf: T }, Empty, } impl RecvDgram where - T: AsMut<[u8]> + T: AsMut<[u8]>, { pub(crate) fn new(sock: UnixDatagram, buf: T) -> RecvDgram { RecvDgram { - st: State::Receiving { - sock, - buf, - }, + st: State::Receiving { sock, buf }, } } } @@ -71,9 +65,7 @@ where panic!() } - if let State::Receiving { sock, buf } = - mem::replace(&mut self.st, State::Empty) - { + if let State::Receiving { sock, buf } = mem::replace(&mut self.st, State::Empty) { Ok(Async::Ready((sock, buf, received, peer))) } else { panic!() diff --git a/tokio-uds/src/send_dgram.rs b/tokio-uds/src/send_dgram.rs index 59d438b76..d598646a4 100644 --- a/tokio-uds/src/send_dgram.rs +++ b/tokio-uds/src/send_dgram.rs @@ -34,11 +34,7 @@ where { pub(crate) fn new(sock: UnixDatagram, buf: T, addr: P) -> SendDgram { SendDgram { - st: State::Sending { - sock, - buf, - addr, - } + st: State::Sending { sock, buf, addr }, } } } @@ -70,9 +66,7 @@ where } else { panic!() } - if let State::Sending { sock, buf, addr: _ } = - mem::replace(&mut self.st, State::Empty) - { + if let State::Sending { sock, buf, addr: _ } = mem::replace(&mut self.st, State::Empty) { Ok(Async::Ready((sock, buf))) } else { panic!() diff --git a/tokio-uds/src/stream.rs b/tokio-uds/src/stream.rs index 7098c85fe..7a1adf5e9 100644 --- a/tokio-uds/src/stream.rs +++ b/tokio-uds/src/stream.rs @@ -50,8 +50,7 @@ impl UnixStream { where P: AsRef, { - let res = mio_uds::UnixStream::connect(path) - .map(UnixStream::new); + let res = mio_uds::UnixStream::connect(path).map(UnixStream::new); let inner = match res { Ok(stream) => State::Waiting(stream), @@ -260,11 +259,11 @@ impl Future for ConnectFuture { match self.inner { State::Waiting(ref mut stream) => { if let Async::NotReady = stream.io.poll_write_ready()? { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } if let Some(e) = try!(stream.io.get_ref().take_error()) { - return Err(e) + return Err(e); } } State::Error(_) => { @@ -273,8 +272,8 @@ impl Future for ConnectFuture { _ => unreachable!(), }; - return Err(e) - }, + return Err(e); + } State::Empty => panic!("can't poll stream twice"), } diff --git a/tokio-uds/src/ucred.rs b/tokio-uds/src/ucred.rs index bc53ea171..92843e895 100644 --- a/tokio-uds/src/ucred.rs +++ b/tokio-uds/src/ucred.rs @@ -12,7 +12,14 @@ pub struct UCred { #[cfg(any(target_os = "linux", target_os = "android"))] pub use self::impl_linux::get_peer_cred; -#[cfg(any(target_os = "dragonfly", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] pub use self::impl_macos::get_peer_cred; #[cfg(any(target_os = "solaris"))] @@ -21,9 +28,9 @@ pub use self::impl_solaris::get_peer_cred; #[cfg(any(target_os = "linux", target_os = "android"))] pub mod impl_linux { use libc::{c_void, getsockopt, socklen_t, SOL_SOCKET, SO_PEERCRED}; + use std::os::unix::io::AsRawFd; use std::{io, mem}; use UnixStream; - use std::os::unix::io::AsRawFd; use libc::ucred; @@ -64,12 +71,19 @@ pub mod impl_linux { } } -#[cfg(any(target_os = "dragonfly", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] pub mod impl_macos { use libc::getpeereid; + use std::os::unix::io::AsRawFd; use std::{io, mem}; use UnixStream; - use std::os::unix::io::AsRawFd; pub fn get_peer_cred(sock: &UnixStream) -> io::Result { unsafe { @@ -88,13 +102,12 @@ pub mod impl_macos { } } - #[cfg(any(target_os = "solaris"))] pub mod impl_solaris { use std::io; use std::os::unix::io::AsRawFd; - use UnixStream; use std::ptr; + use UnixStream; #[allow(non_camel_case_types)] enum ucred_t {} @@ -104,7 +117,10 @@ pub mod impl_solaris { fn ucred_geteuid(cred: *const ucred_t) -> super::uid_t; fn ucred_getegid(cred: *const ucred_t) -> super::gid_t; - fn getpeerucred(fd: ::std::os::raw::c_int, cred: *mut *mut ucred_t) -> ::std::os::raw::c_int; + fn getpeerucred( + fd: ::std::os::raw::c_int, + cred: *mut *mut ucred_t, + ) -> ::std::os::raw::c_int; } pub fn get_peer_cred(sock: &UnixStream) -> io::Result { @@ -121,10 +137,7 @@ pub mod impl_solaris { ucred_free(cred); - Ok(super::UCred { - uid, - gid, - }) + Ok(super::UCred { uid, gid }) } else { Err(io::Error::last_os_error()) } @@ -132,18 +145,23 @@ pub mod impl_solaris { } } - // Note that LOCAL_PEERCRED is not supported on DragonFly (yet). So do not run tests. #[cfg(not(target_os = "dragonfly"))] #[cfg(test)] mod test { - use UnixStream; - use libc::geteuid; use libc::getegid; + use libc::geteuid; + use UnixStream; #[test] - #[cfg_attr(target_os = "freebsd", ignore = "Requires FreeBSD 12.0 or later. https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=176419")] - #[cfg_attr(target_os = "netbsd", ignore = "NetBSD does not support getpeereid() for sockets created by socketpair()")] + #[cfg_attr( + target_os = "freebsd", + ignore = "Requires FreeBSD 12.0 or later. https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=176419" + )] + #[cfg_attr( + target_os = "netbsd", + ignore = "NetBSD does not support getpeereid() for sockets created by socketpair()" + )] fn test_socket_pair() { let (a, b) = UnixStream::pair().unwrap(); let cred_a = a.peer_cred().unwrap(); diff --git a/tokio-uds/tests/datagram.rs b/tokio-uds/tests/datagram.rs index 6f58f7c07..d7d6b587c 100644 --- a/tokio-uds/tests/datagram.rs +++ b/tokio-uds/tests/datagram.rs @@ -61,12 +61,16 @@ fn framed_echo() { let (sink, stream) = server.split(); - let echo_stream = stream.map(|(msg, addr)| (msg, addr.as_pathname().unwrap().to_path_buf())); + let echo_stream = + stream.map(|(msg, addr)| (msg, addr.as_pathname().unwrap().to_path_buf())); // spawn echo server - rt.spawn(echo_stream.forward(sink) - .map_err(|e| panic!("err={:?}", e)) - .map(|_| ())); + rt.spawn( + echo_stream + .forward(sink) + .map_err(|e| panic!("err={:?}", e)) + .map(|_| ()), + ); } { @@ -75,7 +79,8 @@ fn framed_echo() { let (sink, stream) = client.split(); - rt.block_on(sink.send(("ECHO".to_string(), server_path))).unwrap(); + rt.block_on(sink.send(("ECHO".to_string(), server_path))) + .unwrap(); let response = rt.block_on(stream.take(1).collect()).unwrap(); assert_eq!(response[0].0, "ECHO"); diff --git a/tokio-uds/tests/stream.rs b/tokio-uds/tests/stream.rs index ebb183524..c9de684fb 100644 --- a/tokio-uds/tests/stream.rs +++ b/tokio-uds/tests/stream.rs @@ -11,15 +11,17 @@ use tokio_uds::*; use tokio::io; use tokio::runtime::current_thread::Runtime; -use futures::{Future, Stream}; use futures::sync::oneshot; +use futures::{Future, Stream}; use tempfile::Builder; macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {:?}", stringify!($e), e), - }) + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; } #[test] @@ -33,7 +35,8 @@ fn echo() { let (tx, rx) = oneshot::channel(); rt.spawn({ - server.incoming() + server + .incoming() .into_future() .and_then(move |(sock, _)| { tx.send(sock.unwrap()).unwrap();