Reformat doc examples

integrate-threads-example
Stjepan Glavina 5 years ago
parent 893fd9757c
commit 3f4a56abdc

@ -74,19 +74,16 @@ impl DirBuilder {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::{metadata, DirBuilder};
///
/// # futures::executor::block_on(async {
/// let path = "/tmp/foo/bar/baz";
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::DirBuilder;
///
/// DirBuilder::new()
/// .recursive(true)
/// .create(path)
/// .create("/tmp/foo/bar/baz")
/// .await?;
///
/// assert!(metadata(path).await?.is_dir());
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn create<P: AsRef<Path>>(&self, path: P) -> impl Future<Output = io::Result<()>> {
let mut builder = fs::DirBuilder::new();

@ -76,18 +76,18 @@ impl DirEntry {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_dir;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut dir = read_dir(".").await?;
/// let mut dir = fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.next().await {
/// let entry = entry?;
/// println!("{:?}", entry.path());
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn path(&self) -> PathBuf {
self.path.clone()
@ -101,18 +101,18 @@ impl DirEntry {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_dir;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut dir = read_dir(".").await?;
/// let mut dir = fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.next().await {
/// let entry = entry?;
/// println!("{:?}", entry.metadata().await?);
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn metadata(&self) -> io::Result<fs::Metadata> {
future::poll_fn(|cx| {
@ -154,18 +154,18 @@ impl DirEntry {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_dir;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut dir = read_dir(".").await?;
/// let mut dir = fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.next().await {
/// let entry = entry?;
/// println!("{:?}", entry.file_type().await?);
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn file_type(&self) -> io::Result<fs::FileType> {
future::poll_fn(|cx| {
@ -205,18 +205,18 @@ impl DirEntry {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_dir;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut dir = read_dir(".").await?;
/// let mut dir = fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.next().await {
/// let entry = entry?;
/// println!("{:?}", entry.file_name());
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn file_name(&self) -> OsString {
self.file_name.clone()

@ -34,29 +34,31 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::create("foo.txt").await?;
/// file.write_all(b"Hello, world!").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
///
/// Read the contents of a file into a `Vec<u8>`:
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::open("foo.txt").await?;
/// let mut contents = Vec::new();
/// file.read_to_end(&mut contents).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
#[derive(Debug)]
pub struct File {
@ -123,12 +125,13 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
///
/// # futures::executor::block_on(async {
/// let file = File::open("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
let path = path.as_ref().to_owned();
@ -169,12 +172,13 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
///
/// # futures::executor::block_on(async {
/// let file = File::create("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
let path = path.as_ref().to_owned();
@ -215,15 +219,16 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::create("foo.txt").await?;
/// file.write_all(b"Hello, world!").await?;
/// file.sync_all().await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn sync_all(&self) -> io::Result<()> {
future::poll_fn(|cx| {
@ -270,15 +275,16 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::create("foo.txt").await?;
/// file.write_all(b"Hello, world!").await?;
/// file.sync_data().await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn sync_data(&self) -> io::Result<()> {
future::poll_fn(|cx| {
@ -329,14 +335,15 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::create("foo.txt").await?;
/// file.set_len(10).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn set_len(&self, size: u64) -> io::Result<()> {
future::poll_fn(|cx| {
@ -376,13 +383,14 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
///
/// # futures::executor::block_on(async {
/// let file = File::open("foo.txt").await?;
/// let metadata = file.metadata().await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn metadata(&self) -> io::Result<fs::Metadata> {
future::poll_fn(|cx| {
@ -427,16 +435,17 @@ impl File {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::File;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut file = File::create("foo.txt").await?;
/// let mut perms = file.metadata().await?.permissions();
/// perms.set_readonly(true);
/// file.set_permissions(perms).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn set_permissions(&self, perm: fs::Permissions) -> io::Result<()> {
let mut perm = Some(perm);

@ -10,14 +10,15 @@
//!
//! ```no_run
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::fs::File;
//! use async_std::prelude::*;
//!
//! # futures::executor::block_on(async {
//! let mut file = File::create("foo.txt").await?;
//! file.write_all(b"Hello, world!").await?;
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! #
//! # Ok(()) }) }
//! ```
use std::fs;
@ -61,12 +62,13 @@ pub use std::fs::{FileType, Metadata, Permissions};
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::canonicalize;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let path = canonicalize(".").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let path = fs::canonicalize(".").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
let path = path.as_ref().to_owned();
@ -91,12 +93,13 @@ pub async fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::create_dir;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// create_dir("./some/dir").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::create_dir("./some/dir").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -120,12 +123,13 @@ pub async fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::create_dir_all;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// create_dir_all("./some/dir").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::create_dir_all("./some/dir").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -151,12 +155,13 @@ pub async fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::hard_link;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// hard_link("a.txt", "b.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::hard_link("a.txt", "b.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
let from = from.as_ref().to_owned();
@ -188,12 +193,13 @@ pub async fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Re
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::copy;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let bytes_copied = copy("foo.txt", "bar.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let bytes_copied = fs::copy("foo.txt", "bar.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
let from = from.as_ref().to_owned();
@ -220,12 +226,13 @@ pub async fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::metadata;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let perm = metadata("foo.txt").await?.permissions();
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let perm = fs::metadata("foo.txt").await?.permissions();
/// #
/// # Ok(()) }) }
/// ```
pub async fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
let path = path.as_ref().to_owned();
@ -253,12 +260,13 @@ pub async fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let contents = read("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let contents = fs::read("foo.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
let path = path.as_ref().to_owned();
@ -288,18 +296,18 @@ pub async fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_dir;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{fs, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut dir = read_dir(".").await?;
/// let mut dir = fs::read_dir(".").await?;
///
/// while let Some(entry) = dir.next().await {
/// let entry = entry?;
/// println!("{:?}", entry.file_name());
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
let path = path.as_ref().to_owned();
@ -325,12 +333,13 @@ pub async fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::read_link;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let path = read_link("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let path = fs::read_link("foo.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
let path = path.as_ref().to_owned();
@ -383,12 +392,13 @@ pub async fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::remove_dir;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// remove_dir("./some/dir").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::remove_dir("./some/dir").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -412,12 +422,13 @@ pub async fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::remove_dir_all;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// remove_dir_all("./some/dir").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::remove_dir_all("./some/dir").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -441,12 +452,13 @@ pub async fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::remove_file;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// remove_file("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::remove_file("foo.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -471,12 +483,13 @@ pub async fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::rename;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// rename("a.txt", "b.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::rename("a.txt", "b.txt").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
let from = from.as_ref().to_owned();
@ -501,15 +514,16 @@ pub async fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Resul
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::{metadata, set_permissions};
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let mut perm = metadata("foo.txt").await?.permissions();
/// let mut perm = fs::metadata("foo.txt").await?.permissions();
/// perm.set_readonly(true);
///
/// set_permissions("foo.txt", perm).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::set_permissions("foo.txt", perm).await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn set_permissions<P: AsRef<Path>>(path: P, perm: fs::Permissions) -> io::Result<()> {
let path = path.as_ref().to_owned();
@ -533,12 +547,13 @@ pub async fn set_permissions<P: AsRef<Path>>(path: P, perm: fs::Permissions) ->
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::symlink_metadata;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// let perm = symlink_metadata("foo.txt").await?.permissions();
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let perm = fs::symlink_metadata("foo.txt").await?.permissions();
/// #
/// # Ok(()) }) }
/// ```
pub async fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
let path = path.as_ref().to_owned();
@ -564,12 +579,13 @@ pub async fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::fs::write;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs;
///
/// # futures::executor::block_on(async {
/// write("foo.txt", b"Lorem ipsum").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// fs::write("foo.txt", b"Lorem ipsum").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
let path = path.as_ref().to_owned();

@ -33,32 +33,34 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .read(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
///
/// Opening a file for both reading and writing, creating it if it doesn't exist:
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .read(true)
/// .write(true)
/// .create(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
#[derive(Clone, Debug)]
pub struct OpenOptions(fs::OpenOptions);
@ -72,15 +74,16 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .read(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn new() -> OpenOptions {
OpenOptions(fs::OpenOptions::new())
@ -94,15 +97,16 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .read(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn read(&mut self, read: bool) -> &mut OpenOptions {
self.0.read(read);
@ -120,15 +124,16 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .write(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn write(&mut self, write: bool) -> &mut OpenOptions {
self.0.write(write);
@ -165,15 +170,16 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .append(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn append(&mut self, append: bool) -> &mut OpenOptions {
self.0.append(append);
@ -191,16 +197,17 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .write(true)
/// .truncate(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
self.0.truncate(truncate);
@ -220,16 +227,17 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .write(true)
/// .create(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn create(&mut self, create: bool) -> &mut OpenOptions {
self.0.create(create);
@ -256,16 +264,17 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new()
/// .write(true)
/// .create_new(true)
/// .open("foo.txt")
/// .await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
self.0.create_new(create_new);
@ -308,12 +317,13 @@ impl OpenOptions {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::fs::OpenOptions;
///
/// # futures::executor::block_on(async {
/// let file = OpenOptions::new().open("foo.txt").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn open<P: AsRef<Path>>(&self, path: P) -> impl Future<Output = io::Result<File>> {
let path = path.as_ref().to_owned();

@ -8,14 +8,16 @@ pub use std::future::Future;
/// # Examples
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::future::pending;
/// use async_std::prelude::*;
/// use std::time::Duration;
///
/// # async_std::task::block_on(async {
/// let dur = Duration::from_secs(1);
/// assert!(pending::<()>().timeout(dur).await.is_err());
/// # })
/// #
/// # }) }
/// ```
pub async fn pending<T>() -> T {
futures::future::pending::<T>().await
@ -31,11 +33,13 @@ pub async fn pending<T>() -> T {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::future::ready;
///
/// # async_std::task::block_on(async {
/// assert_eq!(ready(10).await, 10);
/// # })
/// #
/// # }) }
/// ```
pub async fn ready<T>(val: T) -> T {
val

@ -28,19 +28,16 @@ use std::io;
///
/// ```
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, task};
///
/// fn main() -> std::io::Result<()> {
/// task::block_on(async {
/// let mut reader: &[u8] = b"hello";
/// let mut writer: Vec<u8> = vec![];
/// let mut writer = io::stdout();
///
/// io::copy(&mut reader, &mut writer).await?;
///
/// assert_eq!(&b"hello"[..], &writer[..]);
/// Ok(())
/// })
/// }
/// #
/// # Ok(()) }) }
/// ```
pub async fn copy<R, W>(reader: &mut R, writer: &mut W) -> io::Result<u64>
where

@ -10,14 +10,15 @@
//!
//! ```no_run
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::io;
//!
//! # futures::executor::block_on(async {
//! let stdin = io::stdin();
//! let mut line = String::new();
//! stdin.read_line(&mut line).await?;
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! #
//! # Ok(()) }) }
//! ```
#[doc(inline)]

@ -19,14 +19,14 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::io::stderr;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut stderr = stderr();
/// let mut stderr = io::stderr();
/// stderr.write_all(b"Hello, world!").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn stderr() -> Stderr {
Stderr(Mutex::new(State::Idle(Some(Inner {

@ -20,14 +20,15 @@ use crate::task::blocking;
///
/// ```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 fn stdin() -> Stdin {
Stdin(Mutex::new(State::Idle(Some(Inner {

@ -19,14 +19,14 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::io::stdout;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut stdout = stdout();
/// let mut stdout = io::stdout();
/// stdout.write_all(b"Hello, world!").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn stdout() -> Stdout {
Stdout(Mutex::new(State::Idle(Some(Inner {

@ -14,17 +14,19 @@
//!
//! ```no_run
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::net::UdpSocket;
//!
//! # futures::executor::block_on(async {
//! let socket = UdpSocket::bind("127.0.0.1:8080").await?;
//! let mut buf = vec![0u8; 1024];
//!
//! loop {
//! let (n, peer) = socket.recv_from(&mut buf).await?;
//! socket.send_to(&buf[..n], &peer).await?;
//! }
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! #
//! # Ok(()) }) }
//! ```
pub use tcp::{Incoming, TcpListener, TcpStream};

@ -33,22 +33,17 @@ use crate::net::driver::IoHandle;
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::net::TcpStream;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{net::TcpStream, prelude::*};
///
/// # futures::executor::block_on(async {
/// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
/// println!("Connected to {}", &stream.peer_addr()?);
///
/// let msg = "hello world";
/// println!("<- {}", msg);
/// stream.write_all(msg.as_bytes()).await?;
/// stream.write_all(b"hello world").await?;
///
/// let mut buf = vec![0u8; 1024];
/// let n = stream.read(&mut buf).await?;
/// println!("-> {}\n", std::str::from_utf8(&buf[..n])?);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
#[derive(Debug)]
pub struct TcpStream {
@ -73,12 +68,13 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:0").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn connect<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpStream> {
enum State {
@ -157,16 +153,14 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
/// use std::net::{IpAddr, Ipv4Addr};
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// let expected = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
/// assert_eq!(stream.local_addr()?.ip(), expected);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let addr = stream.local_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()
@ -178,16 +172,14 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
/// use std::net::{IpAddr, Ipv4Addr};
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// let expected = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
/// assert_eq!(stream.peer_addr()?.ip(), expected);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let peer = stream.peer_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().peer_addr()
@ -203,15 +195,16 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_ttl(100)?;
/// assert_eq!(stream.ttl()?, 100);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn ttl(&self) -> io::Result<u32> {
self.io_handle.get_ref().ttl()
@ -226,22 +219,25 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_ttl(100)?;
/// assert_eq!(stream.ttl()?, 100);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.io_handle.get_ref().set_ttl(ttl)
}
/// Receives data on the socket from the remote address to which it is connected, without
/// removing that data from the queue. On success, returns the number of bytes peeked.
/// removing that data from the queue.
///
/// On success, returns the number of bytes peeked.
///
/// Successive calls return the same data. This is accomplished by passing `MSG_PEEK` as a flag
/// to the underlying `recv` system call.
@ -250,15 +246,16 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8000").await?;
///
/// let mut buf = [0; 10];
/// let len = stream.peek(&mut buf).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let mut buf = vec![0; 1024];
/// let n = stream.peek(&mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
let res = future::poll_fn(|cx| {
@ -286,15 +283,16 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_nodelay(true)?;
/// assert_eq!(stream.nodelay()?, true);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn nodelay(&self) -> io::Result<bool> {
self.io_handle.get_ref().nodelay()
@ -312,15 +310,16 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_nodelay(true)?;
/// assert_eq!(stream.nodelay()?, true);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.io_handle.get_ref().set_nodelay(nodelay)
@ -337,14 +336,15 @@ impl TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
/// use std::net::Shutdown;
///
/// # futures::executor::block_on(async {
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.shutdown(Shutdown::Both)?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn shutdown(&self, how: std::net::Shutdown) -> std::io::Result<()> {
self.io_handle.get_ref().shutdown(how)
@ -460,24 +460,20 @@ impl AsyncWrite for &TcpStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::io;
/// use async_std::net::TcpListener;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, net::TcpListener, prelude::*};
///
/// # futures::executor::block_on(async {
/// let listener = TcpListener::bind("127.0.0.1:8080").await?;
/// println!("Listening on {}", listener.local_addr()?);
///
/// let mut incoming = listener.incoming();
///
/// while let Some(stream) = incoming.next().await {
/// let stream = stream?;
/// println!("Accepting from: {}", stream.peer_addr()?);
///
/// let (reader, writer) = &mut (&stream, &stream);
/// io::copy(reader, writer).await?;
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
#[derive(Debug)]
pub struct TcpListener {
@ -502,12 +498,13 @@ impl TcpListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpListener;
///
/// # futures::executor::block_on(async {
/// let listener = TcpListener::bind("127.0.0.1:0").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
///
/// [`local_addr`]: #method.local_addr
@ -550,13 +547,14 @@ impl TcpListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpListener;
///
/// # futures::executor::block_on(async {
/// let listener = TcpListener::bind("127.0.0.1:0").await?;
/// let (stream, addr) = listener.accept().await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
future::poll_fn(|cx| {
@ -602,10 +600,10 @@ impl TcpListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// use async_std::net::TcpListener;
/// use async_std::prelude::*;
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{net::TcpListener, prelude::*};
///
/// # futures::executor::block_on(async {
/// let listener = TcpListener::bind("127.0.0.1:0").await?;
/// let mut incoming = listener.incoming();
///
@ -613,8 +611,8 @@ impl TcpListener {
/// let mut stream = stream?;
/// stream.write_all(b"hello world").await?;
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn incoming(&self) -> Incoming<'_> {
Incoming(self)
@ -629,16 +627,14 @@ impl TcpListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpListener;
/// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
///
/// # futures::executor::block_on(async {
/// let listener = TcpListener::bind("127.0.0.1:8080").await?;
///
/// let expected = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
/// assert_eq!(listener.local_addr()?, SocketAddr::V4(expected));
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let addr = listener.local_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()

@ -30,21 +30,19 @@ use crate::net::driver::IoHandle;
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// let mut buf = vec![0u8; 1024];
///
/// println!("Listening on {}", socket.local_addr()?);
///
/// loop {
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// let sent = socket.send_to(&buf[..n], &peer).await?;
/// println!("Sent {} out of {} bytes to {}", sent, n, peer);
/// socket.send_to(&buf[..n], &peer).await?;
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
#[derive(Debug)]
pub struct UdpSocket {
@ -68,12 +66,13 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
let mut last_err = None;
@ -116,13 +115,15 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::IpAddr;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
/// println!("Address: {:?}", socket.local_addr());
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// let addr = socket.local_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()
@ -136,6 +137,8 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// const THE_MERCHANT_OF_VENICE: &[u8] = b"
@ -145,14 +148,13 @@ impl UdpSocket {
/// And if you wrong us, shall we not revenge?
/// ";
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
///
/// let addr = "127.0.0.1:7878";
/// let sent = socket.send_to(THE_MERCHANT_OF_VENICE, &addr).await?;
/// println!("Sent {} bytes to {}", sent, addr);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addrs: A) -> io::Result<usize> {
let addr = match addrs.to_socket_addrs()?.next() {
@ -188,16 +190,17 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
///
/// let mut buf = vec![0; 1024];
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// println!("Received {} bytes from {}", n, peer);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
future::poll_fn(|cx| {
@ -229,13 +232,14 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
/// socket.connect("127.0.0.1:8080").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn connect<A: ToSocketAddrs>(&self, addrs: A) -> io::Result<()> {
let mut last_err = None;
@ -263,6 +267,8 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// const THE_MERCHANT_OF_VENICE: &[u8] = b"
@ -272,14 +278,13 @@ impl UdpSocket {
/// And if you wrong us, shall we not revenge?
/// ";
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
///
/// let addr = "127.0.0.1:7878";
/// let sent = socket.send_to(THE_MERCHANT_OF_VENICE, &addr).await?;
/// println!("Sent {} bytes to {}", sent, addr);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
future::poll_fn(|cx| {
@ -305,16 +310,17 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
///
/// # futures::executor::block_on(async {
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
///
/// let mut buf = vec![0; 1024];
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// println!("Received {} bytes from {}", n, peer);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
future::poll_fn(|cx| {
@ -438,17 +444,18 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::Ipv4Addr;
///
/// # futures::executor::block_on(async {
/// let interface = Ipv4Addr::new(0, 0, 0, 0);
/// let mdns_addr = Ipv4Addr::new(224, 0, 0, 123);
///
/// let socket = UdpSocket::bind("127.0.0.1:0").await?;
/// socket.join_multicast_v4(&mdns_addr, &interface)?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
self.io_handle
@ -466,17 +473,18 @@ impl UdpSocket {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::UdpSocket;
/// use std::net::{Ipv6Addr, SocketAddr};
///
/// # futures::executor::block_on(async {
/// 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?;
///
/// socket.join_multicast_v6(&mdns_addr, 0)?;
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
self.io_handle

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

@ -33,17 +33,17 @@ use crate::task::blocking;
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::bind("/tmp/socket1").await?;
/// socket.send_to(b"hello world", "/tmp/socket2").await?;
///
/// let mut buf = vec![0u8; 1024];
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// println!("Received {} bytes from {:?}", n, peer);
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub struct UnixDatagram {
#[cfg(not(feature = "docs.rs"))]
@ -67,12 +67,13 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::bind("/tmp/socket").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
let path = path.as_ref().to_owned();
@ -86,12 +87,13 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::unbound()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn unbound() -> io::Result<UnixDatagram> {
let socket = mio_uds::UnixDatagram::unbound()?;
@ -106,12 +108,13 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let (socket1, socket2) = UnixDatagram::pair()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
let (a, b) = mio_uds::UnixDatagram::pair()?;
@ -133,13 +136,14 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::unbound()?;
/// socket.connect("/tmp/socket").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
// TODO(stjepang): Connect the socket on a blocking pool.
@ -153,13 +157,14 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::bind("/tmp/socket").await?;
/// let addr = socket.local_addr()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()
@ -175,14 +180,15 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let mut socket = UnixDatagram::unbound()?;
/// socket.connect("/tmp/socket").await?;
/// let peer = socket.peer_addr()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().peer_addr()
@ -196,14 +202,15 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let mut socket = UnixDatagram::unbound()?;
/// let mut buf = vec![0; 1024];
/// let (n, peer) = socket.recv_from(&mut buf).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
future::poll_fn(|cx| {
@ -229,14 +236,15 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::bind("/tmp/socket").await?;
/// let mut buf = vec![0; 1024];
/// let n = socket.recv(&mut buf).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
future::poll_fn(|cx| {
@ -262,13 +270,14 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let mut socket = UnixDatagram::unbound()?;
/// socket.send_to(b"hello world", "/tmp/socket").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
future::poll_fn(|cx| {
@ -294,14 +303,15 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
///
/// # futures::executor::block_on(async {
/// let mut socket = UnixDatagram::unbound()?;
/// socket.connect("/tmp/socket").await?;
/// socket.send(b"hello world").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
future::poll_fn(|cx| {
@ -330,14 +340,15 @@ impl UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixDatagram;
/// use std::net::Shutdown;
///
/// # futures::executor::block_on(async {
/// let socket = UnixDatagram::unbound()?;
/// socket.shutdown(Shutdown::Both)?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.io_handle.get_ref().shutdown(how)
@ -380,10 +391,11 @@ impl fmt::Debug for UnixDatagram {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixListener;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket").await?;
/// let mut incoming = listener.incoming();
///
@ -391,8 +403,8 @@ impl fmt::Debug for UnixDatagram {
/// let mut stream = stream?;
/// stream.write_all(b"hello world").await?;
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub struct UnixListener {
#[cfg(not(feature = "docs.rs"))]
@ -408,12 +420,13 @@ impl UnixListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixListener;
///
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
let path = path.as_ref().to_owned();
@ -433,13 +446,14 @@ impl UnixListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixListener;
///
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket").await?;
/// let (socket, addr) = listener.accept().await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
future::poll_fn(|cx| {
@ -480,10 +494,11 @@ impl UnixListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixListener;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket").await?;
/// let mut incoming = listener.incoming();
///
@ -491,8 +506,8 @@ impl UnixListener {
/// let mut stream = stream?;
/// stream.write_all(b"hello world").await?;
/// }
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn incoming(&self) -> Incoming<'_> {
Incoming(self)
@ -504,13 +519,14 @@ impl UnixListener {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixListener;
///
/// # futures::executor::block_on(async {
/// let listener = UnixListener::bind("/tmp/socket").await?;
/// let addr = listener.local_addr()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()
@ -567,17 +583,18 @@ impl Stream for Incoming<'_> {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
/// use async_std::prelude::*;
///
/// # futures::executor::block_on(async {
/// let mut stream = UnixStream::connect("/tmp/socket").await?;
/// stream.write_all(b"hello world").await?;
///
/// let mut response = Vec::new();
/// stream.read_to_end(&mut response).await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub struct UnixStream {
#[cfg(not(feature = "docs.rs"))]
@ -593,12 +610,13 @@ impl UnixStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
///
/// # futures::executor::block_on(async {
/// let stream = UnixStream::connect("/tmp/socket").await?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
enum State {
@ -654,12 +672,13 @@ impl UnixStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
///
/// # futures::executor::block_on(async {
/// let stream = UnixStream::pair()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
let (a, b) = mio_uds::UnixStream::pair()?;
@ -680,13 +699,14 @@ impl UnixStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
///
/// # futures::executor::block_on(async {
/// let stream = UnixStream::connect("/tmp/socket").await?;
/// let addr = stream.local_addr()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().local_addr()
@ -698,13 +718,14 @@ impl UnixStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
///
/// # futures::executor::block_on(async {
/// let stream = UnixStream::connect("/tmp/socket").await?;
/// let peer = stream.peer_addr()?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.io_handle.get_ref().peer_addr()
@ -719,14 +740,15 @@ impl UnixStream {
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::os::unix::net::UnixStream;
/// use std::net::Shutdown;
///
/// # futures::executor::block_on(async {
/// let stream = UnixStream::connect("/tmp/socket").await?;
/// stream.shutdown(Shutdown::Both)?;
/// # std::io::Result::Ok(())
/// # }).unwrap();
/// #
/// # Ok(()) }) }
/// ```
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.io_handle.get_ref().shutdown(how)

@ -8,17 +8,18 @@
//!
//! ```no_run
//! # #![feature(async_await)]
//! # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
//! #
//! use async_std::{io, prelude::*};
//! use std::time::Duration;
//!
//! # async_std::task::block_on(async {
//! let stdin = io::stdin();
//! let mut line = String::new();
//! let dur = Duration::from_secs(5);
//!
//! stdin.read_line(&mut line).timeout(dur).await??;
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! #
//! # Ok(()) }) }
//! ```
//!
//! [`timeout`]: ../time/trait.Timeout.html#method.timeout

@ -8,16 +8,17 @@
//!
//! ```
//! # #![feature(async_await)]
//! # use async_std::prelude::*;
//! # async_std::task::block_on(async {
//! use async_std::stream;
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::{prelude::*, stream};
//!
//! let mut stream = stream::repeat(9).take(3);
//!
//! while let Some(num) = stream.next().await {
//! assert_eq!(num, 9);
//! }
//! # std::io::Result::Ok(())
//! # }).unwrap();
//! #
//! # }) }
//! ```
#[doc(inline)]

@ -10,10 +10,11 @@
//!
//! ```
//! # #![feature(async_await)]
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::{sync::Mutex, task};
//! use std::sync::Arc;
//!
//! # futures::executor::block_on(async {
//! let m1 = Arc::new(Mutex::new(0));
//! let m2 = m1.clone();
//!
@ -23,7 +24,8 @@
//! .await;
//!
//! assert_eq!(*m1.lock().await, 1);
//! # })
//! #
//! # }) }
//! ```
pub use mutex::{Mutex, MutexGuard};

@ -24,10 +24,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;
///
/// # futures::executor::block_on(async {
/// let m = Arc::new(Mutex::new(0));
/// let mut tasks = vec![];
///
@ -42,7 +43,8 @@ const BLOCKED: usize = 1 << 1;
/// t.await;
/// }
/// assert_eq!(*m.lock().await, 10);
/// # })
/// #
/// # }) }
/// ```
pub struct Mutex<T> {
state: AtomicUsize,
@ -79,10 +81,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;
///
/// # futures::executor::block_on(async {
/// let m1 = Arc::new(Mutex::new(10));
/// let m2 = m1.clone();
///
@ -92,7 +95,8 @@ impl<T> Mutex<T> {
/// .await;
///
/// assert_eq!(*m2.lock().await, 20);
/// # })
/// #
/// # }) }
/// ```
pub async fn lock(&self) -> MutexGuard<'_, T> {
pub struct LockFuture<'a, T> {
@ -190,10 +194,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;
///
/// # futures::executor::block_on(async {
/// let m1 = Arc::new(Mutex::new(10));
/// let m2 = m1.clone();
///
@ -207,7 +212,8 @@ impl<T> Mutex<T> {
/// .await;
///
/// assert_eq!(*m2.lock().await, 20);
/// # })
/// #
/// # }) }
/// ```
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
if self.state.fetch_or(LOCK, Ordering::Acquire) & LOCK == 0 {
@ -241,13 +247,15 @@ impl<T> Mutex<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::Mutex;
///
/// # futures::executor::block_on(async {
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut() = 10;
/// assert_eq!(*mutex.lock().await, 10);
/// });
/// #
/// # }) }
/// ```
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.value.get() }

@ -33,9 +33,10 @@ const READ_COUNT_MASK: usize = !(ONE_READ - 1);
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let lock = RwLock::new(5);
///
/// // Multiple read locks can be held at a time.
@ -49,7 +50,8 @@ const READ_COUNT_MASK: usize = !(ONE_READ - 1);
/// let mut w = lock.write().await;
/// *w += 1;
/// assert_eq!(*w, 6);
/// # })
/// #
/// # }) }
/// ```
pub struct RwLock<T> {
state: AtomicUsize,
@ -88,16 +90,18 @@ impl<T> RwLock<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let lock = RwLock::new(1);
///
/// let n = lock.read().await;
/// assert_eq!(*n, 1);
///
/// assert!(lock.try_read().is_some());
/// # })
/// #
/// # }) }
/// ```
pub async fn read(&self) -> RwLockReadGuard<'_, T> {
pub struct LockFuture<'a, T> {
@ -209,16 +213,18 @@ impl<T> RwLock<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let lock = RwLock::new(1);
///
/// let mut n = lock.read().await;
/// assert_eq!(*n, 1);
///
/// assert!(lock.try_read().is_some());
/// # })
/// #
/// # }) }
/// ```
pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>> {
let mut state = self.state.load(Ordering::Acquire);
@ -250,16 +256,18 @@ impl<T> RwLock<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let lock = RwLock::new(1);
///
/// let mut n = lock.write().await;
/// *n = 2;
///
/// assert!(lock.try_read().is_none());
/// # })
/// #
/// # }) }
/// ```
pub async fn write(&self) -> RwLockWriteGuard<'_, T> {
pub struct LockFuture<'a, T> {
@ -370,16 +378,18 @@ impl<T> RwLock<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let lock = RwLock::new(1);
///
/// let mut n = lock.read().await;
/// assert_eq!(*n, 1);
///
/// assert!(lock.try_write().is_none());
/// # })
/// #
/// # }) }
/// ```
pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>> {
let mut state = self.state.load(Ordering::Acquire);
@ -427,13 +437,15 @@ impl<T> RwLock<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::sync::RwLock;
///
/// # futures::executor::block_on(async {
/// let mut lock = RwLock::new(0);
/// *lock.get_mut() = 10;
/// assert_eq!(*lock.write().await, 10);
/// });
/// #
/// # }) }
/// ```
pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.value.get() }

@ -182,11 +182,7 @@ impl<T: Send + 'static> LocalKey<T> {
}
let key = self.__key.load(Ordering::Acquire);
if key == 0 {
init(&self.__key)
} else {
key
}
if key == 0 { init(&self.__key) } else { key }
}
}

@ -11,14 +11,15 @@
//!
//! ```
//! # #![feature(async_await)]
//! # fn main() { async_std::task::block_on(async {
//! #
//! use async_std::task;
//!
//! # async_std::task::block_on(async {
//! let handle = task::spawn(async {
//! 1 + 2
//! });
//! assert_eq!(handle.await, 3);
//! # });
//! #
//! # }) }
//! ```
#[doc(inline)]

@ -30,11 +30,14 @@ use super::{JoinHandle, Task};
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task::current;
///
/// # async_std::task::block_on(async {
/// println!("The name of this task is {:?}", current().name());
/// # });
/// #
/// # }) }
/// ```
pub fn current() -> Task {
get_task(|task| task.clone()).expect("`task::current()` called outside the context of a task")
}
@ -49,15 +52,17 @@ pub fn current() -> Task {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task;
///
/// # async_std::task::block_on(async {
/// let handle = task::spawn(async {
/// 1 + 2
/// });
///
/// assert_eq!(handle.await, 3);
/// # });
/// #
/// # }) }
/// ```
pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where

@ -16,12 +16,14 @@ use crate::time::Timeout;
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task;
/// use std::time::Duration;
///
/// # async_std::task::block_on(async {
/// task::sleep(Duration::from_secs(1)).await;
/// # });
/// #
/// # }) }
/// ```
pub async fn sleep(dur: Duration) {
let _ = future::pending::<()>().timeout(dur).await;

@ -66,14 +66,16 @@ impl<T> JoinHandle<T> {
///
/// ```
/// # #![feature(async_await)]
/// # fn main() { async_std::task::block_on(async {
/// #
/// use async_std::task;
///
/// # async_std::task::block_on(async {
/// let handle = task::spawn(async {
/// 1 + 2
/// });
/// println!("id = {}", handle.task().id());
/// # });
/// #
/// # }) }
pub fn task(&self) -> &Task {
self.0.tag().task()
}
@ -97,13 +99,12 @@ impl<T> Future for JoinHandle<T> {
///
/// ```
/// # #![feature(async_await)]
/// #
/// use async_std::task;
///
/// # async_std::task::block_on(async {
/// task::block_on(async {
/// println!("id = {:?}", task::current().id());
/// })
/// # });
/// ```
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub struct TaskId(NonZeroU64);

@ -34,7 +34,6 @@ use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use cfg_if::cfg_if;
use futures_timer::Delay;
use pin_utils::unsafe_pinned;
@ -56,20 +55,18 @@ impl From<TimeoutError> for io::Error {
}
}
cfg_if! {
if #[cfg(feature = "docs.rs")] {
#[doc(hidden)]
pub struct ImplFuture<T>(std::marker::PhantomData<T>);
/// An extension trait that configures timeouts for futures.
pub trait Timeout: Future + Sized {
/// TODO
type TimeoutFuture: Future<Output = Result<<Self as Future>::Output, TimeoutError>>;
/// An extension trait that configures timeouts for futures.
pub trait Timeout: Future + Sized {
/// Awaits a future to completion or times out after a duration of time.
///
/// # Examples
///
/// ```no_run
/// # #![feature(async_await)]
/// # fn main() -> io::Result<()> { async_std::task::block_on(async {
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::{io, prelude::*};
/// use std::time::Duration;
@ -84,39 +81,34 @@ cfg_if! {
/// #
/// # Ok(()) }) }
/// ```
fn timeout(self, dur: Duration) -> ImplFuture<Result<Self::Output, TimeoutError>> {
TimeoutFuture {
future: self,
delay: Delay::new(dur),
}
}
}
} else {
/// An extension trait that configures timeouts for futures.
pub trait Timeout: Future + Sized {
/// Awaits a future to completion or times out after a duration of time.
fn timeout(self, dur: Duration) -> TimeoutFuture<Self> {
fn timeout(self, dur: Duration) -> Self::TimeoutFuture;
}
impl<F: Future> Timeout for F {
type TimeoutFuture = TimeoutFuture<F>;
fn timeout(self, dur: Duration) -> Self::TimeoutFuture {
TimeoutFuture {
future: self,
delay: Delay::new(dur),
}
}
}
}
/// A future that times out after a duration of time.
#[doc(hidden)]
#[derive(Debug)]
pub struct TimeoutFuture<F> {
/// A future that times out after a duration of time.
#[doc(hidden)]
#[derive(Debug)]
pub struct TimeoutFuture<F> {
future: F,
delay: Delay,
}
}
impl<F> TimeoutFuture<F> {
impl<F> TimeoutFuture<F> {
unsafe_pinned!(future: F);
unsafe_pinned!(delay: Delay);
}
}
impl<F: Future> Future for TimeoutFuture<F> {
impl<F: Future> Future for TimeoutFuture<F> {
type Output = Result<F::Output, TimeoutError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
@ -128,8 +120,4 @@ cfg_if! {
},
}
}
}
}
}
impl<F: Future> Timeout for F {}

Loading…
Cancel
Save