async_std/lib.rs
1#![allow(rustdoc::invalid_html_tags)]
2//! # Async version of the Rust standard library
3//!
4//! `async-std` is a foundation of portable Rust software, a set of minimal and battle-tested
5//! shared abstractions for the [broader Rust ecosystem][crates.io]. It offers std types, like
6//! [`Future`] and [`Stream`], library-defined [operations on language primitives](#primitives),
7//! [standard macros](#macros), [I/O] and [multithreading], among [many other things][other].
8//!
9//! `async-std` is available from [crates.io]. Once included, `async-std` can be accessed
10//! in [`use`] statements through the path `async_std`, as in [`use async_std::future`].
11//!
12//! [I/O]: io/index.html
13//! [multithreading]: task/index.html
14//! [other]: #what-is-in-the-standard-library-documentation
15//! [`use`]: https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html
16//! [`use async_std::future`]: future/index.html
17//! [crates.io]: https://crates.io
18//! [`Future`]: future/trait.Future.html
19//! [`Stream`]: stream/trait.Stream.html
20//!
21//! # How to read this documentation
22//!
23//! If you already know the name of what you are looking for, the fastest way to
24//! find it is to use the <a href="#" onclick="focusSearchBar();">search
25//! bar</a> at the top of the page.
26//!
27//! Otherwise, you may want to jump to one of these useful sections:
28//!
29//! * [`async_std::*` modules](#modules)
30//! * [Async macros](#macros)
31//! * [The Async Prelude](prelude/index.html)
32//! * [Cargo.toml feature flags](#features)
33//! * [Examples](#examples)
34//!
35//! If this is your first time, the documentation for `async-std` is
36//! written to be casually perused. Clicking on interesting things should
37//! generally lead you to interesting places. Still, there are important bits
38//! you don't want to miss, so read on for a tour of the `async-std` and
39//! its documentation!
40//!
41//! Once you are familiar with the contents of `async-std` you may
42//! begin to find the verbosity of the prose distracting. At this stage in your
43//! development you may want to press the `[-]` button near the top of the
44//! page to collapse it into a more skimmable view.
45//!
46//! While you are looking at that `[-]` button also notice the `[src]`
47//! button. Rust's API documentation comes with the source code and you are
48//! encouraged to read it. The `async-std` source is generally high
49//! quality and a peek behind the curtains is often enlightening.
50//!
51//! Modules in this crate are organized in the same way as in `std`, except blocking
52//! functions have been replaced with async functions and threads have been replaced with
53//! lightweight tasks.
54//!
55//! You can find more information, reading materials, and other resources here:
56//!
57//! * [The async-std website](https://async.rs/)
58//! * [The async-std book](https://book.async.rs)
59//! * [GitHub repository](https://github.com/async-rs/async-std)
60//! * [List of code examples](https://github.com/async-rs/async-std/tree/HEAD/examples)
61//! * [Discord chat](https://discord.gg/JvZeVNe)
62//!
63//! # What is in the `async-std` documentation?
64//!
65//! First, `async-std` is divided into a number of focused
66//! modules, [all listed further down this page](#modules). These modules are
67//! the bedrock upon which async Rust is forged, and they have mighty names
68//! like [`async_std::os`] and [`async_std::task`]. Modules' documentation
69//! typically includes an overview of the module along with examples, and are
70//! a smart place to start familiarizing yourself with the library.
71//!
72//! Second, `async-std` defines [The Async Prelude], a small collection
73//! of items - mostly traits - that should be imported into every module of
74//! every async crate. The traits in the prelude are pervasive, making the
75//! prelude documentation a good entry point to learning about the library.
76//!
77//! [The Async Prelude]: prelude/index.html
78//! [`async_std::os`]: os/index.html
79//! [`async_std::task`]: task/index.html
80//!
81//! And finally, `async-std` exports a number of async macros, and
82//! [lists them on this page](#macros).
83//!
84//! # Contributing changes to the documentation
85//!
86//! Check out `async-std`'s contribution guidelines [here](https://async.rs/contribute).
87//! The source for this documentation can be found on [GitHub](https://github.com/async-rs).
88//! To contribute changes, make sure you read the guidelines first, then submit
89//! pull requests for your suggested changes.
90//!
91//! Contributions are appreciated! If you see a part of the docs that can be
92//! improved, submit a PR, or chat with us first on
93//! [Discord](https://discord.gg/JvZeVNe).
94//!
95//! # A tour of `async-std`
96//!
97//! The rest of this crate documentation is dedicated to pointing out notable
98//! features of `async-std`.
99//!
100//! ## Platform abstractions and I/O
101//!
102//! Besides basic data types, `async-std` is largely concerned with
103//! abstracting over differences in common platforms, most notably Windows and
104//! Unix derivatives.
105//!
106//! Common types of I/O, including [files], [TCP], [UDP], are defined in the
107//! [`io`], [`fs`], and [`net`] modules.
108//!
109//! The [`task`] module contains `async-std`'s task abstractions. [`sync`]
110//! contains further primitive shared memory types. [`channel`] contains the channel types for message passing.
111//!
112//! [files]: fs/struct.File.html
113//! [TCP]: net/struct.TcpStream.html
114//! [UDP]: net/struct.UdpSocket.html
115//! [`io`]: io/index.html
116//! [`sync`]: sync/index.html
117//! [`channel`]: channel/index.html
118//!
119//! ## Timeouts, intervals, and delays
120//!
121//! `async-std` provides several methods to manipulate time:
122//!
123//! * [`task::sleep`] to wait for a duration to pass without blocking.
124//! * [`stream::interval`] for emitting an event at a set interval.
125//! * [`future::timeout`] to time-out futures if they don't resolve within a
126//! set interval.
127//!
128//! [`task::sleep`]: task/fn.sleep.html
129//! [`stream::interval`]: stream/fn.interval.html
130//! [`future::timeout`]: future/fn.timeout.html
131//!
132//! # Examples
133//!
134//! All examples require the [`"attributes"` feature](#features) to be enabled.
135//! This feature is not enabled by default because it significantly impacts
136//! compile times. See [`task::block_on`] for an alternative way to start
137//! executing tasks.
138//!
139//! Call an async function from the main function:
140//!
141#![cfg_attr(feature = "attributes", doc = "```")]
142#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
143//! async fn say_hello() {
144//! println!("Hello, world!");
145//! }
146//!
147//! #[async_std::main]
148//! async fn main() {
149//! say_hello().await;
150//! }
151//! ```
152//!
153//! Await two futures concurrently, and return a tuple of their output:
154//!
155#![cfg_attr(feature = "attributes", doc = "```")]
156#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
157//! use async_std::prelude::*;
158//!
159//! #[async_std::main]
160//! async fn main() {
161//! let a = async { 1u8 };
162//! let b = async { 2u8 };
163//! assert_eq!(a.join(b).await, (1u8, 2u8))
164//! }
165//! ```
166//!
167//! Create a UDP server that echoes back each received message to the sender:
168//!
169#![cfg_attr(feature = "attributes", doc = "```no_run")]
170#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
171//! use async_std::net::UdpSocket;
172//!
173//! #[async_std::main]
174//! async fn main() -> std::io::Result<()> {
175//! let socket = UdpSocket::bind("127.0.0.1:8080").await?;
176//! println!("Listening on {}", socket.local_addr()?);
177//!
178//! let mut buf = vec![0u8; 1024];
179//!
180//! loop {
181//! let (recv, peer) = socket.recv_from(&mut buf).await?;
182//! let sent = socket.send_to(&buf[..recv], &peer).await?;
183//! println!("Sent {} out of {} bytes to {}", sent, recv, peer);
184//! }
185//! }
186//! ```
187//! [`task::block_on`]: task/fn.block_on.html
188//!
189//! # Features
190//!
191//! Items marked with
192//! <span
193//! class="module-item stab portability"
194//! style="display: inline; border-radius: 3px; padding: 2px; font-size: 80%; line-height: 1.2;"
195//! > <code>unstable</code> </span>
196//! are available only when the `unstable` Cargo feature is enabled:
197//!
198//! ```toml
199//! [dependencies.async-std]
200//! version = "1.7.0"
201//! features = ["unstable"]
202//! ```
203//!
204//! Items marked with
205//! <span
206//! class="module-item stab portability"
207//! style="display: inline; border-radius: 3px; padding: 2px; font-size: 80%; line-height: 1.2;"
208//! > <code>attributes</code> </span>
209//! are available only when the `attributes` Cargo feature is enabled:
210//!
211//! ```toml
212//! [dependencies.async-std]
213//! version = "1.7.0"
214//! features = ["attributes"]
215//! ```
216//!
217//! Compatibility with the `tokio` 1.0 runtime is also simultaneously possible
218//! using the `tokio1` Cargo feature:
219//!
220//! ```toml
221//! [dependencies.async-std]
222//! version = "1.7.0"
223//! features = ["tokio1"]
224//! ```
225//!
226//! Compatibility with the `tokio` 0.2 runtime is possible using the `tokio02`
227//! Cargo feature:
228//!
229//! ```toml
230//! [dependencies.async-std]
231//! version = "1.7.0"
232//! features = ["tokio02"]
233//! ```
234//!
235//! Compatibility with the `tokio` 0.3 runtime is also simultaneously possible
236//! using the `tokio03` Cargo feature:
237//!
238//! ```toml
239//! [dependencies.async-std]
240//! version = "1.7.0"
241//! features = ["tokio03"]
242//! ```
243//!
244//! Additionally it's possible to only use the core traits and combinators by
245//! only enabling the `std` Cargo feature:
246//!
247//! ```toml
248//! [dependencies.async-std]
249//! version = "1.7.0"
250//! default-features = false
251//! features = ["std"]
252//! ```
253//!
254//! And to use async-std on `no_std` targets that only support `alloc` only
255//! enable the `alloc` Cargo feature:
256//!
257//! ```toml
258//! [dependencies.async-std]
259//! version = "1.7.0"
260//! default-features = false
261//! features = ["alloc"]
262//! ```
263//!
264//! # Runtime configuration
265//!
266//! Several environment variables are available to tune the async-std
267//! runtime:
268//!
269//! * `ASYNC_STD_THREAD_COUNT`: The number of threads that the
270//! async-std runtime will start. By default, this is one per logical
271//! cpu as determined by [async-global-executor](async_global_executor),
272//! which may be different than the number of physical cpus. Async-std
273//! _will panic_ if this is set to any value other than a positive
274//! integer.
275//! * `ASYNC_STD_THREAD_NAME`: The name that async-std's runtime
276//! threads report to the operating system. The default value is
277//! `"async-std/runtime"`.
278//!
279
280#![cfg_attr(not(feature = "std"), no_std)]
281#![cfg_attr(feature = "docs", feature(doc_cfg))]
282#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
283#![allow(clippy::mutex_atomic, clippy::module_inception)]
284#![doc(test(attr(deny(rust_2018_idioms))))]
285#![doc(test(attr(allow(unused_extern_crates, unused_variables))))]
286#![doc(html_logo_url = "https://async.rs/images/logo--hero.svg")]
287
288#[macro_use]
289mod utils;
290
291#[cfg(feature = "attributes")]
292#[cfg_attr(feature = "docs", doc(cfg(attributes)))]
293#[doc(inline)]
294pub use async_attributes::{main, test};
295
296#[cfg(feature = "std")]
297mod macros;
298
299cfg_alloc! {
300 pub mod task;
301 pub mod future;
302 pub mod stream;
303}
304
305cfg_std! {
306 pub mod io;
307 pub mod os;
308 pub mod prelude;
309 pub mod sync;
310 pub mod channel;
311}
312
313cfg_default! {
314 #[cfg(not(target_os = "unknown"))]
315 pub mod fs;
316 pub mod path;
317 pub mod net;
318 #[cfg(not(target_os = "unknown"))]
319 pub(crate) mod rt;
320}
321
322cfg_unstable! {
323 pub mod pin;
324 #[cfg(all(not(target_os = "unknown"), feature = "std"))]
325 pub mod process;
326
327 mod unit;
328 mod vec;
329 mod result;
330 mod option;
331 mod string;
332 mod collections;
333}
334
335cfg_unstable_default! {
336 #[doc(inline)]
337 pub use std::{write, writeln};
338}