Skip to content

Commit 6d8cc4e

Browse files
authored
tcp: update API documentation (#1392)
1 parent 6cbe3d4 commit 6d8cc4e

File tree

5 files changed

+294
-462
lines changed

5 files changed

+294
-462
lines changed

tokio-io/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ Core I/O primitives for asynchronous I/O in Rust.
2121
categories = ["asynchronous"]
2222
publish = false
2323

24+
[features]
25+
util = ["memchr"]
26+
2427
[dependencies]
2528
bytes = "0.4.7"
2629
log = "0.4"
@@ -32,6 +35,3 @@ pin-utils = "0.1.0-alpha.4"
3235
tokio = { version = "0.2.0", path = "../tokio" }
3336
futures-util-preview = "0.3.0-alpha.17"
3437
tokio-test = { version = "0.2.0", path = "../tokio-test" }
35-
36-
[features]
37-
util = ["memchr"]

tokio-reactor/src/poll_evented.rs

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,33 @@ use tokio_io::{AsyncRead, AsyncWrite};
5252
/// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and
5353
/// [`clear_read_ready`].
5454
///
55-
/// ```rust,ignore
56-
/// pub fn poll_accept(&mut self) -> Poll<(net::TcpStream, SocketAddr), io::Error> {
57-
/// let ready = Ready::readable();
55+
/// ```rust
56+
/// use tokio_reactor::PollEvented;
5857
///
59-
/// try_ready!(self.poll_evented.poll_read_ready(ready));
58+
/// use futures_core::ready;
59+
/// use mio::Ready;
60+
/// use mio::net::{TcpStream, TcpListener};
61+
/// use std::io;
62+
/// use std::task::{Context, Poll};
6063
///
61-
/// match self.poll_evented.get_ref().accept_std() {
62-
/// Ok(pair) => Ok(Async::Ready(pair)),
63-
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
64-
/// self.poll_evented.clear_read_ready(ready);
65-
/// Ok(Async::NotReady)
64+
/// struct MyListener {
65+
/// poll_evented: PollEvented<TcpListener>,
66+
/// }
67+
///
68+
/// impl MyListener {
69+
/// pub fn poll_accept(&mut self, cx: &mut Context<'_>) -> Poll<Result<TcpStream, io::Error>> {
70+
/// let ready = Ready::readable();
71+
///
72+
/// ready!(self.poll_evented.poll_read_ready(cx, ready))?;
73+
///
74+
/// match self.poll_evented.get_ref().accept() {
75+
/// Ok((socket, _)) => Poll::Ready(Ok(socket)),
76+
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
77+
/// self.poll_evented.clear_read_ready(cx, ready);
78+
/// Poll::Pending
79+
/// }
80+
/// Err(e) => Poll::Ready(Err(e)),
6681
/// }
67-
/// Err(e) => Err(e),
6882
/// }
6983
/// }
7084
/// ```
@@ -209,8 +223,8 @@ where
209223
/// `writable`. HUP is always implicitly included on platforms that support
210224
/// it.
211225
///
212-
/// If the resource is not ready for a read then `Async::NotReady` is
213-
/// returned and the current task is notified once a new event is received.
226+
/// If the resource is not ready for a read then `Poll::Pending` is returned
227+
/// and the current task is notified once a new event is received.
214228
///
215229
/// The I/O resource will remain in a read-ready state until readiness is
216230
/// cleared by calling [`clear_read_ready`].
@@ -241,8 +255,8 @@ where
241255
/// Clears the I/O resource's read readiness state and registers the current
242256
/// task to be notified once a read readiness event is received.
243257
///
244-
/// After calling this function, `poll_read_ready` will return `NotReady`
245-
/// until a new read readiness event has been received.
258+
/// After calling this function, `poll_read_ready` will return
259+
/// `Poll::Pending` until a new read readiness event has been received.
246260
///
247261
/// The `mask` argument specifies the readiness bits to clear. This may not
248262
/// include `writable` or `hup`.

tokio-reactor/src/registration.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -263,15 +263,15 @@ impl Registration {
263263
///
264264
/// There are several possible return values:
265265
///
266-
/// * `Ok(Async::Ready(readiness))` means that the I/O resource has received
266+
/// * `Poll::Ready(Ok(readiness))` means that the I/O resource has received
267267
/// a new readiness event. The readiness value is included.
268268
///
269-
/// * `Ok(NotReady)` means that no new readiness events have been received
269+
/// * `Poll::Pending` means that no new readiness events have been received
270270
/// since the last call to `poll_read_ready`.
271271
///
272-
/// * `Err(err)` means that the registration has encountered an error. This
273-
/// error either represents a permanent internal error **or** the fact
274-
/// that [`register`] was not called first.
272+
/// * `Poll::Ready(Err(err))` means that the registration has encountered an
273+
/// error. This error either represents a permanent internal error **or**
274+
/// the fact that [`register`] was not called first.
275275
///
276276
/// [`register`]: #method.register
277277
/// [edge-triggered]: https://docs.rs/mio/0.6/mio/struct.Poll.html#edge-triggered-and-level-triggered
@@ -314,15 +314,15 @@ impl Registration {
314314
///
315315
/// There are several possible return values:
316316
///
317-
/// * `Ok(Async::Ready(readiness))` means that the I/O resource has received
317+
/// * `Poll::Ready(Ok(readiness))` means that the I/O resource has received
318318
/// a new readiness event. The readiness value is included.
319319
///
320-
/// * `Ok(NotReady)` means that no new readiness events have been received
320+
/// * `Poll::Pending` means that no new readiness events have been received
321321
/// since the last call to `poll_write_ready`.
322322
///
323-
/// * `Err(err)` means that the registration has encountered an error. This
324-
/// error either represents a permanent internal error **or** the fact
325-
/// that [`register`] was not called first.
323+
/// * `Poll::Ready(Err(err))` means that the registration has encountered an
324+
/// error. This error either represents a permanent internal error **or**
325+
/// the fact that [`register`] was not called first.
326326
///
327327
/// [`register`]: #method.register
328328
/// [edge-triggered]: https://docs.rs/mio/0.6/mio/struct.Poll.html#edge-triggered-and-level-triggered

tokio-tcp/src/listener.rs

Lines changed: 35 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,22 @@ use tokio_reactor::{Handle, PollEvented};
1818
/// # Examples
1919
///
2020
/// ```no_run
21-
/// use futures::stream::Stream;
22-
/// use std::net::SocketAddr;
23-
/// use tokio::net::{TcpListener, TcpStream};
21+
/// #![feature(async_await)]
2422
///
25-
/// fn process_socket(socket: TcpStream) {
26-
/// // ...
27-
/// }
23+
/// use tokio::net::TcpListener;
24+
/// use std::error::Error;
25+
/// # async fn process_socket<T>(socket: T) {}
2826
///
29-
/// let addr = "127.0.0.1:8080".parse::<SocketAddr>()?;
30-
/// let listener = TcpListener::bind(&addr)?;
27+
/// #[tokio::main]
28+
/// async fn main() -> Result<(), Box<dyn Error>> {
29+
/// let addr = "127.0.0.1:8080".parse()?;
30+
/// let mut listener = TcpListener::bind(&addr)?;
3131
///
32-
/// // accept connections and process them
33-
/// tokio::run(listener.incoming()
34-
/// .map_err(|e| eprintln!("failed to accept socket; error = {:?}", e))
35-
/// .for_each(|socket| {
32+
/// loop {
33+
/// let (socket, _) = listener.accept().await?;
3634
/// process_socket(socket);
37-
/// Ok(())
38-
/// })
39-
/// );
40-
/// # Ok::<_, Box<dyn std::error::Error>>(())
35+
/// }
36+
/// }
4137
/// ```
4238
pub struct TcpListener {
4339
io: PollEvented<mio::net::TcpListener>,
@@ -64,42 +60,38 @@ impl TcpListener {
6460
Ok(TcpListener::new(l))
6561
}
6662

67-
/// Attempt to accept a connection and create a new connected `TcpStream` if
68-
/// successful.
69-
///
70-
/// Note that typically for simple usage it's easier to treat incoming
71-
/// connections as a `Stream` of `TcpStream`s with the `incoming` method
72-
/// below.
73-
///
74-
/// # Return
75-
///
76-
/// On success, returns `Ok(Async::Ready((socket, addr)))`.
77-
///
78-
/// If the listener is not ready to accept, the method returns
79-
/// `Ok(Async::NotReady)` and arranges for the current task to receive a
80-
/// notification when the listener becomes ready to accept.
63+
/// Accept a new incoming connection from this listener.
8164
///
82-
/// # Panics
65+
/// This function will yield once a new TCP connection is established. When
66+
/// established, the corresponding [`TcpStream`] and the remote peer's
67+
/// address will be returned.
8368
///
84-
/// This function will panic if called from outside of a task context.
69+
/// [`TcpStream`]: ../struct.TcpStream.html
8570
///
8671
/// # Examples
8772
///
88-
/// ```no_run
89-
/// use std::net::SocketAddr;
73+
/// ```
74+
/// #![feature(async_await)]
75+
///
76+
/// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
9077
/// use tokio::net::TcpListener;
91-
/// use futures::Async;
9278
///
93-
/// let addr = "127.0.0.1:0".parse::<SocketAddr>()?;
79+
/// let addr = "127.0.0.1:8080".parse()?;
9480
/// let mut listener = TcpListener::bind(&addr)?;
95-
/// match listener.poll_accept() {
96-
/// Ok(Async::Ready((_socket, addr))) => println!("listener ready to accept: {:?}", addr),
97-
/// Ok(Async::NotReady) => println!("listener not ready to accept!"),
98-
/// Err(e) => eprintln!("got an error: {}", e),
81+
/// match listener.accept().await {
82+
/// Ok((_socket, addr)) => println!("new client: {:?}", addr),
83+
/// Err(e) => println!("couldn't get client: {:?}", e),
9984
/// }
100-
/// # Ok::<_, Box<dyn std::error::Error>>(())
85+
/// # Ok(())
86+
/// # }
10187
/// ```
102-
pub fn poll_accept(
88+
#[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988
89+
pub async fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> {
90+
use async_util::future::poll_fn;
91+
poll_fn(|cx| self.poll_accept(cx)).await
92+
}
93+
94+
pub(crate) fn poll_accept(
10395
&mut self,
10496
cx: &mut Context<'_>,
10597
) -> Poll<io::Result<(TcpStream, SocketAddr)>> {
@@ -111,62 +103,7 @@ impl TcpListener {
111103
Poll::Ready(Ok((io, addr)))
112104
}
113105

114-
/// Accept a new incoming connection from this listener.
115-
///
116-
/// This function will yield once a new TCP connection is established. When
117-
/// established, the corresponding [`TcpStream`] and the remote peer's
118-
/// address will be returned.
119-
///
120-
/// [`TcpStream`]: ../struct.TcpStream.html
121-
///
122-
/// # Examples
123-
///
124-
/// ```
125-
/// unimplemented!();
126-
/// ```
127-
#[allow(clippy::needless_lifetimes)] // false positive: https://github.com/rust-lang/rust-clippy/issues/3988
128-
pub async fn accept(&mut self) -> io::Result<(TcpStream, SocketAddr)> {
129-
use async_util::future::poll_fn;
130-
poll_fn(|cx| self.poll_accept(cx)).await
131-
}
132-
133-
/// Attempt to accept a connection and create a new connected `TcpStream` if
134-
/// successful.
135-
///
136-
/// This function is the same as `accept` above except that it returns a
137-
/// `std::net::TcpStream` instead of a `tokio::net::TcpStream`. This in turn
138-
/// can then allow for the TCP stream to be associated with a different
139-
/// reactor than the one this `TcpListener` is associated with.
140-
///
141-
/// # Return
142-
///
143-
/// On success, returns `Ok(Async::Ready((socket, addr)))`.
144-
///
145-
/// If the listener is not ready to accept, the method returns
146-
/// `Ok(Async::NotReady)` and arranges for the current task to receive a
147-
/// notification when the listener becomes ready to accept.
148-
///
149-
/// # Panics
150-
///
151-
/// This function will panic if called from outside of a task context.
152-
///
153-
/// # Examples
154-
///
155-
/// ```no_run
156-
/// use std::net::SocketAddr;
157-
/// use tokio::net::TcpListener;
158-
/// use futures::Async;
159-
///
160-
/// let addr = "127.0.0.1:0".parse::<SocketAddr>()?;
161-
/// let mut listener = TcpListener::bind(&addr)?;
162-
/// match listener.poll_accept_std() {
163-
/// Ok(Async::Ready((_socket, addr))) => println!("listener ready to accept: {:?}", addr),
164-
/// Ok(Async::NotReady) => println!("listener not ready to accept!"),
165-
/// Err(e) => eprintln!("got an error: {}", e),
166-
/// }
167-
/// # Ok::<_, Box<dyn std::error::Error>>(())
168-
/// ```
169-
pub fn poll_accept_std(
106+
fn poll_accept_std(
170107
&mut self,
171108
cx: &mut Context<'_>,
172109
) -> Poll<io::Result<(net::TcpStream, SocketAddr)>> {
@@ -267,28 +204,6 @@ impl TcpListener {
267204
/// necessarily fatal ‒ for example having too many open file descriptors or the other side
268205
/// closing the connection while it waits in an accept queue. These would terminate the stream
269206
/// if not handled in any way.
270-
///
271-
/// If aiming for production, decision what to do about them must be made. The
272-
/// [`tk-listen`](https://crates.io/crates/tk-listen) crate might be of some help.
273-
///
274-
/// # Examples
275-
///
276-
/// ```
277-
/// use tokio::net::TcpListener;
278-
/// use futures::stream::Stream;
279-
/// use std::net::SocketAddr;
280-
///
281-
/// let addr = "127.0.0.1:0".parse::<SocketAddr>()?;
282-
/// let listener = TcpListener::bind(&addr)?;
283-
///
284-
/// listener.incoming()
285-
/// .map_err(|e| eprintln!("failed to accept stream; error = {:?}", e))
286-
/// .for_each(|_socket| {
287-
/// println!("new socket!");
288-
/// Ok(())
289-
/// });
290-
/// # Ok::<_, Box<dyn std::error::Error>>(())
291-
/// ```
292207
#[cfg(feature = "async-traits")]
293208
pub fn incoming(self) -> Incoming {
294209
Incoming::new(self)

0 commit comments

Comments
 (0)