mirror of
https://github.com/async-rs/async-std.git
synced 2025-02-06 12:45:32 +00:00
Reindent de-macrofied code.
This commit only affects whitespace; `git diff -w` for it is empty.
This commit is contained in:
parent
1146c66f1b
commit
01ede03e0a
6 changed files with 3129 additions and 3129 deletions
|
@ -22,267 +22,267 @@ cfg_unstable_default! {
|
|||
|
||||
pub use core::future::Future as Future;
|
||||
|
||||
#[doc = r#"
|
||||
Extension methods for [`Future`].
|
||||
#[doc = r#"
|
||||
Extension methods for [`Future`].
|
||||
|
||||
[`Future`]: ../future/trait.Future.html
|
||||
"#]
|
||||
pub trait FutureExt: Future {
|
||||
/// Returns a Future that delays execution for a specified time.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # async_std::task::block_on(async {
|
||||
/// use async_std::prelude::*;
|
||||
/// use async_std::future;
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// let a = future::ready(1).delay(Duration::from_millis(2000));
|
||||
/// dbg!(a.await);
|
||||
/// # })
|
||||
/// ```
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn delay(self, dur: Duration) -> DelayFuture<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
DelayFuture::new(self, dur)
|
||||
}
|
||||
|
||||
/// Flatten out the execution of this future when the result itself
|
||||
/// can be converted into another future.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # async_std::task::block_on(async {
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let nested_future = async { async { 1 } };
|
||||
/// let future = nested_future.flatten();
|
||||
/// assert_eq!(future.await, 1);
|
||||
/// # })
|
||||
/// ```
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn flatten(
|
||||
self,
|
||||
) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future>
|
||||
where
|
||||
Self: Sized,
|
||||
<Self as Future>::Output: IntoFuture,
|
||||
{
|
||||
FlattenFuture::new(self)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for one of two similarly-typed futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning the output of the
|
||||
first future that completes.
|
||||
|
||||
This function will return a new future which awaits for either one of both
|
||||
futures to complete. If multiple futures are completed at the same time,
|
||||
resolution will occur in the order that they have been passed.
|
||||
|
||||
Note that this function consumes all futures passed, and once a future is
|
||||
completed, all other futures are dropped.
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::pending();
|
||||
let b = future::ready(1u8);
|
||||
let c = future::ready(2u8);
|
||||
|
||||
let f = a.race(b).race(c);
|
||||
assert_eq!(f.await, 1u8);
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn race<F>(
|
||||
self,
|
||||
other: F,
|
||||
) -> Race<Self, F>
|
||||
where
|
||||
Self: std::future::Future + Sized,
|
||||
F: std::future::Future<Output = <Self as std::future::Future>::Output>,
|
||||
{
|
||||
Race::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for one of two similarly-typed fallible futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning all results once complete.
|
||||
|
||||
`try_race` is similar to [`race`], but keeps going if a future
|
||||
resolved to an error until all futures have been resolved. In which case
|
||||
an error is returned.
|
||||
|
||||
The ordering of which value is yielded when two futures resolve
|
||||
simultaneously is intentionally left unspecified.
|
||||
|
||||
[`race`]: #method.race
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
use std::io::{Error, ErrorKind};
|
||||
|
||||
let a = future::pending::<Result<_, Error>>();
|
||||
let b = future::ready(Err(Error::from(ErrorKind::Other)));
|
||||
let c = future::ready(Ok(1u8));
|
||||
|
||||
let f = a.try_race(b).try_race(c);
|
||||
assert_eq!(f.await?, 1u8);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn try_race<F, T, E>(
|
||||
self,
|
||||
other: F
|
||||
) -> TryRace<Self, F>
|
||||
where
|
||||
Self: std::future::Future<Output = Result<T, E>> + Sized,
|
||||
F: std::future::Future<Output = <Self as std::future::Future>::Output>,
|
||||
{
|
||||
TryRace::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for two similarly-typed futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning the output of the
|
||||
futures once both complete.
|
||||
|
||||
This function returns a new future which polls both futures
|
||||
concurrently.
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::ready(1u8);
|
||||
let b = future::ready(2u16);
|
||||
|
||||
let f = a.join(b);
|
||||
assert_eq!(f.await, (1u8, 2u16));
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn join<F>(
|
||||
self,
|
||||
other: F
|
||||
) -> Join<Self, F>
|
||||
where
|
||||
Self: std::future::Future + Sized,
|
||||
F: std::future::Future,
|
||||
{
|
||||
Join::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for two similarly-typed fallible futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning all results once
|
||||
complete.
|
||||
|
||||
`try_join` is similar to [`join`], but returns an error immediately
|
||||
if a future resolves to an error.
|
||||
|
||||
[`join`]: #method.join
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::ready(Err::<u8, &str>("Error"));
|
||||
let b = future::ready(Ok(1u8));
|
||||
|
||||
let f = a.try_join(b);
|
||||
assert_eq!(f.await, Err("Error"));
|
||||
|
||||
let a = future::ready(Ok::<u8, String>(1u8));
|
||||
let b = future::ready(Ok::<u16, String>(2u16));
|
||||
|
||||
let f = a.try_join(b);
|
||||
assert_eq!(f.await, Ok((1u8, 2u16)));
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn try_join<F, A, B, E>(
|
||||
self,
|
||||
other: F
|
||||
) -> TryJoin<Self, F>
|
||||
where
|
||||
Self: std::future::Future<Output = Result<A, E>> + Sized,
|
||||
F: std::future::Future<Output = Result<B, E>>,
|
||||
{
|
||||
TryJoin::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for both the future and a timeout, if the timeout completes before
|
||||
the future, it returns a TimeoutError.
|
||||
|
||||
# Example
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
#
|
||||
use std::time::Duration;
|
||||
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let fut = future::ready(0);
|
||||
let dur = Duration::from_millis(100);
|
||||
let res = fut.timeout(dur).await;
|
||||
assert!(res.is_ok());
|
||||
|
||||
let fut = future::pending::<()>();
|
||||
let dur = Duration::from_millis(100);
|
||||
let res = fut.timeout(dur).await;
|
||||
assert!(res.is_err())
|
||||
#
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(all(feature = "default", feature = "unstable"), feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn timeout(self, dur: Duration) -> TimeoutFuture<Self>
|
||||
where Self: Sized
|
||||
{
|
||||
TimeoutFuture::new(self, dur)
|
||||
}
|
||||
[`Future`]: ../future/trait.Future.html
|
||||
"#]
|
||||
pub trait FutureExt: Future {
|
||||
/// Returns a Future that delays execution for a specified time.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # async_std::task::block_on(async {
|
||||
/// use async_std::prelude::*;
|
||||
/// use async_std::future;
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// let a = future::ready(1).delay(Duration::from_millis(2000));
|
||||
/// dbg!(a.await);
|
||||
/// # })
|
||||
/// ```
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn delay(self, dur: Duration) -> DelayFuture<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
DelayFuture::new(self, dur)
|
||||
}
|
||||
|
||||
/// Flatten out the execution of this future when the result itself
|
||||
/// can be converted into another future.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # async_std::task::block_on(async {
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let nested_future = async { async { 1 } };
|
||||
/// let future = nested_future.flatten();
|
||||
/// assert_eq!(future.await, 1);
|
||||
/// # })
|
||||
/// ```
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn flatten(
|
||||
self,
|
||||
) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future>
|
||||
where
|
||||
Self: Sized,
|
||||
<Self as Future>::Output: IntoFuture,
|
||||
{
|
||||
FlattenFuture::new(self)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for one of two similarly-typed futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning the output of the
|
||||
first future that completes.
|
||||
|
||||
This function will return a new future which awaits for either one of both
|
||||
futures to complete. If multiple futures are completed at the same time,
|
||||
resolution will occur in the order that they have been passed.
|
||||
|
||||
Note that this function consumes all futures passed, and once a future is
|
||||
completed, all other futures are dropped.
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::pending();
|
||||
let b = future::ready(1u8);
|
||||
let c = future::ready(2u8);
|
||||
|
||||
let f = a.race(b).race(c);
|
||||
assert_eq!(f.await, 1u8);
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn race<F>(
|
||||
self,
|
||||
other: F,
|
||||
) -> Race<Self, F>
|
||||
where
|
||||
Self: std::future::Future + Sized,
|
||||
F: std::future::Future<Output = <Self as std::future::Future>::Output>,
|
||||
{
|
||||
Race::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for one of two similarly-typed fallible futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning all results once complete.
|
||||
|
||||
`try_race` is similar to [`race`], but keeps going if a future
|
||||
resolved to an error until all futures have been resolved. In which case
|
||||
an error is returned.
|
||||
|
||||
The ordering of which value is yielded when two futures resolve
|
||||
simultaneously is intentionally left unspecified.
|
||||
|
||||
[`race`]: #method.race
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
use std::io::{Error, ErrorKind};
|
||||
|
||||
let a = future::pending::<Result<_, Error>>();
|
||||
let b = future::ready(Err(Error::from(ErrorKind::Other)));
|
||||
let c = future::ready(Ok(1u8));
|
||||
|
||||
let f = a.try_race(b).try_race(c);
|
||||
assert_eq!(f.await?, 1u8);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn try_race<F, T, E>(
|
||||
self,
|
||||
other: F
|
||||
) -> TryRace<Self, F>
|
||||
where
|
||||
Self: std::future::Future<Output = Result<T, E>> + Sized,
|
||||
F: std::future::Future<Output = <Self as std::future::Future>::Output>,
|
||||
{
|
||||
TryRace::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for two similarly-typed futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning the output of the
|
||||
futures once both complete.
|
||||
|
||||
This function returns a new future which polls both futures
|
||||
concurrently.
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::ready(1u8);
|
||||
let b = future::ready(2u16);
|
||||
|
||||
let f = a.join(b);
|
||||
assert_eq!(f.await, (1u8, 2u16));
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn join<F>(
|
||||
self,
|
||||
other: F
|
||||
) -> Join<Self, F>
|
||||
where
|
||||
Self: std::future::Future + Sized,
|
||||
F: std::future::Future,
|
||||
{
|
||||
Join::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for two similarly-typed fallible futures to complete.
|
||||
|
||||
Awaits multiple futures simultaneously, returning all results once
|
||||
complete.
|
||||
|
||||
`try_join` is similar to [`join`], but returns an error immediately
|
||||
if a future resolves to an error.
|
||||
|
||||
[`join`]: #method.join
|
||||
|
||||
# Examples
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let a = future::ready(Err::<u8, &str>("Error"));
|
||||
let b = future::ready(Ok(1u8));
|
||||
|
||||
let f = a.try_join(b);
|
||||
assert_eq!(f.await, Err("Error"));
|
||||
|
||||
let a = future::ready(Ok::<u8, String>(1u8));
|
||||
let b = future::ready(Ok::<u16, String>(2u16));
|
||||
|
||||
let f = a.try_join(b);
|
||||
assert_eq!(f.await, Ok((1u8, 2u16)));
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn try_join<F, A, B, E>(
|
||||
self,
|
||||
other: F
|
||||
) -> TryJoin<Self, F>
|
||||
where
|
||||
Self: std::future::Future<Output = Result<A, E>> + Sized,
|
||||
F: std::future::Future<Output = Result<B, E>>,
|
||||
{
|
||||
TryJoin::new(self, other)
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Waits for both the future and a timeout, if the timeout completes before
|
||||
the future, it returns a TimeoutError.
|
||||
|
||||
# Example
|
||||
```
|
||||
# async_std::task::block_on(async {
|
||||
#
|
||||
use std::time::Duration;
|
||||
|
||||
use async_std::prelude::*;
|
||||
use async_std::future;
|
||||
|
||||
let fut = future::ready(0);
|
||||
let dur = Duration::from_millis(100);
|
||||
let res = fut.timeout(dur).await;
|
||||
assert!(res.is_ok());
|
||||
|
||||
let fut = future::pending::<()>();
|
||||
let dur = Duration::from_millis(100);
|
||||
let res = fut.timeout(dur).await;
|
||||
assert!(res.is_err())
|
||||
#
|
||||
# });
|
||||
```
|
||||
"#]
|
||||
#[cfg(any(all(feature = "default", feature = "unstable"), feature = "docs"))]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
fn timeout(self, dur: Duration) -> TimeoutFuture<Self>
|
||||
where Self: Sized
|
||||
{
|
||||
TimeoutFuture::new(self, dur)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Future + ?Sized> FutureExt for T {}
|
||||
|
||||
|
|
|
@ -17,226 +17,226 @@ use crate::task::{Context, Poll};
|
|||
|
||||
pub use futures_io::AsyncBufRead as BufRead;
|
||||
|
||||
#[doc = r#"
|
||||
Extension methods for [`BufRead`].
|
||||
|
||||
[`BufRead`]: ../trait.BufRead.html
|
||||
"#]
|
||||
pub trait BufReadExt: BufRead {
|
||||
#[doc = r#"
|
||||
Extension methods for [`BufRead`].
|
||||
Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
|
||||
|
||||
[`BufRead`]: ../trait.BufRead.html
|
||||
This function will read bytes from the underlying stream until the delimiter or EOF
|
||||
is found. Once found, all bytes up to, and including, the delimiter (if found) will
|
||||
be appended to `buf`.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = BufReader::new(File::open("a.txt").await?);
|
||||
|
||||
let mut buf = Vec::with_capacity(1024);
|
||||
let n = file.read_until(b'\n', &mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
|
||||
Multiple successful calls to `read_until` append all bytes up to and including to
|
||||
`buf`:
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let from: &[u8] = b"append\nexample\n";
|
||||
let mut reader = BufReader::new(from);
|
||||
let mut buf = vec![];
|
||||
|
||||
let mut size = reader.read_until(b'\n', &mut buf).await?;
|
||||
assert_eq!(size, 7);
|
||||
assert_eq!(buf, b"append\n");
|
||||
|
||||
size += reader.read_until(b'\n', &mut buf).await?;
|
||||
assert_eq!(size, from.len());
|
||||
|
||||
assert_eq!(buf, from);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
pub trait BufReadExt: BufRead {
|
||||
#[doc = r#"
|
||||
Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
|
||||
|
||||
This function will read bytes from the underlying stream until the delimiter or EOF
|
||||
is found. Once found, all bytes up to, and including, the delimiter (if found) will
|
||||
be appended to `buf`.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = BufReader::new(File::open("a.txt").await?);
|
||||
|
||||
let mut buf = Vec::with_capacity(1024);
|
||||
let n = file.read_until(b'\n', &mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
|
||||
Multiple successful calls to `read_until` append all bytes up to and including to
|
||||
`buf`:
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let from: &[u8] = b"append\nexample\n";
|
||||
let mut reader = BufReader::new(from);
|
||||
let mut buf = vec![];
|
||||
|
||||
let mut size = reader.read_until(b'\n', &mut buf).await?;
|
||||
assert_eq!(size, 7);
|
||||
assert_eq!(buf, b"append\n");
|
||||
|
||||
size += reader.read_until(b'\n', &mut buf).await?;
|
||||
assert_eq!(size, from.len());
|
||||
|
||||
assert_eq!(buf, from);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_until<'a>(
|
||||
&'a mut self,
|
||||
byte: u8,
|
||||
buf: &'a mut Vec<u8>,
|
||||
) -> ReadUntilFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadUntilFuture {
|
||||
reader: self,
|
||||
byte,
|
||||
buf,
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes and appends them into `buf` until a newline (the 0xA byte) is
|
||||
reached.
|
||||
|
||||
This function will read bytes from the underlying stream until the newline
|
||||
delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and
|
||||
including, the delimiter (if found) will be appended to `buf`.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
If this function returns `Ok(0)`, the stream has reached EOF.
|
||||
|
||||
# Errors
|
||||
|
||||
This function has the same error semantics as [`read_until`] and will also return
|
||||
an error if the read bytes are not valid UTF-8. If an I/O error is encountered then
|
||||
`buf` may contain some bytes already read in the event that all data read so far
|
||||
was valid UTF-8.
|
||||
|
||||
[`read_until`]: #method.read_until
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = BufReader::new(File::open("a.txt").await?);
|
||||
|
||||
let mut buf = String::new();
|
||||
file.read_line(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_line<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut String,
|
||||
) -> ReadLineFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadLineFuture {
|
||||
reader: self,
|
||||
bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
|
||||
buf,
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Returns a stream over the lines of this byte stream.
|
||||
|
||||
The stream returned from this function will yield instances of
|
||||
[`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline byte
|
||||
(the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
|
||||
|
||||
[`io::Result`]: type.Result.html
|
||||
[`String`]: https://doc.rust-lang.org/std/string/struct.String.html
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let file = File::open("a.txt").await?;
|
||||
let mut lines = BufReader::new(file).lines();
|
||||
let mut count = 0;
|
||||
|
||||
while let Some(line) = lines.next().await {
|
||||
line?;
|
||||
count += 1;
|
||||
}
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn lines(self) -> Lines<Self>
|
||||
where
|
||||
Self: Unpin + Sized,
|
||||
{
|
||||
Lines {
|
||||
reader: self,
|
||||
buf: String::new(),
|
||||
bytes: Vec::new(),
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Returns a stream over the contents of this reader split on the byte `byte`.
|
||||
|
||||
The stream returned from this function will return instances of
|
||||
[`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
|
||||
the delimiter byte at the end.
|
||||
|
||||
This function will yield errors whenever [`read_until`] would have
|
||||
also yielded an error.
|
||||
|
||||
[`io::Result`]: type.Result.html
|
||||
[`Vec<u8>`]: ../vec/struct.Vec.html
|
||||
[`read_until`]: #method.read_until
|
||||
|
||||
# Examples
|
||||
|
||||
[`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
|
||||
this example, we use [`Cursor`] to iterate over all hyphen delimited
|
||||
segments in a byte slice
|
||||
|
||||
[`Cursor`]: struct.Cursor.html
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::io;
|
||||
|
||||
let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
|
||||
|
||||
let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
|
||||
assert_eq!(split_iter.next().await, Some(b"lorem".to_vec()));
|
||||
assert_eq!(split_iter.next().await, Some(b"ipsum".to_vec()));
|
||||
assert_eq!(split_iter.next().await, Some(b"dolor".to_vec()));
|
||||
assert_eq!(split_iter.next().await, None);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn split(self, byte: u8) -> Split<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Split {
|
||||
reader: self,
|
||||
buf: Vec::new(),
|
||||
delim: byte,
|
||||
read: 0,
|
||||
}
|
||||
fn read_until<'a>(
|
||||
&'a mut self,
|
||||
byte: u8,
|
||||
buf: &'a mut Vec<u8>,
|
||||
) -> ReadUntilFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadUntilFuture {
|
||||
reader: self,
|
||||
byte,
|
||||
buf,
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes and appends them into `buf` until a newline (the 0xA byte) is
|
||||
reached.
|
||||
|
||||
This function will read bytes from the underlying stream until the newline
|
||||
delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and
|
||||
including, the delimiter (if found) will be appended to `buf`.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
If this function returns `Ok(0)`, the stream has reached EOF.
|
||||
|
||||
# Errors
|
||||
|
||||
This function has the same error semantics as [`read_until`] and will also return
|
||||
an error if the read bytes are not valid UTF-8. If an I/O error is encountered then
|
||||
`buf` may contain some bytes already read in the event that all data read so far
|
||||
was valid UTF-8.
|
||||
|
||||
[`read_until`]: #method.read_until
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = BufReader::new(File::open("a.txt").await?);
|
||||
|
||||
let mut buf = String::new();
|
||||
file.read_line(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_line<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut String,
|
||||
) -> ReadLineFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadLineFuture {
|
||||
reader: self,
|
||||
bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
|
||||
buf,
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Returns a stream over the lines of this byte stream.
|
||||
|
||||
The stream returned from this function will yield instances of
|
||||
[`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline byte
|
||||
(the 0xA byte) or CRLF (0xD, 0xA bytes) at the end.
|
||||
|
||||
[`io::Result`]: type.Result.html
|
||||
[`String`]: https://doc.rust-lang.org/std/string/struct.String.html
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::BufReader;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let file = File::open("a.txt").await?;
|
||||
let mut lines = BufReader::new(file).lines();
|
||||
let mut count = 0;
|
||||
|
||||
while let Some(line) = lines.next().await {
|
||||
line?;
|
||||
count += 1;
|
||||
}
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn lines(self) -> Lines<Self>
|
||||
where
|
||||
Self: Unpin + Sized,
|
||||
{
|
||||
Lines {
|
||||
reader: self,
|
||||
buf: String::new(),
|
||||
bytes: Vec::new(),
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Returns a stream over the contents of this reader split on the byte `byte`.
|
||||
|
||||
The stream returned from this function will return instances of
|
||||
[`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
|
||||
the delimiter byte at the end.
|
||||
|
||||
This function will yield errors whenever [`read_until`] would have
|
||||
also yielded an error.
|
||||
|
||||
[`io::Result`]: type.Result.html
|
||||
[`Vec<u8>`]: ../vec/struct.Vec.html
|
||||
[`read_until`]: #method.read_until
|
||||
|
||||
# Examples
|
||||
|
||||
[`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
|
||||
this example, we use [`Cursor`] to iterate over all hyphen delimited
|
||||
segments in a byte slice
|
||||
|
||||
[`Cursor`]: struct.Cursor.html
|
||||
|
||||
```
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::io;
|
||||
|
||||
let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
|
||||
|
||||
let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
|
||||
assert_eq!(split_iter.next().await, Some(b"lorem".to_vec()));
|
||||
assert_eq!(split_iter.next().await, Some(b"ipsum".to_vec()));
|
||||
assert_eq!(split_iter.next().await, Some(b"dolor".to_vec()));
|
||||
assert_eq!(split_iter.next().await, None);
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn split(self, byte: u8) -> Split<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Split {
|
||||
reader: self,
|
||||
buf: Vec::new(),
|
||||
delim: byte,
|
||||
read: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: BufRead + ?Sized> BufReadExt for T {}
|
||||
|
||||
pub fn read_until_internal<R: BufReadExt + ?Sized>(
|
||||
|
|
|
@ -23,356 +23,356 @@ pub use take::Take;
|
|||
|
||||
pub use futures_io::AsyncRead as Read;
|
||||
|
||||
#[doc = r#"
|
||||
Extension methods for [`Read`].
|
||||
|
||||
[`Read`]: ../trait.Read.html
|
||||
"#]
|
||||
pub trait ReadExt: Read {
|
||||
#[doc = r#"
|
||||
Extension methods for [`Read`].
|
||||
Reads some bytes from the byte stream.
|
||||
|
||||
[`Read`]: ../trait.Read.html
|
||||
Returns the number of bytes read from the start of the buffer.
|
||||
|
||||
If the return value is `Ok(n)`, then it must be guaranteed that
|
||||
`0 <= n <= buf.len()`. A nonzero `n` value indicates that the buffer has been
|
||||
filled in with `n` bytes of data. If `n` is `0`, then it can indicate one of two
|
||||
scenarios:
|
||||
|
||||
1. This reader has reached its "end of file" and will likely no longer be able to
|
||||
produce bytes. Note that this does not mean that the reader will always no
|
||||
longer be able to produce bytes.
|
||||
2. The buffer specified was 0 bytes in length.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = vec![0; 1024];
|
||||
let n = file.read(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
pub trait ReadExt: Read {
|
||||
#[doc = r#"
|
||||
Reads some bytes from the byte stream.
|
||||
|
||||
Returns the number of bytes read from the start of the buffer.
|
||||
|
||||
If the return value is `Ok(n)`, then it must be guaranteed that
|
||||
`0 <= n <= buf.len()`. A nonzero `n` value indicates that the buffer has been
|
||||
filled in with `n` bytes of data. If `n` is `0`, then it can indicate one of two
|
||||
scenarios:
|
||||
|
||||
1. This reader has reached its "end of file" and will likely no longer be able to
|
||||
produce bytes. Note that this does not mean that the reader will always no
|
||||
longer be able to produce bytes.
|
||||
2. The buffer specified was 0 bytes in length.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = vec![0; 1024];
|
||||
let n = file.read(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut [u8],
|
||||
) -> ReadFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin
|
||||
{
|
||||
ReadFuture { reader: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Like [`read`], except that it reads into a slice of buffers.
|
||||
|
||||
Data is copied to fill each buffer in order, with the final buffer written to
|
||||
possibly being only partially filled. This method must behave as a single call to
|
||||
[`read`] with the buffers concatenated would.
|
||||
|
||||
The default implementation calls [`read`] with either the first nonempty buffer
|
||||
provided, or an empty one if none exists.
|
||||
|
||||
[`read`]: #tymethod.read
|
||||
"#]
|
||||
fn read_vectored<'a>(
|
||||
&'a mut self,
|
||||
bufs: &'a mut [IoSliceMut<'a>],
|
||||
) -> ReadVectoredFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadVectoredFuture { reader: self, bufs }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes from the byte stream.
|
||||
|
||||
All bytes read from this stream will be appended to the specified buffer `buf`.
|
||||
This function will continuously call [`read`] to append more data to `buf` until
|
||||
[`read`] returns either `Ok(0)` or an error.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
[`read`]: #tymethod.read
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_to_end<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut Vec<u8>,
|
||||
) -> ReadToEndFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
let start_len = buf.len();
|
||||
ReadToEndFuture {
|
||||
reader: self,
|
||||
buf,
|
||||
start_len,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes from the byte stream and appends them into a string.
|
||||
|
||||
If successful, this function will return the number of bytes read.
|
||||
|
||||
If the data in this stream is not valid UTF-8 then an error will be returned and
|
||||
`buf` will be left unmodified.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = String::new();
|
||||
file.read_to_string(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_to_string<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut String,
|
||||
) -> ReadToStringFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
let start_len = buf.len();
|
||||
ReadToStringFuture {
|
||||
reader: self,
|
||||
bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
|
||||
buf,
|
||||
start_len,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads the exact number of bytes required to fill `buf`.
|
||||
|
||||
This function reads as many bytes as necessary to completely fill the specified
|
||||
buffer `buf`.
|
||||
|
||||
No guarantees are provided about the contents of `buf` when this function is
|
||||
called, implementations cannot rely on any property of the contents of `buf` being
|
||||
true. It is recommended that implementations only write data to `buf` instead of
|
||||
reading its contents.
|
||||
|
||||
If this function encounters an "end of file" before completely filling the buffer,
|
||||
it returns an error of the kind [`ErrorKind::UnexpectedEof`]. The contents of
|
||||
`buf` are unspecified in this case.
|
||||
|
||||
If any other read error is encountered then this function immediately returns. The
|
||||
contents of `buf` are unspecified in this case.
|
||||
|
||||
If this function returns an error, it is unspecified how many bytes it has read,
|
||||
but it will never read more than would be necessary to completely fill the buffer.
|
||||
|
||||
[`ErrorKind::UnexpectedEof`]: enum.ErrorKind.html#variant.UnexpectedEof
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = vec![0; 10];
|
||||
file.read_exact(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_exact<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut [u8],
|
||||
) -> ReadExactFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadExactFuture { reader: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates an adaptor which will read at most `limit` bytes from it.
|
||||
|
||||
This function returns a new instance of `Read` which will read at most
|
||||
`limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
|
||||
read errors will not count towards the number of bytes read and future
|
||||
calls to [`read`] may succeed.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`]s implement `Read`:
|
||||
|
||||
[`File`]: ../fs/struct.File.html
|
||||
[`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
|
||||
[`read`]: tymethod.read
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f = File::open("foo.txt").await?;
|
||||
let mut buffer = [0; 5];
|
||||
|
||||
// read at most five bytes
|
||||
let mut handle = f.take(5);
|
||||
|
||||
handle.read(&mut buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn take(self, limit: u64) -> Take<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Take { inner: self, limit }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates a "by reference" adaptor for this instance of `Read`.
|
||||
|
||||
The returned adaptor also implements `Read` and will simply borrow this
|
||||
current reader.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let mut f = File::open("foo.txt").await?;
|
||||
let mut buffer = Vec::new();
|
||||
let mut other_buffer = Vec::new();
|
||||
|
||||
{
|
||||
let reference = f.by_ref();
|
||||
|
||||
// read at most 5 bytes
|
||||
reference.take(5).read_to_end(&mut buffer).await?;
|
||||
|
||||
} // drop our &mut reference so we can use f again
|
||||
|
||||
// original file still usable, read the rest
|
||||
f.read_to_end(&mut other_buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
|
||||
|
||||
|
||||
#[doc = r#"
|
||||
Transforms this `Read` instance to a `Stream` over its bytes.
|
||||
|
||||
The returned type implements `Stream` where the `Item` is
|
||||
`Result<u8, io::Error>`.
|
||||
The yielded item is `Ok` if a byte was successfully read and `Err`
|
||||
otherwise. EOF is mapped to returning `None` from this iterator.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f = File::open("foo.txt").await?;
|
||||
let mut s = f.bytes();
|
||||
|
||||
while let Some(byte) = s.next().await {
|
||||
println!("{}", byte.unwrap());
|
||||
}
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn bytes(self) -> Bytes<Self> where Self: Sized {
|
||||
Bytes { inner: self }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates an adaptor which will chain this stream with another.
|
||||
|
||||
The returned `Read` instance will first read all bytes from this object
|
||||
until EOF is encountered. Afterwards the output is equivalent to the
|
||||
output of `next`.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f1 = File::open("foo.txt").await?;
|
||||
let f2 = File::open("bar.txt").await?;
|
||||
|
||||
let mut handle = f1.chain(f2);
|
||||
let mut buffer = String::new();
|
||||
|
||||
// read the value into a String. We could use any Read method here,
|
||||
// this is just one example.
|
||||
handle.read_to_string(&mut buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
|
||||
Chain { first: self, second: next, done_first: false }
|
||||
fn read<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut [u8],
|
||||
) -> ReadFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin
|
||||
{
|
||||
ReadFuture { reader: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Like [`read`], except that it reads into a slice of buffers.
|
||||
|
||||
Data is copied to fill each buffer in order, with the final buffer written to
|
||||
possibly being only partially filled. This method must behave as a single call to
|
||||
[`read`] with the buffers concatenated would.
|
||||
|
||||
The default implementation calls [`read`] with either the first nonempty buffer
|
||||
provided, or an empty one if none exists.
|
||||
|
||||
[`read`]: #tymethod.read
|
||||
"#]
|
||||
fn read_vectored<'a>(
|
||||
&'a mut self,
|
||||
bufs: &'a mut [IoSliceMut<'a>],
|
||||
) -> ReadVectoredFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadVectoredFuture { reader: self, bufs }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes from the byte stream.
|
||||
|
||||
All bytes read from this stream will be appended to the specified buffer `buf`.
|
||||
This function will continuously call [`read`] to append more data to `buf` until
|
||||
[`read`] returns either `Ok(0)` or an error.
|
||||
|
||||
If successful, this function will return the total number of bytes read.
|
||||
|
||||
[`read`]: #tymethod.read
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_to_end<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut Vec<u8>,
|
||||
) -> ReadToEndFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
let start_len = buf.len();
|
||||
ReadToEndFuture {
|
||||
reader: self,
|
||||
buf,
|
||||
start_len,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads all bytes from the byte stream and appends them into a string.
|
||||
|
||||
If successful, this function will return the number of bytes read.
|
||||
|
||||
If the data in this stream is not valid UTF-8 then an error will be returned and
|
||||
`buf` will be left unmodified.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = String::new();
|
||||
file.read_to_string(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_to_string<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut String,
|
||||
) -> ReadToStringFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
let start_len = buf.len();
|
||||
ReadToStringFuture {
|
||||
reader: self,
|
||||
bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
|
||||
buf,
|
||||
start_len,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Reads the exact number of bytes required to fill `buf`.
|
||||
|
||||
This function reads as many bytes as necessary to completely fill the specified
|
||||
buffer `buf`.
|
||||
|
||||
No guarantees are provided about the contents of `buf` when this function is
|
||||
called, implementations cannot rely on any property of the contents of `buf` being
|
||||
true. It is recommended that implementations only write data to `buf` instead of
|
||||
reading its contents.
|
||||
|
||||
If this function encounters an "end of file" before completely filling the buffer,
|
||||
it returns an error of the kind [`ErrorKind::UnexpectedEof`]. The contents of
|
||||
`buf` are unspecified in this case.
|
||||
|
||||
If any other read error is encountered then this function immediately returns. The
|
||||
contents of `buf` are unspecified in this case.
|
||||
|
||||
If this function returns an error, it is unspecified how many bytes it has read,
|
||||
but it will never read more than would be necessary to completely fill the buffer.
|
||||
|
||||
[`ErrorKind::UnexpectedEof`]: enum.ErrorKind.html#variant.UnexpectedEof
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let mut buf = vec![0; 10];
|
||||
file.read_exact(&mut buf).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn read_exact<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a mut [u8],
|
||||
) -> ReadExactFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
ReadExactFuture { reader: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates an adaptor which will read at most `limit` bytes from it.
|
||||
|
||||
This function returns a new instance of `Read` which will read at most
|
||||
`limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
|
||||
read errors will not count towards the number of bytes read and future
|
||||
calls to [`read`] may succeed.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`]s implement `Read`:
|
||||
|
||||
[`File`]: ../fs/struct.File.html
|
||||
[`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
|
||||
[`read`]: tymethod.read
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f = File::open("foo.txt").await?;
|
||||
let mut buffer = [0; 5];
|
||||
|
||||
// read at most five bytes
|
||||
let mut handle = f.take(5);
|
||||
|
||||
handle.read(&mut buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn take(self, limit: u64) -> Take<Self>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Take { inner: self, limit }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates a "by reference" adaptor for this instance of `Read`.
|
||||
|
||||
The returned adaptor also implements `Read` and will simply borrow this
|
||||
current reader.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let mut f = File::open("foo.txt").await?;
|
||||
let mut buffer = Vec::new();
|
||||
let mut other_buffer = Vec::new();
|
||||
|
||||
{
|
||||
let reference = f.by_ref();
|
||||
|
||||
// read at most 5 bytes
|
||||
reference.take(5).read_to_end(&mut buffer).await?;
|
||||
|
||||
} // drop our &mut reference so we can use f again
|
||||
|
||||
// original file still usable, read the rest
|
||||
f.read_to_end(&mut other_buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
|
||||
|
||||
|
||||
#[doc = r#"
|
||||
Transforms this `Read` instance to a `Stream` over its bytes.
|
||||
|
||||
The returned type implements `Stream` where the `Item` is
|
||||
`Result<u8, io::Error>`.
|
||||
The yielded item is `Ok` if a byte was successfully read and `Err`
|
||||
otherwise. EOF is mapped to returning `None` from this iterator.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f = File::open("foo.txt").await?;
|
||||
let mut s = f.bytes();
|
||||
|
||||
while let Some(byte) = s.next().await {
|
||||
println!("{}", byte.unwrap());
|
||||
}
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn bytes(self) -> Bytes<Self> where Self: Sized {
|
||||
Bytes { inner: self }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Creates an adaptor which will chain this stream with another.
|
||||
|
||||
The returned `Read` instance will first read all bytes from this object
|
||||
until EOF is encountered. Afterwards the output is equivalent to the
|
||||
output of `next`.
|
||||
|
||||
# Examples
|
||||
|
||||
[`File`][file]s implement `Read`:
|
||||
|
||||
[file]: ../fs/struct.File.html
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let f1 = File::open("foo.txt").await?;
|
||||
let f2 = File::open("bar.txt").await?;
|
||||
|
||||
let mut handle = f1.chain(f2);
|
||||
let mut buffer = String::new();
|
||||
|
||||
// read the value into a String. We could use any Read method here,
|
||||
// this is just one example.
|
||||
handle.read_to_string(&mut buffer).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn chain<R: Read>(self, next: R) -> Chain<Self, R> where Self: Sized {
|
||||
Chain { first: self, second: next, done_first: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Read + ?Sized> ReadExt for T {}
|
||||
|
||||
/// Initializes a buffer if necessary.
|
||||
|
|
|
@ -6,45 +6,45 @@ use crate::io::SeekFrom;
|
|||
|
||||
pub use futures_io::AsyncSeek as Seek;
|
||||
|
||||
#[doc = r#"
|
||||
Extension methods for [`Seek`].
|
||||
|
||||
[`Seek`]: ../trait.Seek.html
|
||||
"#]
|
||||
pub trait SeekExt: Seek {
|
||||
#[doc = r#"
|
||||
Extension methods for [`Seek`].
|
||||
Seeks to a new position in a byte stream.
|
||||
|
||||
[`Seek`]: ../trait.Seek.html
|
||||
Returns the new position in the byte stream.
|
||||
|
||||
A seek beyond the end of stream is allowed, but behavior is defined by the
|
||||
implementation.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::SeekFrom;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let file_len = file.seek(SeekFrom::End(0)).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
pub trait SeekExt: Seek {
|
||||
#[doc = r#"
|
||||
Seeks to a new position in a byte stream.
|
||||
|
||||
Returns the new position in the byte stream.
|
||||
|
||||
A seek beyond the end of stream is allowed, but behavior is defined by the
|
||||
implementation.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::fs::File;
|
||||
use async_std::io::SeekFrom;
|
||||
use async_std::prelude::*;
|
||||
|
||||
let mut file = File::open("a.txt").await?;
|
||||
|
||||
let file_len = file.seek(SeekFrom::End(0)).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn seek(
|
||||
&mut self,
|
||||
pos: SeekFrom,
|
||||
) -> SeekFuture<'_, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
SeekFuture { seeker: self, pos }
|
||||
}
|
||||
fn seek(
|
||||
&mut self,
|
||||
pos: SeekFrom,
|
||||
) -> SeekFuture<'_, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
SeekFuture { seeker: self, pos }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Seek + ?Sized> SeekExt for T {}
|
||||
|
|
|
@ -14,174 +14,174 @@ use crate::io::{self, IoSlice};
|
|||
|
||||
pub use futures_io::AsyncWrite as Write;
|
||||
|
||||
#[doc = r#"
|
||||
Extension methods for [`Write`].
|
||||
|
||||
[`Write`]: ../trait.Write.html
|
||||
"#]
|
||||
pub trait WriteExt: Write {
|
||||
#[doc = r#"
|
||||
Extension methods for [`Write`].
|
||||
Writes some bytes into the byte stream.
|
||||
|
||||
[`Write`]: ../trait.Write.html
|
||||
Returns the number of bytes written from the start of the buffer.
|
||||
|
||||
If the return value is `Ok(n)` then it must be guaranteed that
|
||||
`0 <= n <= buf.len()`. A return value of `0` typically means that the underlying
|
||||
object is no longer able to accept bytes and will likely not be able to in the
|
||||
future as well, or that the buffer provided is empty.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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 n = file.write(b"hello world").await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
pub trait WriteExt: Write {
|
||||
#[doc = r#"
|
||||
Writes some bytes into the byte stream.
|
||||
|
||||
Returns the number of bytes written from the start of the buffer.
|
||||
|
||||
If the return value is `Ok(n)` then it must be guaranteed that
|
||||
`0 <= n <= buf.len()`. A return value of `0` typically means that the underlying
|
||||
object is no longer able to accept bytes and will likely not be able to in the
|
||||
future as well, or that the buffer provided is empty.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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 n = file.write(b"hello world").await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn write<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a [u8],
|
||||
) -> WriteFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteFuture { writer: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Flushes the stream to ensure that all buffered contents reach their destination.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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?;
|
||||
|
||||
file.write_all(b"hello world").await?;
|
||||
file.flush().await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn flush(&mut self) -> FlushFuture<'_, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
FlushFuture { writer: self }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Like [`write`], except that it writes from a slice of buffers.
|
||||
|
||||
Data is copied from each buffer in order, with the final buffer read from possibly
|
||||
being only partially consumed. This method must behave as a call to [`write`] with
|
||||
the buffers concatenated would.
|
||||
|
||||
The default implementation calls [`write`] with either the first nonempty buffer
|
||||
provided, or an empty one if none exists.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
"#]
|
||||
fn write_vectored<'a>(
|
||||
&'a mut self,
|
||||
bufs: &'a [IoSlice<'a>],
|
||||
) -> WriteVectoredFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteVectoredFuture { writer: self, bufs }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Writes an entire buffer into the byte stream.
|
||||
|
||||
This method will continuously call [`write`] until there is no more data to be
|
||||
written or an error is returned. This method will not return until the entire
|
||||
buffer has been successfully written or such an error occurs.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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?;
|
||||
|
||||
file.write_all(b"hello world").await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
"#]
|
||||
fn write_all<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a [u8],
|
||||
) -> WriteAllFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteAllFuture { writer: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Writes a formatted string into this writer, returning any error encountered.
|
||||
|
||||
This method will continuously call [`write`] until there is no more data to be
|
||||
written or an error is returned. This future will not resolve until the entire
|
||||
buffer has been successfully written or such an error occurs.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let mut buffer = File::create("foo.txt").await?;
|
||||
|
||||
// this call
|
||||
write!(buffer, "{:.*}", 2, 1.234567).await?;
|
||||
// turns into this:
|
||||
buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn write_fmt<'a>(
|
||||
&'a mut self,
|
||||
fmt: std::fmt::Arguments<'_>,
|
||||
) -> WriteFmtFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
// In order to not have to implement an async version of `fmt` including private types
|
||||
// and all, we convert `Arguments` to a `Result<Vec<u8>>` and pass that to the Future.
|
||||
// Doing an owned conversion saves us from juggling references.
|
||||
let mut string = String::new();
|
||||
let res = std::fmt::write(&mut string, fmt)
|
||||
.map(|_| string.into_bytes())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::Other, "formatter error"));
|
||||
WriteFmtFuture { writer: self, res: Some(res), buffer: None, amt: 0 }
|
||||
}
|
||||
fn write<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a [u8],
|
||||
) -> WriteFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteFuture { writer: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Flushes the stream to ensure that all buffered contents reach their destination.
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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?;
|
||||
|
||||
file.write_all(b"hello world").await?;
|
||||
file.flush().await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn flush(&mut self) -> FlushFuture<'_, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
FlushFuture { writer: self }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Like [`write`], except that it writes from a slice of buffers.
|
||||
|
||||
Data is copied from each buffer in order, with the final buffer read from possibly
|
||||
being only partially consumed. This method must behave as a call to [`write`] with
|
||||
the buffers concatenated would.
|
||||
|
||||
The default implementation calls [`write`] with either the first nonempty buffer
|
||||
provided, or an empty one if none exists.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
"#]
|
||||
fn write_vectored<'a>(
|
||||
&'a mut self,
|
||||
bufs: &'a [IoSlice<'a>],
|
||||
) -> WriteVectoredFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteVectoredFuture { writer: self, bufs }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Writes an entire buffer into the byte stream.
|
||||
|
||||
This method will continuously call [`write`] until there is no more data to be
|
||||
written or an error is returned. This method will not return until the entire
|
||||
buffer has been successfully written or such an error occurs.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# 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?;
|
||||
|
||||
file.write_all(b"hello world").await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
"#]
|
||||
fn write_all<'a>(
|
||||
&'a mut self,
|
||||
buf: &'a [u8],
|
||||
) -> WriteAllFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
WriteAllFuture { writer: self, buf }
|
||||
}
|
||||
|
||||
#[doc = r#"
|
||||
Writes a formatted string into this writer, returning any error encountered.
|
||||
|
||||
This method will continuously call [`write`] until there is no more data to be
|
||||
written or an error is returned. This future will not resolve until the entire
|
||||
buffer has been successfully written or such an error occurs.
|
||||
|
||||
[`write`]: #tymethod.write
|
||||
|
||||
# Examples
|
||||
|
||||
```no_run
|
||||
# fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
#
|
||||
use async_std::io::prelude::*;
|
||||
use async_std::fs::File;
|
||||
|
||||
let mut buffer = File::create("foo.txt").await?;
|
||||
|
||||
// this call
|
||||
write!(buffer, "{:.*}", 2, 1.234567).await?;
|
||||
// turns into this:
|
||||
buffer.write_fmt(format_args!("{:.*}", 2, 1.234567)).await?;
|
||||
#
|
||||
# Ok(()) }) }
|
||||
```
|
||||
"#]
|
||||
fn write_fmt<'a>(
|
||||
&'a mut self,
|
||||
fmt: std::fmt::Arguments<'_>,
|
||||
) -> WriteFmtFuture<'a, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
// In order to not have to implement an async version of `fmt` including private types
|
||||
// and all, we convert `Arguments` to a `Result<Vec<u8>>` and pass that to the Future.
|
||||
// Doing an owned conversion saves us from juggling references.
|
||||
let mut string = String::new();
|
||||
let res = std::fmt::write(&mut string, fmt)
|
||||
.map(|_| string.into_bytes())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::Other, "formatter error"));
|
||||
WriteFmtFuture { writer: self, res: Some(res), buffer: None, amt: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Write + ?Sized> WriteExt for T {}
|
||||
|
|
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue