broker_tokio/
lib.rs

1#![doc(html_root_url = "https://docs.rs/tokio/0.2.10")]
2#![allow(
3    clippy::cognitive_complexity,
4    clippy::large_enum_variant,
5    clippy::needless_doctest_main
6)]
7#![warn(
8    missing_debug_implementations,
9    missing_docs,
10    rust_2018_idioms,
11    unreachable_pub
12)]
13#![deny(intra_doc_link_resolution_failure)]
14#![doc(test(
15    no_crate_inject,
16    attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
17))]
18#![cfg_attr(docsrs, feature(doc_cfg))]
19
20//! A runtime for writing reliable, asynchronous, and slim applications.
21//!
22//! Tokio is an event-driven, non-blocking I/O platform for writing asynchronous
23//! applications with the Rust programming language. At a high level, it
24//! provides a few major components:
25//!
26//! * Tools for [working with asynchronous tasks][tasks], including
27//!   [synchronization primitives and channels][sync] and [timeouts, delays, and
28//!   intervals][time].
29//! * APIs for [performing asynchronous I/O][io], including [TCP and UDP][net] sockets,
30//!   [filesystem][fs] operations, and [process] and [signal] management.
31//! * A [runtime] for executing asynchronous code, including a task scheduler,
32//!   an I/O driver backed by the operating system's event queue (epoll, kqueue,
33//!   IOCP, etc...), and a high performance timer.
34//!
35//! Guide level documentation is found on the [website].
36//!
37//! [tasks]: #working-with-tasks
38//! [sync]: crate::sync
39//! [time]: crate::time
40//! [io]: #asynchronous-io
41//! [net]: crate::net
42//! [fs]: crate::fs
43//! [process]: crate::process
44//! [signal]: crate::signal
45//! [fs]: crate::fs
46//! [runtime]: crate::runtime
47//! [website]: https://tokio.rs/docs/overview/
48//!
49//! # A Tour of Tokio
50//!
51//! Tokio consists of a number of modules that provide a range of functionality
52//! essential for implementing asynchronous applications in Rust. In this
53//! section, we will take a brief tour of Tokio, summarizing the major APIs and
54//! their uses.
55//!
56//! The easiest way to get started is to enable all features. Do this by
57//! enabling the `full` feature flag:
58//!
59//! ```toml
60//! tokio = { version = "0.2", features = ["full"] }
61//! ```
62//!
63//! ## Feature flags
64//!
65//! Tokio uses a set of [feature flags] to reduce the amount of compiled code. It
66//! is possible to just enable certain features over others. By default, Tokio
67//! does not enable any features but allows one to enable a subset for their use
68//! case. Below is a list of the available feature flags. You may also notice
69//! above each function, struct and trait there is a set of feature flags
70//! that are required for that item to be enabled. If you are new to Tokio it is
71//! recommended that you use the `full` feature flag which will enable everything.
72//! Beware though that this will pull in many extra dependencies that you may not
73//! need.
74//!
75//! - `full`: Enables all Tokio features and every API will be available.
76//! - `rt-core`: Enables `tokio::spawn` and the basic (single-threaded) scheduler.
77//! - `rt-threaded`: Enables the heavier, multi-threaded, work-stealing scheduler.
78//! - `rt-util`: Enables non-scheduler utilities.
79//! - `io-driver`: Enables the `mio` based IO driver.
80//! - `io-util`: Enables the IO based `Ext` traits.
81//! - `io-std`: Enable `Stdout`, `Stdin` and `Stderr` types.
82//! - `net`: Enables `tokio::net` types such as `TcpStream`, `UnixStream` and `UdpSocket`.
83//! - `tcp`: Enables all `tokio::net::tcp` types.
84//! - `udp`: Enables all `tokio::net::udp` types.
85//! - `uds`: Enables all `tokio::net::unix` types.
86//! - `time`: Enables `tokio::time` types and allows the schedulers to enable
87//! the built in timer.
88//! - `process`: Enables `tokio::process` types.
89//! - `macros`: Enables `#[tokio::main]` and `#[tokio::test]` macros.
90//! - `sync`: Enables all `tokio::sync` types.
91//! - `stream`: Enables optional `Stream` implementations for types within Tokio.
92//! - `signal`: Enables all `tokio::signal` types.
93//! - `fs`: Enables `tokio::fs` types.
94//! - `dns`: Enables async `tokio::net::ToSocketAddrs`.
95//! - `test-util`: Enables testing based infrastructure for the Tokio runtime.
96//! - `blocking`: Enables `block_in_place` and `spawn_blocking`.
97//!
98//! _Note: `AsyncRead` and `AsyncWrite` do not require any features and are
99//! enabled by default._
100//!
101//! [feature flags]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section
102//!
103//! ### Authoring applications
104//!
105//! Tokio is great for writing applications and most users in this case shouldn't
106//! worry to much about what features they should pick. If you're unsure, we suggest
107//! going with `full` to ensure that you don't run into any road blocks while you're
108//! building your application.
109//!
110//! #### Example
111//!
112//! This example shows the quickest way to get started with Tokio.
113//!
114//! ```toml
115//! tokio = { version = "0.2", features = ["full"] }
116//! ```
117//!
118//! ### Authoring libraries
119//!
120//! As a library author your goal should be to provide the lighest weight crate
121//! that is based on Tokio. To achieve this you should ensure that you only enable
122//! the features you need. This allows users to pick up your crate without having
123//! to enable unnecessary features.
124//!
125//! #### Example
126//!
127//! This example shows how you may want to import features for a library that just
128//! needs to `tokio::spawn` and use a `TcpStream`.
129//!
130//! ```toml
131//! tokio = { version = "0.2", features = ["rt-core", "tcp"] }
132//! ```
133//!
134//! ## Working With Tasks
135//!
136//! Asynchronous programs in Rust are based around lightweight, non-blocking
137//! units of execution called [_tasks_][tasks]. The [`tokio::task`] module provides
138//! important tools for working with tasks:
139//!
140//! * The [`spawn`] function and [`JoinHandle`] type, for scheduling a new task
141//!   on the Tokio runtime and awaiting the output of a spawned task, respectively,
142//! * Functions for [running blocking operations][blocking] in an asynchronous
143//!   task context.
144//!
145//! The [`tokio::task`] module is present only when the "rt-core" feature flag
146//! is enabled.
147//!
148//! [tasks]: task/index.html#what-are-tasks
149//! [`tokio::task`]: crate::task
150//! [`spawn`]: crate::task::spawn()
151//! [`JoinHandle`]: crate::task::JoinHandle
152//! [blocking]: task/index.html#blocking-and-yielding
153//!
154//! The [`tokio::sync`] module contains synchronization primitives to use when
155//! needing to communicate or share data. These include:
156//!
157//! * channels ([`oneshot`], [`mpsc`], and [`watch`]), for sending values
158//!   between tasks,
159//! * a non-blocking [`Mutex`], for controlling access to a shared, mutable
160//!   value,
161//! * an asynchronous [`Barrier`] type, for multiple tasks to synchronize before
162//!   beginning a computation.
163//!
164//! The `tokio::sync` module is present only when the "sync" feature flag is
165//! enabled.
166//!
167//! [`tokio::sync`]: crate::sync
168//! [`Mutex`]: crate::sync::Mutex
169//! [`Barrier`]: crate::sync::Barrier
170//! [`oneshot`]: crate::sync::oneshot
171//! [`mpsc`]: crate::sync::mpsc
172//! [`watch`]: crate::sync::watch
173//!
174//! The [`tokio::time`] module provides utilities for tracking time and
175//! scheduling work. This includes functions for setting [timeouts][timeout] for
176//! tasks, [delaying][delay] work to run in the future, or [repeating an operation at an
177//! interval][interval].
178//!
179//! In order to use `tokio::time`, the "time" feature flag must be enabled.
180//!
181//! [`tokio::time`]: crate::time
182//! [delay]: crate::time::delay_for()
183//! [interval]: crate::time::interval()
184//! [timeout]: crate::time::timeout()
185//!
186//! Finally, Tokio provides a _runtime_ for executing asynchronous tasks. Most
187//! applications can use the [`#[tokio::main]`][main] macro to run their code on the
188//! Tokio runtime. In use-cases where manual control over the runtime is
189//! required, the [`tokio::runtime`] module provides APIs for configuring and
190//! managing runtimes.
191//!
192//! Using the runtime requires the "rt-core" or "rt-threaded" feature flags, to
193//! enable the basic [single-threaded scheduler][rt-core] and the [thread-pool
194//! scheduler][rt-threaded], respectively. See the [`runtime` module
195//! documentation][rt-features] for details. In addition, the "macros" feature
196//! flag enables the `#[tokio::main]` and `#[tokio::test]` attributes.
197//!
198//! [main]: attr.main.html
199//! [`tokio::runtime`]: crate::runtime
200//! [`Builder`]: crate::runtime::Builder
201//! [`Runtime`]: crate::runtime::Runtime
202//! [rt-core]: runtime/index.html#basic-scheduler
203//! [rt-threaded]: runtime/index.html#threaded-scheduler
204//! [rt-features]: runtime/index.html#runtime-scheduler
205//!
206//! ## Asynchronous IO
207//!
208//! As well as scheduling and running tasks, Tokio provides everything you need
209//! to perform input and output asynchronously.
210//!
211//! The [`tokio::io`] module provides Tokio's asynchronous core I/O primitives,
212//! the [`AsyncRead`], [`AsyncWrite`], and [`AsyncBufRead`] traits. In addition,
213//! when the "io-util" feature flag is enabled, it also provides combinators and
214//! functions for working with these traits, forming as an asynchronous
215//! counterpart to [`std::io`]. When the "io-driver" feature flag is enabled, it
216//! also provides utilities for library authors implementing I/O resources.
217//!
218//! Tokio also includes APIs for performing various kinds of I/O and interacting
219//! with the operating system asynchronously. These include:
220//!
221//! * [`tokio::net`], which contains non-blocking versions of [TCP], [UDP], and
222//!   [Unix Domain Sockets][UDS] (enabled by the "net" feature flag),
223//! * [`tokio::fs`], similar to [`std::fs`] but for performing filesystem I/O
224//!   asynchronously (enabled by the "fs" feature flag),
225//! * [`tokio::signal`], for asynchronously handling Unix and Windows OS signals
226//!   (enabled by the "signal" feature flag),
227//! * [`tokio::process`], for spawning and managing child processes (enabled by
228//!   the "process" feature flag).
229//!
230//! [`tokio::io`]: crate::io
231//! [`AsyncRead`]: crate::io::AsyncRead
232//! [`AsyncWrite`]: crate::io::AsyncWrite
233//! [`AsyncBufRead`]: crate::io::AsyncBufRead
234//! [`std::io`]: std::io
235//! [`tokio::net`]: crate::net
236//! [TCP]: crate::net::tcp
237//! [UDP]: crate::net::udp
238//! [UDS]: crate::net::unix
239//! [`tokio::fs`]: crate::fs
240//! [`std::fs`]: std::fs
241//! [`tokio::signal`]: crate::signal
242//! [`tokio::process`]: crate::process
243//!
244//! # Examples
245//!
246//! A simple TCP echo server:
247//!
248//! ```no_run
249//! use tokio::net::TcpListener;
250//! use tokio::prelude::*;
251//!
252//! #[tokio::main]
253//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
254//!     let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
255//!
256//!     loop {
257//!         let (mut socket, _) = listener.accept().await?;
258//!
259//!         tokio::spawn(async move {
260//!             let mut buf = [0; 1024];
261//!
262//!             // In a loop, read data from the socket and write the data back.
263//!             loop {
264//!                 let n = match socket.read(&mut buf).await {
265//!                     // socket closed
266//!                     Ok(n) if n == 0 => return,
267//!                     Ok(n) => n,
268//!                     Err(e) => {
269//!                         eprintln!("failed to read from socket; err = {:?}", e);
270//!                         return;
271//!                     }
272//!                 };
273//!
274//!                 // Write the data back
275//!                 if let Err(e) = socket.write_all(&buf[0..n]).await {
276//!                     eprintln!("failed to write to socket; err = {:?}", e);
277//!                     return;
278//!                 }
279//!             }
280//!         });
281//!     }
282//! }
283//! ```
284
285// macros used internally
286#[macro_use]
287mod macros;
288
289cfg_fs! {
290    pub mod fs;
291}
292
293mod future;
294
295pub mod io;
296pub mod net;
297
298mod loom;
299mod park;
300
301pub mod prelude;
302
303cfg_process! {
304    pub mod process;
305}
306
307pub mod runtime;
308
309cfg_signal! {
310    pub mod signal;
311}
312
313cfg_stream! {
314    pub mod stream;
315}
316
317cfg_sync! {
318    pub mod sync;
319}
320cfg_not_sync! {
321    mod sync;
322}
323
324cfg_rt_core! {
325    pub mod task;
326    pub use task::spawn;
327}
328
329cfg_time! {
330    pub mod time;
331}
332
333mod util;
334
335cfg_macros! {
336    doc_rt_core! {
337        cfg_rt_threaded! {
338            #[cfg(not(test))] // Work around for rust-lang/rust#62127
339            pub use tokio_macros::main_threaded as main;
340            pub use tokio_macros::test_threaded as test;
341        }
342
343        cfg_not_rt_threaded! {
344            #[cfg(not(test))] // Work around for rust-lang/rust#62127
345            pub use tokio_macros::main_basic as main;
346            pub use tokio_macros::test_basic as test;
347        }
348    }
349
350    // Maintains old behavior
351    cfg_not_rt_core! {
352        #[cfg(not(test))]
353        pub use tokio_macros::main;
354        pub use tokio_macros::test;
355    }
356}
357
358// Tests
359#[cfg(test)]
360mod tests;
361
362// TODO: rm
363#[cfg(feature = "io-util")]
364#[cfg(test)]
365fn is_unpin<T: Unpin>() {}