chore: apply rustfmt to all crates (#917)

This commit is contained in:
Carl Lerche
2019-02-21 11:56:15 -08:00
committed by GitHub
parent ab595d0825
commit 80162306e7
253 changed files with 3710 additions and 3407 deletions
+9 -7
View File
@@ -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]
+5 -10
View File
@@ -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();
}
+2 -2
View File
@@ -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::*;
-1
View File
@@ -23,5 +23,4 @@ fn enumerate() {
result.wait(),
Ok(vec![(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)])
);
}
+27 -22
View File
@@ -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::<Vec<_>>();
.collect::<Vec<_>>();
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<usize> {
+190 -143
View File
@@ -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::<Vec<_>>();
let some_as = std::iter::repeat(b'a').take(1024).collect::<Vec<_>>();
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<usize> {
@@ -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(()),
+12 -10
View File
@@ -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();
+27 -12
View File
@@ -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 || {
+5 -3
View File
@@ -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<Future<Item = (), Error = ()>>;
@@ -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(&notify, id)
.unwrap();
});
+83 -67
View File
@@ -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<Future<Item=(), Error=()> + Send> {
fn create_client_server_future() -> Box<Future<Item = (), Error = ()> + 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<Future<Item=(), Error=()> + 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<F>(spawn: F)
where
F: Fn(Box<Future<Item=(), Error=()> + Send>),
F: Fn(Box<Future<Item = (), Error = ()> + 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<F>(spawn: F)
where
F: Fn(
tokio::runtime::current_thread::Handle,
Box<Future<Item=(), Error=()> + Send>,
),
F: Fn(tokio::runtime::current_thread::Handle, Box<Future<Item = (), Error = ()> + 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<F>(spawn: F)
where
F: Fn(Box<Future<Item=(), Error=()> + Send>) + Send + 'static,
F: Fn(Box<Future<Item = (), Error = ()> + 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<F>(spawn: F)
where
F: Fn(&mut Runtime, Box<Future<Item=(), Error=()> + Send>),
F: Fn(&mut Runtime, Box<Future<Item = (), Error = ()> + 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<F>(spawn: F)
where
F: Fn(Box<Future<Item=(), Error=()> + Send>) + Send + 'static,
F: Fn(Box<Future<Item = (), Error = ()> + 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<F1, F2>(first: F1, nested: F2)
where
F1: Fn(Box<Future<Item=(), Error=()> + Send>) + Send + 'static,
F2: Fn(Box<Future<Item=(), Error=()> + Send>) + panic::UnwindSafe + Send + 'static,
F1: Fn(Box<Future<Item = (), Error = ()> + Send>) + Send + 'static,
F2: Fn(Box<Future<Item = (), Error = ()> + 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();
+12 -15
View File
@@ -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();