Skip to main content

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