Merge branch 'master' into tyler_elastic_threadpool

pull/3/head
Stjepan Glavina 5 years ago committed by GitHub
commit ea2da1f4a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,7 +1,10 @@
language: rust
env:
- RUSTFLAGS="-D warnings"
before_script:
- rustup component add rustfmt
- rustup component add rustfmt
matrix:
fast_finish: true
@ -10,11 +13,11 @@ matrix:
os: linux
- rust: nightly
os: osx
- rust: nightly-x86_64-pc-windows-msvc
os: windows
# - rust: nightly-x86_64-pc-windows-msvc
# os: windows
script:
- cargo fmt --all -- --check
- cargo check --all --benches --bins --examples --tests
- cargo test --all
- cargo doc --features docs.rs
- cargo fmt --all -- --check
- cargo doc --features docs

@ -19,9 +19,9 @@ rustdoc-args = ["--features docs"]
docs = []
[dependencies]
async-task = { path = "../async-task" }
async-task = { git = "ssh://git@github.com/async-rs/async-task.git" }
cfg-if = "0.1.9"
crossbeam = "0.7.1"
crossbeam-channel = "0.3.9"
futures-preview = "0.3.0-alpha.17"
futures-timer = "0.3.0"
lazy_static = "1.3.0"

1
docs/.gitignore vendored

@ -0,0 +1 @@
book

@ -0,0 +1,6 @@
[book]
authors = ["The async-std maintainers"]
language = "en"
multilingual = false
src = "src"
title = "Async programming in Rust with async-std"

@ -0,0 +1,23 @@
# Summary
- [Overview](./overview.md)
- [`async-std`](./overview/async-std.md)
- [`std::future` and `futures-rs`](./overview/std-and-library-futures.md)
- [Stability guarantees](./overview/stability-guarantees.md)
- [Async concepts using async-std](./concepts.md)
- [Futures](./concepts/futures.md)
- [Tasks](./concepts/tasks.md)
- [Async read/write](./concepts/async-read-write.md)
- [Streams and Channels](./concepts/streams.md)
- [Tutorials](./tutorials/index.md)
- [Integrating std::thread](./tutorials/integrating-std-thread.md)
- [Async Patterns](./patterns.md)
- [Fork/Join](./patterns/fork-join.md)
- [Accepting requests](./patterns/accepting-concurrent-requests.md)
- [Proper Shutdown](./patterns/proper-shutdown.md)
- [Background Tasks](./patterns/background-tasks.md)
- [Testing](./patterns/testing.md)
- [Collected Small Patterns](./patterns/small-patterns.md)
- [Security practices](./security/index.md)
- [Security disclosures and policy](./security/policy.md)
- [Glossary](./glossary.md)

@ -0,0 +1,15 @@
# Async concepts using async-std
[Rust Futures][futures] have the reputation of being hard. We don't think this is the case. They are, in our opinion, one of the easiest concurrency concepts around and have an intuitive explanation.
However, there are good reasons for that perception. Futures have three concepts at their base that seem to be a constant source of confusion: deferred computation, asynchronicity and independence of execution strategy.
These concepts are not hard, but something many people are not used to. This base confusion is amplified by many implementations oriented on details and hard to understand. Most explanations of these implementations also target advanced users. We both try to provide easy to understand primitives and approachable overviews of the concepts.
Futures are a concept that abstracts over how code is run. By themselves, they do nothing. This is a weird concept in an imperative language, where usually one thing happens after the other - right now.
So how do Futures run? You decide! Futures do nothing without the piece of code _executing_ them. This part is called an _executor_. An _executor_ decides _when_ and _how_ to execute your futures. The `async-std::task` module provides you with and interface to such an executor.
Let's start with a little bit of motivation, though.
[futures]: https://en.wikipedia.org/wiki/Futures_and_promises

@ -0,0 +1,118 @@
# Futures
A notable point about Rust is [*fearless concurrency*](https://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html). That is the notion that you should be empowered to do concurrent things, without giving up safety. Also, Rust being a low-level language, it's about fearless concurrency *without picking a specific implementation strategy*. This means we *must* abstract over the strategy, to allow choice *later*, if we want to have any way to share code between users of different strategies.
Futures abstract over *computation*. They describe the "what", independent of the "where" and the "when". For that, they aim to break code into small, composable actions that can then be executed by a part of our system. Let's take a tour through what it means to compute things to find where we can abstract.
## Send and Sync
Luckily, concurrent Rust already has two well-known and effective concepts abstracting over sharing between Rust concurrent parts of a program: Send and Sync. Notably, both the Send and Sync traits abstract over *strategies* of concurrent work, compose neatly, and don't prescribe an implementation.
As a quick summary, `Send` abstracts over passing data in a computation over to another concurrent computation (let's call it the receiver), losing access to it on the sender side. In many programming languages, this strategy is commonly implemented, but missing support from the language side expects you to keep up this behaviour yourself. This is a regular source of bugs: senders keeping handles to sent things around and maybe even working with them after sending. Rust mitigates this problem by making this behaviour known. Types can be `Send` or not (by implementing the appropriate marker trait), allowing or disallowing sending them around.
Note how we avoided any word like *"thread"*, but instead opted for "computation". The full power of `Send` (and subsequently also `Sync`) is that they relieve you of the burden of knowing *what* shares. At the point of implementation, you only need to know which method of sharing is appropriate for the type at hand. This keeps reasoning local and is not influenced by whatever implementation the user of that type later uses.
`Sync` is about sharing data between two concurrent parts of a program. This is another common pattern: as writing to a memory location or reading while another party is writing is inherently unsafe, this access needs to be moderated through synchronisation.[^1] There are many common ways of two parties to agree on not using the same part in memory at the same time, for example mutexes and spinlocks. Again, Rust gives you the option of (safely!) not caring. Rust gives you the ability to express that something *needs* synchronisation while not being specific about the *how*.
`Send` and `Sync` can be composed in interesting fashions, but that's beyond the scope here. You can find examples in the [Rust Book][rust-book-sync].
To sum up: Rust gives us the ability to safely abstract over important properties of concurrent programs: their data sharing. It does so in a very lightweight fashion: the language itself only knows about the two markers `Send` and `Sync` and helps us a little by deriving them itself, when possible. The rest is a library concern.
## An easy view of computation
While computation is a subject to write a whole [book](https://computationbook.com/) about, a very simplified view of them suffices for us:
- computation is a sequence of composable operations
- they can branch based on a decision
- they either run to succession and yield a result or they can yield an error
## Deferring computation
As mentioned above `Send` and `Sync` are about data. But programs are not only about data, they also talk about *computing* the data. And that's what \[Futures\][futures] do. We are going to have a close look at how that works in the next chapter. Let's look at what Futures allow us to express, in English. Futures go from this plan:
- Do X
- If X succeeds, do Y
towards
- Start doing X
- Once X succeeds, start doing Y
Remember the talk about "deferred computation" in the intro? That's all it is. Instead of telling the computer what to execute and decide upon *now*, you tell it what to start doing and how to react on potential events the... well... `Future`.
## Orienting towards the beginning
Let's have a look at a simple function, specifically the return value:
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
contents
}
You can call that at any time, so you are in full control on when you call it. But here's the problem: the moment you call it, you transfer control to the called function. It returns a value.
Note that this return value talks about the past. The past has a drawback: all decisions have been made. It has an advantage: the outcome is visible. We can unwrap the presents of program past and then decide what to do with it.
But here's a problem: we wanted to abstract over *computation* to be allowed to let someone else choose how to run it. That's fundamentally incompatible with looking at the results of previous computation all the time. So, let's find a type that describes a computation without running it. Let's look at the function again:
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
contents
}
Speaking in terms of time, we can only take action *before* calling the function or *after* the function returned. This is not desirable, as it takes from us the ability to do something *while* it runs. When working with parallel code, this would take from us the ability to start a parallel task while the first runs (because we gave away control).
This is the moment where we could reach for [threads](https://en.wikipedia.org/wiki/Thread_). But threads are a very specific concurrency primitive and we said that we are searching for an abstraction.
What we are searching is something that represents ongoing work towards a result in the future. Whenever we say `something` in Rust, we almost always mean a trait. Let's start with an incomplete definition of the `Future` trait:
trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output>;
}
Ignore `Pin` and `Context` for now, you don't need them for high-level understanding. Looking at it closely, we see the following: it is generic over the `Output`. It provides a function called `poll`, which allows us to check on the state of the current computation.
Every call to `poll()` can result in one of these two cases:
1. The future is done, `poll` will return `[Poll::Ready](https://doc.rust-lang.org/std/task/enum.Poll.html#variant.Ready)`
2. The future has not finished executing, it will return `[Poll::Pending](https://doc.rust-lang.org/std/task/enum.Poll.html#variant.Pending)`
This allows us to externally check if a `Future` has finished doing its work, or is finally done and can give us the value. The most simple way (but not efficient) would be to just constantly poll futures in a loop. There's optimistions here, and this is what a good runtime is does for you.
Note that calling `poll` after case 1 happened may result in confusing behaviour. See the [futures-docs](https://doc.rust-lang.org/std/future/trait.Future.html) for details.
## Async
While the `Future` trait has existed in Rust for a while, it was inconvenient to build and describe them. For this, Rust now has a special syntax: `async`. The example from above, implemented in `async-std`, would look like this:
use async_std::fs::File;
async fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
contents
}
Amazingly little difference, right? All we did is label the function `async` and insert 2 special commands: `.await`.
This function sets up a deferred computation. When this function is called, it will produce a `Future<Output=String>` instead of immediately returning a String. (Or, more precisely, generate a type for you that implements `Future<Output=String>`.)
## What does `.await` do?
The `.await` postfix does exactly what it says on the tin: the moment you use it, the code will wait until the requested action (e.g. opening a file or reading all data in it) is finished. `.await?` is not special, its just the application of the `?` operator to the result of `.await`. So, what is gained over the initial code example? Were getting futures and then immediately waiting for them?
The `.await` points act as a marker. Here, the code will wait for a `Future` to produce its value. How will a future finish? You dont need to care! The marker allows the code later *executing* this piece of code (usually called the “runtime”) when it can take some time to care about all the other things it has to do. It will come back to this point when the operation you are doing in the background is done. This is why this style of programming is also called *evented programming*. We are waiting for *things to happen* (e.g. a file to be opened) and then react (by starting to read).
When executing 2 or more of these functions at the same time, our runtime system is then able to fill the wait time with handling *all the other events* currently going on.
## Conclusion
Working from values, we searched for something that expresses *working towards a value available sometime later*. From there, we talked about the concept of polling.
A `Future` is any data type that does not represent a value, but the ability to *produce a value at some point in the future*. Implementations of this are very varied and detailled depending on use-case, but the interface is simple.
Next, we will introduce you to `tasks`, which we need to actually *run* Futures.
[^1]: Two parties reading while it is guaranteed that no one is writing is always safe.

@ -0,0 +1,83 @@
# Tasks
Now that we know what Futures are, we now want to run them!
In `async-std`, the `tasks` (TODO: link) module is responsible for this. The simplest way is using the `block_on` function:
```rust
use async_std::fs::File;
use async_std::task;
async fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File.open(path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
contents
}
fn main() {
let task = task::spawn(async {
let result = read_file("data.csv");
match result {
Ok(s) => println!("{}", s),
Err(e) => println!("Error reading file: {:?}", e)
}
});
println!("Started task!");
task::block_on(task);
println!("Stopped task!");
}
```
This asks the runtime baked into `async_std` to execute the code that reads a file. Lets go one by one, though, inside to outside.
```rust
async {
let result = read_file("data.csv");
match result {
Ok(s) => println!("{}", s),
Err(e) => println!("Error reading file: {:?}", e)
}
}
```
This is an `async` *block*. Async blocks are necessary to call `async` functions, and will instruct the compiler to include all the relevant instructions to do so. In Rust, all blocks return a value and `async` blocks happen to return a value of the kind `Future`.
But lets get to the interesting part:
```rust
task::spawn(async { })
```
`spawn` takes a Future and starts running it on a `Task`. It returns a `JoinHandle`. Futures in Rust are sometimes called *cold* Futures. You need something that starts running them. To run a Future, there may be some additional bookkeeping required, e.g. if its running or finished, where it is being placed in memory and what the current state is. This bookkeeping part is abstracted away in a `Task`. A `Task` is similar to a `Thread`, with some minor differences: it will be scheduled by the program instead of the operating system kernel and if it encounters a point where it needs to wait, the program itself responsible for waking it up again. Well talk a little bit about that later. An `async_std` task can also has a name and an ID, just like a thread.
For now, it is enough to know that once you `spawn`ed a task, it will continue running in the background. The `JoinHandle` in itself is a future that will finish once the `Task` ran to conclusion. Much like with `threads` and the `join` function, we can now call `block_on` on the handle to *block* the program (or the calling thread, to be specific) to wait for it to finish.
## Tasks in `async_std`
Tasks in `async_std` are one of the core abstractions. Much like Rusts `thread`s, they provide some practical functionality over the raw concept. `Tasks` have a relationship to the runtime, but they are in themselves separate. `async_std` tasks have a number of desirable properties:
- They are single-allocated
- All tasks have a *backchannel*, which allows them to propagate results and errors to the spawning task through the `JoinHandle`
- The carry desirable metadata for debugging
- They support task local storage
`async_std` s task api handles setup and teardown of a backing runtime for you and doesnt rely on a runtime being started.
## Blocking
TODO: fill me in
## Errors and panics
TODO: fill me in
## Conclusion
`async_std` comes with a useful `Task` type that works with an API similar to `std::thread`. It covers error and panic behaviour in a structured and defined way.
Tasks are separate concurrent units and sometimes they need to communicate. Thats where `Stream`s come in.

@ -0,0 +1,7 @@
# Glossary
### blocking
"blocked" generally refers to conditions that keep a task from doing its work. For example, it might need data to be sent by a client before continuing. When tasks becomes blocked, usually, other tasks are scheduled.
Sometimes you hear that you should never call "blocking functions" in an async context. What this refers to is functions that block the current thread and do not yield control back. This keeps the executor from using this thread to schedule another task.

@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="645"
height="157"
fill="none"
version="1.1"
id="svg13"
sodipodi:docname="horizontal_color.svg"
inkscape:export-filename="/home/anxhelo/works/async-std/PNG/horizontal_color.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
inkscape:version="0.92.4 (unknown)">
<metadata
id="metadata17">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1366"
inkscape:window-height="717"
id="namedview15"
showgrid="false"
inkscape:zoom="0.53937447"
inkscape:cx="277.57355"
inkscape:cy="86.621231"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg13" />
<path
fill-rule="evenodd"
d="M28.82 17.165a3.54 3.54 0 0 1 4.096-.657l11.462 5.786c5.67-3.453 11.9-6.08 18.52-7.71l4-12.15A3.54 3.54 0 0 1 70.259 0H86.74a3.54 3.54 0 0 1 3.361 2.432l3.943 11.98c6.77 1.59 13.14 4.215 18.936 7.702l11.104-5.605a3.54 3.54 0 0 1 4.096.657l11.655 11.655a3.54 3.54 0 0 1 .656 4.096l-5.462 10.82c3.72 5.917 6.532 12.464 8.24 19.443l11.3 3.72A3.54 3.54 0 0 1 157 70.259V86.74a3.54 3.54 0 0 1-2.432 3.361l-11.045 3.635a65.94 65.94 0 0 1-8.216 20.075l5.185 10.272a3.54 3.54 0 0 1-.656 4.096l-11.655 11.655a3.54 3.54 0 0 1-4.096.657l-10.216-5.157a65.96 65.96 0 0 1-20.178 8.328l-3.59 10.905A3.54 3.54 0 0 1 86.741 157H70.26a3.54 3.54 0 0 1-3.361-2.432l-3.644-11.072c-7.1-1.708-13.754-4.558-19.76-8.344l-10.58 5.34a3.54 3.54 0 0 1-4.096-.657L17.165 128.18a3.54 3.54 0 0 1-.657-4.096l5.482-10.86a65.92 65.92 0 0 1-7.803-19.252l-11.756-3.87A3.54 3.54 0 0 1 0 86.741V70.26a3.54 3.54 0 0 1 2.432-3.361l12.014-3.954c1.656-6.664 4.32-12.93 7.82-18.626L16.51 32.915a3.54 3.54 0 0 1 .657-4.096L28.82 17.165zm15.275 100.06c3.73 3.698 8.102 6.356 12.755 7.976-9.23-12.134-8.305-29.524 2.776-40.604s28.47-12.005 40.604-2.776a33.91 33.91 0 0 0-8.081-12.86c-13.3-13.3-34.86-13.3-48.16 0-13.264 13.263-13.3 34.746-.106 48.053l.106.106.106.105zm48.09-.143a15.04 15.04 0 0 0-21.303-21.227 15.04 15.04 0 0 0 21.227 21.303l.076-.076zm11.22-59.38c17.3 17.3 19.265 44.13 5.892 63.595a50.17 50.17 0 0 0 4.741-4.178c19.343-19.344 19.343-50.706 0-70.05s-50.706-19.344-70.05 0a50 50 0 0 0-4.178 4.74c19.464-13.373 46.294-11.41 63.595 5.892z"
fill="url(#A)"
id="path2" />
<path
d="M215.985 113.357c-4.846 0-8.9-1.293-12.127-3.88S199 103.12 199 98.167c0-3.792.914-6.73 2.743-8.812 1.85-2.104 4.24-3.628 7.17-4.57 2.953-.965 6.07-1.622 9.352-1.973 4.472-.482 7.678-.932 9.616-1.348 1.96-.416 2.94-1.48 2.94-3.2v-.197c0-2.477-.738-4.395-2.214-5.754s-3.602-2.038-6.377-2.038c-2.93 0-5.255.636-6.973 1.907-1.696 1.27-2.842 2.773-3.437 4.505l-11.17-1.578c1.322-4.603 3.9-8.078 7.733-10.423 3.855-2.345 8.448-3.518 13.78-3.518 2.423 0 4.846.285 7.27.855s4.638 1.512 6.642 2.828c2.027 1.315 3.646 3.1 4.858 5.327 1.234 2.236 1.85 5.02 1.85 8.352v33.8h-11.5v-6.94h-.397c-1.08 2.126-2.84 4-5.287 5.6-2.423 1.578-5.628 2.367-9.616 2.367zm3.106-8.746c3.613 0 6.477-1.03 8.592-3.1s3.172-4.493 3.172-7.3v-5.95c-.506.416-1.443.8-2.808 1.118-1.344.307-2.776.57-4.296.8l-3.867.56c-2.665.373-4.9 1.107-6.675 2.203-1.784 1.074-2.676 2.75-2.676 5.03 0 2.192.804 3.847 2.412 4.965s3.657 1.677 6.146 1.677zm75.84-29.427l-10.905 1.184c-.463-1.666-1.454-3.135-2.974-4.406-1.498-1.27-3.624-1.907-6.378-1.907-2.5 0-4.582.537-6.28 1.6-1.674 1.074-2.5 2.466-2.478 4.176a4.45 4.45 0 0 0 1.619 3.617c1.124.92 2.974 1.666 5.552 2.236l8.658 1.84c9.495 2.06 14.253 6.62 14.275 13.678 0 3.18-.925 5.984-2.776 8.417-1.85 2.412-4.406 4.297-7.666 5.656s-7.006 2.038-11.235 2.038c-6.235 0-11.236-1.304-15.003-3.912s-6.025-6.226-6.774-10.85l11.665-1.118c1.035 4.603 4.395 6.905 10.08 6.905 2.84 0 5.122-.57 6.84-1.7 1.74-1.16 2.6-2.608 2.6-4.34 0-2.828-2.28-4.746-6.84-5.754l-8.658-1.808c-4.868-1.008-8.47-2.707-10.805-5.096-2.336-2.4-3.492-5.458-3.47-9.14 0-3.113.86-5.8 2.577-8.1 1.72-2.302 4.12-4.077 7.204-5.326 3.084-1.27 6.664-1.907 10.74-1.907 5.948 0 10.63 1.27 14.044 3.814 3.437 2.52 5.563 5.918 6.378 10.193zM312.9 132c-1.74 0-3.26-.153-4.56-.46s-2.3-.603-2.974-.888l2.776-9.535c2.622.745 4.814.877 6.576.394 1.784-.482 3.238-2.115 4.362-4.9l1.2-3.222-18.406-51.555h12.7l11.698 38.14h.528l11.73-38.14h12.723l-20.488 57.08c-1.4 3.967-3.58 7.135-6.5 9.502-2.93 2.4-6.708 3.584-11.334 3.584zm58.562-49.254v29.592H359.5V61.835h11.433v8.582h.595c1.167-2.806 3.03-5.042 5.585-6.708 2.577-1.688 5.76-2.532 9.55-2.532 5.243 0 9.45 1.655 12.623 4.965 3.194 3.3 4.78 8 4.758 14.04v32.157h-11.962V82.023c0-3.376-.88-6.017-2.644-7.924-1.74-1.907-4.152-2.86-7.237-2.86-3.15 0-5.727 1.008-7.732 3.025-2.005 1.995-3.007 4.822-3.007 8.483zm66.883 30.578c-5.045 0-9.385-1.107-13.02-3.32s-6.433-5.282-8.393-9.206c-1.94-3.924-2.908-8.428-2.908-13.514 0-5.15 1-9.678 2.974-13.58 1.982-3.924 4.78-6.992 8.393-9.206 3.635-2.214 7.93-3.32 12.888-3.32 4.14 0 7.798.756 10.97 2.27 3.172 1.5 5.706 3.595 7.6 6.313s2.974 5.907 3.24 9.568h-11.434c-.463-2.433-1.564-4.46-3.305-6.083-1.718-1.644-4.02-2.466-6.906-2.466-3.68 0-6.653 1.447-8.922 4.34-2.247 2.87-3.37 6.86-3.37 11.968 0 5.15 1.113 9.195 3.338 12.133 2.247 2.937 5.232 4.406 8.955 4.406 2.622 0 4.847-.746 6.675-2.236 1.85-1.5 3.03-3.595 3.536-6.313H460.1c-.287 3.573-1.344 6.73-3.173 9.47s-4.318 4.888-7.468 6.445-6.85 2.334-11.103 2.334zm62.33-33.932V89.2H470.2v-9.798h30.467zm52.698-4.208l-10.904 1.184c-.463-1.666-1.454-3.135-2.974-4.406-1.498-1.27-3.624-1.907-6.378-1.907-2.5 0-4.582.537-6.28 1.6-1.674 1.074-2.5 2.466-2.478 4.176a4.45 4.45 0 0 0 1.619 3.617c1.124.92 2.974 1.666 5.552 2.236l8.658 1.84c9.494 2.06 14.253 6.62 14.275 13.678 0 3.18-.925 5.984-2.776 8.417-1.85 2.412-4.406 4.297-7.666 5.656s-7.006 2.038-11.236 2.038c-6.234 0-11.235-1.304-15.002-3.912s-6.025-6.226-6.774-10.85l11.665-1.118c1.035 4.603 4.395 6.905 10.078 6.905 2.842 0 5.122-.57 6.84-1.7 1.74-1.16 2.6-2.608 2.6-4.34 0-2.828-2.28-4.746-6.84-5.754l-8.658-1.808c-4.868-1.008-8.47-2.707-10.806-5.096-2.335-2.4-3.5-5.458-3.47-9.14 0-3.113.86-5.8 2.577-8.1 1.72-2.302 4.12-4.077 7.204-5.326 3.084-1.27 6.664-1.907 10.74-1.907 5.948 0 10.63 1.27 14.044 3.814 3.437 2.52 5.562 5.918 6.377 10.193zm36.3-13.35v9.206h-10.012v26.107c0 2.4.528 3.968 1.586 4.735 1.057.745 2.335 1.118 3.833 1.118.75 0 1.432-.055 2.05-.164l1.454-.296 2.016 9.305c-.64.22-1.553.46-2.743.723-1.168.263-2.6.416-4.296.46-4.494.132-8.272-.964-11.334-3.288-3.04-2.323-4.55-5.863-4.528-10.62V71.04h-7.203v-9.206h7.203v-12.1h11.963v12.1h10.012zm28.296 51.39c-3.987 0-7.556-1.02-10.706-3.058s-5.64-4.998-7.47-8.878-2.742-8.592-2.742-14.138c0-5.6.925-10.346 2.775-14.204 1.873-3.858 4.395-6.784 7.568-8.78s6.708-2.992 10.607-2.992c2.996 0 5.442.504 7.336 1.512 1.917.986 3.437 2.18 4.56 3.584 1.146 1.38 2.016 2.685 2.6 3.913h.496V45H645v67.338h-11.764v-7.957h-.727c-.617 1.227-1.5 2.532-2.677 3.913-1.167 1.36-2.7 2.52-4.626 3.485s-4.33 1.447-7.237 1.447zm3.338-9.766c3.8 0 6.752-1.5 8.823-4.504 2.07-3.025 3.106-6.98 3.106-11.87 0-4.9-1.024-8.823-3.073-11.738-2.05-2.937-5-4.406-8.856-4.406-3.988 0-6.995 1.512-9.022 4.537s-3.04 6.894-3.04 11.607c0 4.735 1.025 8.647 3.074 11.738s5.044 4.636 8.988 4.636z"
fill="#623871"
id="path4" />
<defs
id="defs11">
<linearGradient
id="A"
x1="4.998"
y1="5.29"
x2="146.855"
y2="147.953"
gradientUnits="userSpaceOnUse">
<stop
stop-color="#a047bf"
id="stop6" />
<stop
offset="1"
stop-color="#ee7e40"
id="stop8" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 8.1 KiB

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
width="469.01221"
height="469.01218"
version="1.1"
id="svg13"
sodipodi:docname="icon_color.svg"
inkscape:export-filename="/home/anxhelo/works/async-std/PNG/icon_color.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
style="fill:none"
inkscape:version="0.92.4 (unknown)">
<metadata
id="metadata17">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1366"
inkscape:window-height="717"
id="namedview15"
showgrid="false"
inkscape:zoom="0.53937447"
inkscape:cx="66.57329"
inkscape:cy="291.22962"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg13"
fit-margin-top="0"
fit-margin-left="0"
fit-margin-right="0"
fit-margin-bottom="0" />
<path
d="M 86.095104,51.277669 A 10.575179,10.575179 0 0 1 98.331245,49.314986 L 132.57212,66.59973 C 149.51034,56.284449 168.12148,48.436707 187.89765,43.567346 L 199.84697,7.271181 A 10.575179,10.575179 0 0 1 209.88744,0 h 49.23435 a 10.575179,10.575179 0 0 1 10.04045,7.265207 l 11.77908,35.788319 c 20.22425,4.749868 39.25361,12.591632 56.56825,23.008483 l 33.17138,-16.744035 a 10.575179,10.575179 0 0 1 12.23615,1.962681 l 34.81743,34.817435 a 10.575179,10.575179 0 0 1 1.95969,12.236139 l -16.31686,32.323011 c 11.11293,17.67608 19.51331,37.23418 24.61569,58.08281 l 33.75691,11.11291 a 10.575179,10.575179 0 0 1 7.26225,10.03447 v 49.23431 a 10.575179,10.575179 0 0 1 -7.26524,10.04045 l -32.99516,10.85899 a 196.98511,196.98511 0 0 1 -24.54397,59.97083 l 15.48937,30.68594 a 10.575179,10.575179 0 0 1 -1.95969,12.23614 l -34.81743,34.81742 a 10.575179,10.575179 0 0 1 -12.23617,1.96269 l -30.51863,-15.40572 a 197.04486,197.04486 0 0 1 -60.27851,24.87856 l -10.72455,32.57692 a 10.575179,10.575179 0 0 1 -10.03747,7.26821 h -49.23434 a 10.575179,10.575179 0 0 1 -10.04045,-7.26522 l -10.88586,-33.07581 c -21.2101,-5.10234 -41.08784,-13.61629 -59.0298,-24.92634 L 98.328261,419.69717 A 10.575179,10.575179 0 0 1 86.092106,417.73451 L 51.277691,382.91708 A 10.575179,10.575179 0 0 1 49.314997,370.68091 L 65.691571,338.23844 A 196.92537,196.92537 0 0 1 42.381367,280.72618 L 7.262224,269.16518 A 10.575179,10.575179 0 0 1 0,259.12475 V 209.89041 A 10.575179,10.575179 0 0 1 7.265222,199.84998 L 43.15511,188.03803 C 48.102142,168.13041 56.060396,149.41175 66.5161,132.39586 L 49.320974,98.328257 A 10.575179,10.575179 0 0 1 51.283667,86.092115 Z M 131.7267,350.19076 c 11.14277,11.0472 24.20343,18.98754 38.10349,23.82703 -27.57312,-36.24836 -24.80983,-88.19816 8.29289,-121.2979 33.10268,-33.09971 85.04954,-35.863 121.29791,-8.29284 a 101.30066,101.30066 0 0 0 -24.14072,-38.41718 c -39.7316,-39.73161 -104.1386,-39.73161 -143.87021,0 -39.624078,39.62107 -39.731608,103.79807 -0.31666,143.55059 l 0.31666,0.31663 z m 143.66113,-0.42716 a 44.929576,44.929576 0 0 0 -63.63929,-63.41226 44.929576,44.929576 0 0 0 63.41226,63.6393 z m 33.51796,-177.38818 c 51.68097,51.68096 57.55107,131.83126 17.60139,189.9798 a 149.87478,149.87478 0 0 0 14.16297,-12.4811 c 57.78409,-57.78709 57.78409,-151.47599 0,-209.26307 -57.7841,-57.787083 -151.476,-57.787083 -209.26309,0 a 149.36693,149.36693 0 0 0 -12.48111,14.15999 c 58.14557,-39.94969 138.29588,-34.08554 189.97984,17.60139 z"
id="path2"
style="fill:url(#A);fill-rule:evenodd;stroke-width:2.98733878"
inkscape:connector-curvature="0" />
<defs
id="defs11">
<linearGradient
id="A"
x1="4.9980001"
y1="5.29"
x2="146.855"
y2="147.953"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(2.9873387,0,0,2.9873387,4e-6,0)">
<stop
stop-color="#a047bf"
id="stop6" />
<stop
offset="1"
stop-color="#ee7e40"
id="stop8" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

@ -0,0 +1,10 @@
# Overview
![async-std logo](./images/horizontal_color.svg)
`async-std` along with its [supporting libraries][organization] is a library making your life in async programming easier. It provides provide fundamental implementations for downstream libraries and applications alike. The name reflects the approach of this library: it is a closely modeled to the Rust main standard library as possible, replacing all components by async counterparts.
`async-std` provides an interface to all important primitives: filesystem operations, network operations and concurrency basics like timers. It also exposes an `task` in a model similar to the `thread` module found in the Rust standard lib. But it does not only include io primitives, but also `async/await` compatible versions of primitives like `Mutex`. You can read more about `async-std` in [the overview chapter][overview-std].
[organization]: https://github.com/async-std/async-std
[overview-std]: overview/async-std/

@ -0,0 +1,40 @@
# Stability and SemVer
`async-std` follows https://semver.org/.
In short: we are versioning our software as `MAJOR.MINOR.PATCH`. We increase the:
* MAJOR version when there are incompatible API changes,
* MINOR version when we introducece functionality in a backwards-compatible manner
* PATCH version when we make backwards-compatible bug fixes
We will provide migration documentation between major versions.
## Future expectations
`async-std` uses its own implementations of the following concepts:
* `Read`
* `Write`
* `Seek`
* `BufRead`
* `Stream`
For integration with the ecosystem, all types implementing these traits also have an implementation of the corresponding interfaces in the `futures-rs` library.
Please note that our SemVer guarantees don't extend to usage of those interfaces. We expect those to be conservatively updated and in lockstep.
## Minimum version policy
The current tentative policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if `async-std` 1.0 requires Rust 1.37.0, then `async-std` 1.0.z for all values of z will also require Rust 1.37.0 or newer. However, `async-std` 1.y for y > 0 may require a newer minimum version of Rust.
In general, this crate will be conservative with respect to the minimum supported version of Rust. With `async/await` being a new feature though, we will track changes in a measured pace initially.
## Security fixes
Security fixes will be applied to _all_ minor branches of this library in all _supported_ major revisions. This policy might change in the future, in which case we give at least _3 month_ of ahead notice.
## Credits
This policy is based on [burntsushis regex crate][regex-policy].
[regex-policy]: https://github.com/rust-lang/regex#minimum-rust-version-policy

@ -0,0 +1,27 @@
# `std::future` and `futures-rs`
Rust has two kinds of types commonly referred to as `Future`:
- the first is `std::future::Future` from Rusts [standard library](https://doc.rust-lang.org/std/future/trait.Future.html).
- the second is `futures::future::Future` from the [futures-rs crate](https://docs.rs/futures-preview/0.3.0-alpha.17/futures/prelude/trait.Future.html), currently released as `futures-preview`.
The future defined in the [futures-rs](https://docs.rs/futures-preview/0.3.0-alpha.17/futures/prelude/trait.Future.html) crate was the original implementation of the type. To enable the `async/await` syntax, the core Future trait was moved into Rusts standard library and became `std::future::Future`. In some sense, the `std``::future::Future` can be seen as a minimal subset of `futures::future::Future`.
It is critical to understand the difference between `std::future::Future` and `futures::future::Future`, and the approach that `async-std` takes towards them. In itself, `std::future::Future` is not something you want to interact with as a user—except by calling `.await` on it. The inner workings of `std::future::Future` are mostly of interest to people implementing `Future`. Make no mistake—this is very useful! Most of the functionality that used to be defined on `Future` itself has been moved to an extension trait called `[FuturesExt](https://docs.rs/futures-preview/0.3.0-alpha.17/futures/future/trait.FutureExt.html)`. From this information, you might be able to infer that the `futures` library serves as an extension to the core Rust async features.
In the same tradition as `futures`, `async-std` re-exports the core `std::future::``Future` type. You can get actively opt into the extensions provided by the `futures-preview` crate by adding it your `Cargo.toml` and importing `FuturesExt`.
## Interfaces and Stability
`async-std` aims to be a stable and reliable library, at the level of the Rust standard library. This also means that we don't rely on the `futures` library for our interface. Yet, we appreciate that many users have come to like the conveniences that `futures-rs` brings. For that reason, `async-std` implements all `futures` traits for its types.
Luckily, the approach from above gives you full flexibility. If you care about stability a lot, you can just use `async-std` as is. If you prefer the `futures` library interfaces, you link those in.. Both uses are first class.
## `async_std::future`
Theres some support functions that we see as important for working with futures of any kind. These can be found in the `async_std::future` module and are covered by our stability guarantees.
## Streams and Read/Write/Seek/BufRead traits
Due to limitations of the Rust compiler, those are currently implemented in `async_std`, but cannot be implemented by users themselves.

@ -0,0 +1,5 @@
# Patterns
This section documents small, useful patterns.
It is intended to be read at a glance, allowing you to get back when you have a problem.

@ -0,0 +1,16 @@
# Small Patterns
A collection of small, useful patterns.
## Splitting streams
`async-std` doesn't provide a `split()` method on `io` handles. Instead, splitting a stream into a read and write half can be done like this:
```rust
use async_std::io;
async fn echo(stream: io::TcpStream) {
let (reader, writer) = &mut (&stream, &stream);
io::copy(reader, writer).await?;
}
```

@ -0,0 +1,12 @@
# Security
Writing a highly perfomant async core library is a task involving some instances of unsafe code.
We take great care in vetting all unsafe code included in `async-std` and do follow generally accepted practices.
In the case that you find a security-related bug in our library, please get in touch with our [security contact][security-policy].
Patches improving the resilience of the library or the testing setup are happily accepted on our [github org][github].
[security-policies]: /security/policy
[github]: https://github.com/async-std/

@ -0,0 +1,37 @@
# Policy
Safety is one of the core principles of what we do, and to that end, we would like to ensure that async-std has a secure implementation. Thank you for taking the time to responsibly disclose any issues you find.
All security bugs in async-std distribution should be reported by email to security@ferrous-systems.com. This list is delivered to a small security team. Your email will be acknowledged within 24 hours, and youll receive a more detailed response to your email within 48 hours indicating the next steps in handling your report. If you would like, you can encrypt your report using our public key. This key is also On MITs keyserver and reproduced below.
Be sure to use a descriptive subject line to avoid having your report be missed. After the initial reply to your report, the security team will endeavor to keep you informed of the progress being made towards a fix and full announcement. As recommended by [RFPolicy][rf-policy], these updates will be sent at least every five days. In reality, this is more likely to be every 24-48 hours.
If you have not received a reply to your email within 48 hours, or have not heard from the security team for the past five days, there are a few steps you can take (in order):
* Contact the current security coordinator TODO directly.
* Contact the back-up contact TODO directly.
* Post on our Community forums
Please note that the discussion forums are public areas. When escalating in these venues, please do not discuss your issue. Simply say that youre trying to get a hold of someone from the security team.
[rf-policy]: https://en.wikipedia.org/wiki/RFPolicy
## Disclosure policy
The async-std project has a 5 step disclosure process.
* The security report is received and is assigned a primary handler. This person will coordinate the fix and release process.
* The problem is confirmed and a list of all affected versions is determined.
* Code is audited to find any potential similar problems.
* Fixes are prepared for all releases which are still under maintenance. These fixes are not committed to the public repository but rather held locally pending the announcement.
* On the embargo date, the changes are pushed to the public repository and new builds are deployed to crates.io. Within 6 hours, a copy of the advisory will be published on the the async.rs blog.
This process can take some time, especially when coordination is required with maintainers of other projects. Every effort will be made to handle the bug in as timely a manner as possible, however its important that we follow the release process above to ensure that the disclosure is handled in a consistent manner.
## Credits
This policy is adapted from the [Rust project](https://www.rust-lang.org/policies/security) security policy.
## PGP Key
TODO

@ -0,0 +1,43 @@
# Exercise: Waiting for `std::thread`
Parallel processing is usually done via [threads].
In `async-std`, we have similar concept, called a [`task`].
These two worlds seem different - and in some regards, they are - though they
are easy to connect.
In this exercise, you will learn how to connect to concurrent/parallel components easily, by connecting a thread to a task.
## Understanding the problem
The standard thread API in Rust is `std::thread`. Specifically, it contains the [`spawn`] function, which allows us to start a thread:
```rust
std::thread::spawn(|| {
println!("in child thread");
})
println!("in parent thread");
```
This creates a thread, _immediately_ [schedules] it to run, and continues. This is crucial: once the thread is spawned, it is independent of its _parent thread_. If you want to wait for the thread to end, you need to capture its [`JoinHandle`] and join it with your current thread:
```rust
let thread = std::thread::spawn(|| {
println!("in child thread");
})
thread.join();
println!("in parent thread");
```
This comes at a cost though: the waiting thread will [block] until the child is done. Wouldn't it be nice if we could just use the `.await` syntax here and leave the opportunity for another task to be scheduled while waiting?
## Backchannels
[threads]: TODO: wikipedia
[`task`]: TODO: docs link
[`spawn`]: TODO: docs link
[`JoinHandle`]: TODO: docs link
[schedules]: TODO: Glossary link
[block]: TODO: Link to blocking

@ -13,9 +13,8 @@ fn main() -> io::Result<()> {
let path = args().nth(1).expect("missing path argument");
task::block_on(async {
let file = BufReader::new(File::open(&path).await?);
let mut lines = file.lines();
let file = File::open(&path).await?;
let mut lines = BufReader::new(file).lines();
let mut count = 0u64;
while let Some(line) = lines.next().await {

@ -4,7 +4,10 @@
use std::env::args;
use async_std::{fs, io, prelude::*, task};
use async_std::fs;
use async_std::io;
use async_std::prelude::*;
use async_std::task;
fn main() -> io::Result<()> {
let path = args().nth(1).expect("missing path argument");

@ -4,7 +4,10 @@
use std::env::args;
use async_std::{fs::File, io, prelude::*, task};
use async_std::fs::File;
use async_std::io;
use async_std::prelude::*;
use async_std::task;
const LEN: usize = 4 * 1024 * 1024; // 4 Mb

@ -2,7 +2,9 @@
#![feature(async_await)]
use async_std::{io, prelude::*, task};
use async_std::io;
use async_std::prelude::*;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {

@ -4,7 +4,9 @@
use std::time::Duration;
use async_std::{io, prelude::*, task};
use async_std::io;
use async_std::prelude::*;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {

@ -4,7 +4,8 @@
use std::cell::Cell;
use async_std::{task, task_local};
use async_std::prelude::*;
use async_std::task;
task_local! {
static VAR: Cell<i32> = Cell::new(1);

@ -14,7 +14,10 @@
#![feature(async_await)]
use async_std::{io, net::TcpStream, prelude::*, task};
use async_std::io;
use async_std::net::TcpStream;
use async_std::prelude::*;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {

@ -8,8 +8,10 @@
#![feature(async_await)]
use async_std::io;
use async_std::net::{TcpListener, TcpStream};
use async_std::{io, prelude::*, task};
use async_std::prelude::*;
use async_std::task;
async fn process(stream: TcpStream) -> io::Result<()> {
println!("Accepted from: {}", stream.peer_addr()?);

@ -14,7 +14,9 @@
#![feature(async_await)]
use async_std::{io, net::UdpSocket, task};
use async_std::io;
use async_std::net::UdpSocket;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {

@ -8,7 +8,9 @@
#![feature(async_await)]
use async_std::{io, net::UdpSocket, task};
use async_std::io;
use async_std::net::UdpSocket;
use async_std::task;
fn main() -> io::Result<()> {
task::block_on(async {

@ -77,7 +77,8 @@ impl DirEntry {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
/// use async_std::fs;
/// use async_std::prelude::*;
///
/// let mut dir = fs::read_dir(".").await?;
///
@ -102,7 +103,8 @@ impl DirEntry {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
/// use async_std::fs;
/// use async_std::prelude::*;
///
/// let mut dir = fs::read_dir(".").await?;
///
@ -155,7 +157,8 @@ impl DirEntry {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
/// use async_std::fs;
/// use async_std::prelude::*;
///
/// let mut dir = fs::read_dir(".").await?;
///
@ -206,7 +209,8 @@ impl DirEntry {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
/// use async_std::fs;
/// use async_std::prelude::*;
///
/// let mut dir = fs::read_dir(".").await?;
///

@ -338,9 +338,8 @@ impl File {
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut file = File::create("a.txt").await?;
/// let file = File::create("a.txt").await?;
/// file.set_len(10).await?;
/// #
/// # Ok(()) }) }
@ -438,9 +437,9 @@ impl File {
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut file = File::create("a.txt").await?;
/// let file = File::create("a.txt").await?;
///
/// let mut perms = file.metadata().await?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms).await?;

@ -1,5 +1,4 @@
use std::fs;
use std::path::Path;
use std::pin::Pin;
use std::sync::Mutex;
@ -34,7 +33,8 @@ use crate::task::{blocking, Context, Poll};
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
/// use async_std::fs;
/// use async_std::prelude::*;
///
/// let mut dir = fs::read_dir(".").await?;
///

@ -21,12 +21,13 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_to_string;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let contents = read_to_string("a.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let contents = fs::read_to_string("a.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
let path = path.as_ref().to_owned();

@ -27,7 +27,6 @@ use crate::task::blocking;
///
/// let mut perm = fs::metadata("a.txt").await?.permissions();
/// perm.set_readonly(true);
///
/// fs::set_permissions("a.txt", perm).await?;
/// #
/// # Ok(()) }) }

@ -5,9 +5,10 @@
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use std::time::Duration;
///
/// use async_std::future::pending;
/// use async_std::prelude::*;
/// use std::time::Duration;
///
/// let dur = Duration::from_secs(1);
/// assert!(pending::<()>().timeout(dur).await.is_err());

@ -1,4 +1,3 @@
use std::io;
use std::mem;
use std::pin::Pin;
use std::str;
@ -7,6 +6,7 @@ use cfg_if::cfg_if;
use futures::io::AsyncBufRead;
use crate::future::Future;
use crate::io;
use crate::task::{Context, Poll};
cfg_if! {
@ -49,12 +49,14 @@ pub trait BufRead {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, io::BufReader, prelude::*};
/// use async_std::fs::File;
/// use async_std::io::BufReader;
/// use async_std::prelude::*;
///
/// let mut f = BufReader::new(File::open("a.txt").await?);
/// let mut file = BufReader::new(File::open("a.txt").await?);
///
/// let mut buf = vec![0; 1024];
/// let n = f.read_until(b'\n', &mut buf).await?;
/// let n = file.read_until(b'\n', &mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
@ -98,12 +100,14 @@ pub trait BufRead {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, io::BufReader, prelude::*};
/// use async_std::fs::File;
/// use async_std::io::BufReader;
/// use async_std::prelude::*;
///
/// let mut f = BufReader::new(File::open("a.txt").await?);
/// let mut file = BufReader::new(File::open("a.txt").await?);
///
/// let mut buf = String::new();
/// f.read_line(&mut buf).await?;
/// file.read_line(&mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
@ -137,11 +141,12 @@ pub trait BufRead {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, io::BufReader, prelude::*};
/// use async_std::fs::File;
/// use async_std::io::BufReader;
/// use async_std::prelude::*;
///
/// let mut f = BufReader::new(File::open("a.txt").await?);
///
/// let mut lines = f.lines();
/// let file = File::open("a.txt").await?;
/// let mut lines = BufReader::new(file).lines();
/// let mut count = 0;
///
/// for line in lines.next().await {

@ -1,10 +1,10 @@
use std::io::{IoSliceMut, Read as _, SeekFrom};
use std::io::{IoSliceMut, Read as _};
use std::pin::Pin;
use std::{cmp, fmt};
use futures::io::{AsyncBufRead, AsyncRead, AsyncSeek, Initializer};
use crate::io;
use crate::io::{self, SeekFrom};
use crate::task::{Context, Poll};
const DEFAULT_CAPACITY: usize = 8 * 1024;

@ -31,7 +31,7 @@ use crate::io;
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, task};
/// use async_std::io;
///
/// let mut reader: &[u8] = b"hello";
/// let mut writer = io::stdout();

@ -55,7 +55,8 @@ pub trait Read {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::open("a.txt").await?;
///
@ -104,7 +105,8 @@ pub trait Read {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::open("a.txt").await?;
///
@ -141,7 +143,8 @@ pub trait Read {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::open("a.txt").await?;
///
@ -193,7 +196,8 @@ pub trait Read {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::open("a.txt").await?;
///

@ -1,11 +1,10 @@
use std::io::SeekFrom;
use std::pin::Pin;
use cfg_if::cfg_if;
use futures::io::AsyncSeek;
use crate::future::Future;
use crate::io;
use crate::io::{self, SeekFrom};
use crate::task::{Context, Poll};
cfg_if! {
@ -47,7 +46,9 @@ pub trait Seek {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, io::SeekFrom, prelude::*};
/// use async_std::fs::File;
/// use async_std::io::SeekFrom;
/// use async_std::prelude::*;
///
/// let mut f = File::open("a.txt").await?;
///

@ -19,7 +19,8 @@ use crate::task::{blocking, Context, Poll};
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
/// use async_std::io;
/// use async_std::prelude::*;
///
/// let mut stderr = io::stderr();
/// stderr.write_all(b"Hello, world!").await?;

@ -93,14 +93,15 @@ impl Stdin {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::io::stdin;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::io;
///
/// # futures::executor::block_on(async {
/// let stdin = stdin();
/// let stdin = io::stdin();
/// let mut line = String::new();
/// stdin.read_line(&mut line).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn read_line(&self, buf: &mut String) -> io::Result<usize> {
future::poll_fn(|cx| {

@ -19,7 +19,8 @@ use crate::task::{blocking, Context, Poll};
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
/// use async_std::io;
/// use async_std::prelude::*;
///
/// let mut stdout = io::stdout();
/// stdout.write_all(b"Hello, world!").await?;

@ -50,7 +50,8 @@ pub trait Write {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::create("a.txt").await?;
///
@ -70,7 +71,8 @@ pub trait Write {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::create("a.txt").await?;
///
@ -115,7 +117,8 @@ pub trait Write {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs::File, prelude::*};
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// let mut f = File::create("a.txt").await?;
///

@ -22,6 +22,8 @@
#![feature(async_await)]
#![cfg_attr(feature = "docs", feature(doc_cfg))]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#![doc(test(attr(deny(rust_2018_idioms, warnings))))]
#![doc(test(attr(allow(unused_extern_crates, unused_variables))))]
#![doc(html_logo_url = "https://async.rs/images/logo--hero.svg")]
pub mod fs;

@ -26,7 +26,7 @@
//! socket.send_to(&buf[..n], &peer).await?;
//! }
//! #
//! # Ok(()) }) }
//! # }) }
//! ```
pub use tcp::{Incoming, TcpListener, TcpStream};

@ -33,7 +33,9 @@ use crate::task::{Context, Poll};
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, net::TcpListener, prelude::*};
/// use async_std::io;
/// use async_std::net::TcpListener;
/// use async_std::prelude::*;
///
/// let listener = TcpListener::bind("127.0.0.1:8080").await?;
/// let mut incoming = listener.incoming();
@ -173,7 +175,8 @@ impl TcpListener {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{net::TcpListener, prelude::*};
/// use async_std::net::TcpListener;
/// use async_std::prelude::*;
///
/// let listener = TcpListener::bind("127.0.0.1:0").await?;
/// let mut incoming = listener.incoming();

@ -36,7 +36,8 @@ use crate::task::{Context, Poll};
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{net::TcpStream, prelude::*};
/// use async_std::net::TcpStream;
/// use async_std::prelude::*;
///
/// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.write_all(b"hello world").await?;
@ -340,9 +341,10 @@ impl TcpStream {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
/// use std::net::Shutdown;
///
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.shutdown(Shutdown::Both)?;
/// #

@ -42,7 +42,7 @@ use crate::task::Poll;
/// socket.send_to(&buf[..n], &peer).await?;
/// }
/// #
/// # Ok(()) }) }
/// # }) }
/// ```
#[derive(Debug)]
pub struct UdpSocket {
@ -118,7 +118,6 @@ impl UdpSocket {
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::IpAddr;
///
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
/// let addr = socket.local_addr()?;
@ -446,9 +445,10 @@ impl UdpSocket {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::Ipv4Addr;
///
/// use async_std::net::UdpSocket;
///
/// let interface = Ipv4Addr::new(0, 0, 0, 0);
/// let mdns_addr = Ipv4Addr::new(224, 0, 0, 123);
///
@ -475,9 +475,10 @@ impl UdpSocket {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::{Ipv6Addr, SocketAddr};
///
/// use async_std::net::UdpSocket;
///
/// let socket_addr = SocketAddr::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).into(), 0);
/// let mdns_addr = Ipv6Addr::new(0xFF02, 0, 0, 0, 0, 0, 0, 0x0123) ;
/// let socket = UdpSocket::bind(&socket_addr).await?;

@ -181,7 +181,7 @@ impl UnixDatagram {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// let mut socket = UnixDatagram::unbound()?;
/// let socket = UnixDatagram::unbound()?;
/// socket.connect("/tmp/socket").await?;
/// let peer = socket.peer_addr()?;
/// #
@ -203,7 +203,7 @@ impl UnixDatagram {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// let mut socket = UnixDatagram::unbound()?;
/// let socket = UnixDatagram::unbound()?;
/// let mut buf = vec![0; 1024];
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// #
@ -271,7 +271,7 @@ impl UnixDatagram {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// let mut socket = UnixDatagram::unbound()?;
/// let socket = UnixDatagram::unbound()?;
/// socket.send_to(b"hello world", "/tmp/socket").await?;
/// #
/// # Ok(()) }) }
@ -304,7 +304,7 @@ impl UnixDatagram {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// let mut socket = UnixDatagram::unbound()?;
/// let socket = UnixDatagram::unbound()?;
/// socket.connect("/tmp/socket").await?;
/// socket.send(b"hello world").await?;
/// #

@ -65,9 +65,10 @@ cfg_if! {
/// With a pathname:
///
/// ```no_run
/// use async_std::os::unix::net::UnixListener;
/// use std::path::Path;
///
/// use async_std::os::unix::net::UnixListener;
///
/// let socket = UnixListener::bind("/tmp/socket").await?;
/// let addr = socket.local_addr()?;
/// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/socket")));

@ -10,9 +10,11 @@
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::{io, prelude::*};
//! use std::time::Duration;
//!
//! use async_std::io;
//! use async_std::prelude::*;
//!
//! let stdin = io::stdin();
//! let mut line = String::new();
//! let dur = Duration::from_secs(5);
@ -37,4 +39,6 @@ pub use crate::io::Write as _;
#[doc(no_inline)]
pub use crate::stream::Stream;
#[doc(no_inline)]
pub use crate::task_local;
#[doc(no_inline)]
pub use crate::time::Timeout as _;

@ -11,7 +11,8 @@ use crate::task::{Context, Poll};
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{prelude::*, stream};
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::empty::<i32>();
///

@ -10,7 +10,8 @@
//! # #![feature(async_await)]
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::{prelude::*, stream};
//! use async_std::prelude::*;
//! use async_std::stream;
//!
//! let mut s = stream::repeat(9).take(3);
//!

@ -10,7 +10,8 @@ use crate::task::{Context, Poll};
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{prelude::*, stream};
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::once(7);
///

@ -10,7 +10,8 @@ use crate::task::{Context, Poll};
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{prelude::*, stream};
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::repeat(7);
///

@ -10,7 +10,8 @@
//! # #![feature(async_await)]
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::{prelude::*, stream};
//! use async_std::prelude::*;
//! use async_std::stream;
//!
//! let mut s = stream::repeat(9).take(3);
//!
@ -71,7 +72,8 @@ pub trait Stream {
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{prelude::*, stream};
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::once(7);
///
@ -92,7 +94,8 @@ pub trait Stream {
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{prelude::*, stream};
/// use async_std::prelude::*;
/// use async_std::stream;
///
/// let mut s = stream::repeat(9).take(3);
///

@ -12,9 +12,11 @@
//! # #![feature(async_await)]
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::{sync::Mutex, task};
//! use std::sync::Arc;
//!
//! use async_std::sync::Mutex;
//! use async_std::task;
//!
//! let m1 = Arc::new(Mutex::new(0));
//! let m2 = m1.clone();
//!

@ -27,9 +27,11 @@ const BLOCKED: usize = 1 << 1;
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{sync::Mutex, task};
/// use std::sync::Arc;
///
/// use async_std::sync::Mutex;
/// use async_std::task;
///
/// let m = Arc::new(Mutex::new(0));
/// let mut tasks = vec![];
///
@ -84,9 +86,11 @@ impl<T> Mutex<T> {
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{sync::Mutex, task};
/// use std::sync::Arc;
///
/// use async_std::sync::Mutex;
/// use async_std::task;
///
/// let m1 = Arc::new(Mutex::new(10));
/// let m2 = m1.clone();
///
@ -197,9 +201,11 @@ impl<T> Mutex<T> {
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::{sync::Mutex, task};
/// use std::sync::Arc;
///
/// use async_std::sync::Mutex;
/// use async_std::task;
///
/// let m1 = Arc::new(Mutex::new(10));
/// let m2 = m1.clone();
///
@ -229,7 +235,6 @@ impl<T> Mutex<T> {
/// # Examples
///
/// ```
/// # #![feature(async_await)]
/// use async_std::sync::Mutex;
///
/// let mutex = Mutex::new(10);

@ -220,7 +220,7 @@ impl<T> RwLock<T> {
///
/// let lock = RwLock::new(1);
///
/// let mut n = lock.read().await;
/// let n = lock.read().await;
/// assert_eq!(*n, 1);
///
/// assert!(lock.try_read().is_some());
@ -385,7 +385,7 @@ impl<T> RwLock<T> {
///
/// let lock = RwLock::new(1);
///
/// let mut n = lock.read().await;
/// let n = lock.read().await;
/// assert_eq!(*n, 1);
///
/// assert!(lock.try_write().is_none());

@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
use std::time::Duration;
use crossbeam::channel::{bounded, Receiver, Sender};
use crossbeam_channel::{bounded, Receiver, Sender};
use lazy_static::lazy_static;
use crate::future::Future;

@ -21,9 +21,12 @@ use super::pool;
///
/// ```
/// # #![feature(async_await)]
/// use async_std::{task, task_local};
/// #
/// use std::cell::Cell;
///
/// use async_std::task;
/// use async_std::prelude::*;
///
/// task_local! {
/// static VAL: Cell<u32> = Cell::new(5);
/// }
@ -90,9 +93,12 @@ impl<T: Send + 'static> LocalKey<T> {
///
/// ```
/// # #![feature(async_await)]
/// use async_std::{task, task_local};
/// #
/// use std::cell::Cell;
///
/// use async_std::task;
/// use async_std::prelude::*;
///
/// task_local! {
/// static NUMBER: Cell<u32> = Cell::new(5);
/// }
@ -127,9 +133,12 @@ impl<T: Send + 'static> LocalKey<T> {
///
/// ```
/// # #![feature(async_await)]
/// use async_std::{task, task_local};
/// #
/// use std::cell::Cell;
///
/// use async_std::task;
/// use async_std::prelude::*;
///
/// task_local! {
/// static VAL: Cell<u32> = Cell::new(5);
/// }

@ -6,7 +6,7 @@ use std::pin::Pin;
use std::ptr;
use std::thread;
use crossbeam::channel::{unbounded, Sender};
use crossbeam_channel::{unbounded, Sender};
use futures::future::FutureExt;
use lazy_static::lazy_static;
@ -32,9 +32,9 @@ use crate::io;
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task::current;
/// use async_std::task;
///
/// println!("The name of this task is {:?}", current().name());
/// println!("The name of this task is {:?}", task::current().name());
/// #
/// # }) }
/// ```

@ -18,9 +18,10 @@ use crate::time::Timeout;
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task;
/// use std::time::Duration;
///
/// use async_std::task;
///
/// task::sleep(Duration::from_secs(1)).await;
/// #
/// # }) }

@ -184,7 +184,7 @@ impl Tag {
let new = mem::transmute::<usize, Option<Task>>(new_raw);
drop(new);
}
};
}
mem::transmute::<&AtomicUsize, &Option<Task>>(&self.raw_metadata)
.as_ref()

@ -12,9 +12,11 @@
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::{io, prelude::*};
//! use std::time::Duration;
//!
//! use async_std::io;
//! use async_std::prelude::*;
//!
//! let stdin = io::stdin();
//! let mut line = String::new();
//!

@ -54,9 +54,11 @@ pub trait Timeout: Future + Sized {
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
/// use std::time::Duration;
///
/// use async_std::io;
/// use async_std::prelude::*;
///
/// let stdin = io::stdin();
/// let mut line = String::new();
///

@ -2,7 +2,8 @@
use std::sync::atomic::{AtomicBool, Ordering};
use async_std::{task, task_local};
use async_std::task;
use async_std::task_local;
#[test]
fn drop_local() {

Loading…
Cancel
Save