mio/
lib.rs

1#![deny(
2    missing_docs,
3    missing_debug_implementations,
4    rust_2018_idioms,
5    unused_imports,
6    dead_code
7)]
8#![cfg_attr(docsrs, feature(doc_cfg))]
9// Disallow warnings when running tests.
10#![cfg_attr(test, deny(warnings))]
11// Disallow warnings in examples.
12#![doc(test(attr(deny(warnings))))]
13
14//! Mio is a fast, low-level I/O library for Rust focusing on non-blocking APIs
15//! and event notification for building high performance I/O apps with as little
16//! overhead as possible over the OS abstractions.
17//!
18//! # Usage
19//!
20//! Using Mio starts by creating a [`Poll`], which reads events from the OS and
21//! puts them into [`Events`]. You can handle I/O events from the OS with it.
22//!
23//! For more detail, see [`Poll`].
24//!
25//! [`Poll`]: ../mio/struct.Poll.html
26//! [`Events`]: ../mio/event/struct.Events.html
27//!
28//! ## Examples
29//!
30//! Examples can found in the `examples` directory of the source code, or [on
31//! GitHub].
32//!
33//! [on GitHub]: https://github.com/tokio-rs/mio/tree/master/examples
34//!
35//! ## Guide
36//!
37//! A getting started guide is available in the [`guide`] module.
38//!
39//! ## Available features
40//!
41//! The available features are described in the [`features`] module.
42
43#[cfg(all(target_family = "wasm", not(target_os = "wasi")))]
44compile_error!("This wasm target is unsupported by mio. If using Tokio, disable the net feature.");
45
46// macros used internally
47#[macro_use]
48mod macros;
49
50mod interest;
51mod poll;
52mod sys;
53mod token;
54#[cfg(not(target_os = "wasi"))]
55mod waker;
56
57pub mod event;
58
59cfg_io_source! {
60    mod io_source;
61}
62
63cfg_net! {
64    pub mod net;
65}
66
67#[doc(no_inline)]
68pub use event::Events;
69pub use interest::Interest;
70pub use poll::{Poll, Registry};
71pub use token::Token;
72#[cfg(not(target_os = "wasi"))]
73pub use waker::Waker;
74
75#[cfg(all(unix, feature = "os-ext"))]
76#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "os-ext"))))]
77pub mod unix {
78    //! Unix only extensions.
79
80    pub mod pipe {
81        //! Unix pipe.
82        //!
83        //! See the [`new`] function for documentation.
84
85        pub use crate::sys::pipe::{new, Receiver, Sender};
86    }
87
88    pub use crate::sys::SourceFd;
89}
90
91#[cfg(all(target_os = "hermit", feature = "os-ext"))]
92#[cfg_attr(docsrs, doc(cfg(all(target_os = "hermit", feature = "os-ext"))))]
93pub mod hermit {
94    //! Hermit only extensions.
95
96    pub use crate::sys::SourceFd;
97}
98
99#[cfg(all(windows, feature = "os-ext"))]
100#[cfg_attr(docsrs, doc(cfg(all(windows, feature = "os-ext"))))]
101pub mod windows {
102    //! Windows only extensions.
103
104    pub use crate::sys::named_pipe::NamedPipe;
105}
106
107pub mod features {
108    //! # Mio's optional features.
109    //!
110    //! This document describes the available features in Mio.
111    //!
112    #![cfg_attr(feature = "os-poll", doc = "## `os-poll` (enabled)")]
113    #![cfg_attr(not(feature = "os-poll"), doc = "## `os-poll` (disabled)")]
114    //!
115    //! Mio by default provides only a shell implementation that `panic!`s the
116    //! moment it is actually run. To run it requires OS support, this is
117    //! enabled by activating the `os-poll` feature.
118    //!
119    //! This makes `Poll`, `Registry` and `Waker` functional.
120    //!
121    #![cfg_attr(feature = "os-ext", doc = "## `os-ext` (enabled)")]
122    #![cfg_attr(not(feature = "os-ext"), doc = "## `os-ext` (disabled)")]
123    //!
124    //! `os-ext` enables additional OS specific facilities. These facilities can
125    //! be found in the `unix` and `windows` module.
126    //!
127    #![cfg_attr(feature = "net", doc = "## Network types (enabled)")]
128    #![cfg_attr(not(feature = "net"), doc = "## Network types (disabled)")]
129    //!
130    //! The `net` feature enables networking primitives in the `net` module.
131}
132
133pub mod guide {
134    //! # Getting started guide.
135    //!
136    //! In this guide we'll do the following:
137    //!
138    //! 1. Create a [`Poll`] instance (and learn what it is).
139    //! 2. Register an [event source].
140    //! 3. Create an event loop.
141    //!
142    //! At the end you'll have a very small (but quick) TCP server that accepts
143    //! connections and then drops (disconnects) them.
144    //!
145    //! ## 1. Creating a `Poll` instance
146    //!
147    //! Using Mio starts by creating a [`Poll`] instance, which monitors events
148    //! from the OS and puts them into [`Events`]. This allows us to execute I/O
149    //! operations based on what operations are ready.
150    //!
151    //! [`Poll`]: ../struct.Poll.html
152    //! [`Events`]: ../event/struct.Events.html
153    //!
154    #![cfg_attr(feature = "os-poll", doc = "```")]
155    #![cfg_attr(not(feature = "os-poll"), doc = "```ignore")]
156    //! # use mio::{Poll, Events};
157    //! # fn main() -> std::io::Result<()> {
158    //! // `Poll` allows for polling of readiness events.
159    //! let poll = Poll::new()?;
160    //! // `Events` is collection of readiness `Event`s and can be filled by
161    //! // calling `Poll::poll`.
162    //! let events = Events::with_capacity(128);
163    //! # drop((poll, events));
164    //! # Ok(())
165    //! # }
166    //! ```
167    //!
168    //! For example if we're using a [`TcpListener`],  we'll only want to
169    //! attempt to accept an incoming connection *iff* any connections are
170    //! queued and ready to be accepted. We don't want to waste our time if no
171    //! connections are ready.
172    //!
173    //! [`TcpListener`]: ../net/struct.TcpListener.html
174    //!
175    //! ## 2. Registering event source
176    //!
177    //! After we've created a [`Poll`] instance that monitors events from the OS
178    //! for us, we need to provide it with a source of events. This is done by
179    //! registering an [event source]. As the name “event source” suggests it is
180    //! a source of events which can be polled using a `Poll` instance. On Unix
181    //! systems this is usually a file descriptor, or a socket/handle on
182    //! Windows.
183    //!
184    //! In the example below we'll use a [`TcpListener`] for which we'll receive
185    //! an event (from [`Poll`]) once a connection is ready to be accepted.
186    //!
187    //! [event source]: ../event/trait.Source.html
188    //!
189    #![cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
190    #![cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
191    //! # use mio::net::TcpListener;
192    //! # use mio::{Poll, Token, Interest};
193    //! # fn main() -> std::io::Result<()> {
194    //! # let poll = Poll::new()?;
195    //! # let address = "127.0.0.1:0".parse().unwrap();
196    //! // Create a `TcpListener`, binding it to `address`.
197    //! let mut listener = TcpListener::bind(address)?;
198    //!
199    //! // Next we register it with `Poll` to receive events for it. The `SERVER`
200    //! // `Token` is used to determine that we received an event for the listener
201    //! // later on.
202    //! const SERVER: Token = Token(0);
203    //! poll.registry().register(&mut listener, SERVER, Interest::READABLE)?;
204    //! # Ok(())
205    //! # }
206    //! ```
207    //!
208    //! Multiple event sources can be [registered] (concurrently), so we can
209    //! monitor multiple sources at a time.
210    //!
211    //! [registered]: ../struct.Registry.html#method.register
212    //!
213    //! ## 3. Creating the event loop
214    //!
215    //! After we've created a [`Poll`] instance and registered one or more
216    //! [event sources] with it, we can [poll] it for events. Polling for events
217    //! is simple, we need a container to store the events: [`Events`] and need
218    //! to do something based on the polled events (this part is up to you, we
219    //! can't do it all!). If we do this in a loop we've got ourselves an event
220    //! loop.
221    //!
222    //! The example below shows the event loop in action, completing our small
223    //! TCP server.
224    //!
225    //! [poll]: ../struct.Poll.html#method.poll
226    //! [event sources]: ../event/trait.Source.html
227    //!
228    #![cfg_attr(all(feature = "os-poll", feature = "net"), doc = "```")]
229    #![cfg_attr(not(all(feature = "os-poll", feature = "net")), doc = "```ignore")]
230    //! # use std::io;
231    //! # use std::time::Duration;
232    //! # use mio::net::TcpListener;
233    //! # use mio::{Poll, Token, Interest, Events};
234    //! # fn main() -> io::Result<()> {
235    //! # let mut poll = Poll::new()?;
236    //! # let mut events = Events::with_capacity(128);
237    //! # let address = "127.0.0.1:0".parse().unwrap();
238    //! # let mut listener = TcpListener::bind(address)?;
239    //! # const SERVER: Token = Token(0);
240    //! # poll.registry().register(&mut listener, SERVER, Interest::READABLE)?;
241    //! // Start our event loop.
242    //! loop {
243    //!     // Poll the OS for events, waiting at most 100 milliseconds.
244    //!     poll.poll(&mut events, Some(Duration::from_millis(100)))?;
245    //!
246    //!     // Process each event.
247    //!     for event in events.iter() {
248    //!         // We can use the token we previously provided to `register` to
249    //!         // determine for which type the event is.
250    //!         match event.token() {
251    //!             SERVER => loop {
252    //!                 // One or more connections are ready, so we'll attempt to
253    //!                 // accept them (in a loop).
254    //!                 match listener.accept() {
255    //!                     Ok((connection, address)) => {
256    //!                         println!("Got a connection from: {}", address);
257    //! #                       drop(connection);
258    //!                     },
259    //!                     // A "would block error" is returned if the operation
260    //!                     // is not ready, so we'll stop trying to accept
261    //!                     // connections.
262    //!                     Err(ref err) if would_block(err) => break,
263    //!                     Err(err) => return Err(err),
264    //!                 }
265    //!             }
266    //! #           _ => unreachable!(),
267    //!         }
268    //!     }
269    //! #   return Ok(());
270    //! }
271    //!
272    //! fn would_block(err: &io::Error) -> bool {
273    //!     err.kind() == io::ErrorKind::WouldBlock
274    //! }
275    //! # }
276    //! ```
277}