forked from mirror/async-std
Revert "Stabilize most stream method and remove unnecessary macros"
parent
61f9483cc5
commit
cc19592f80
@ -0,0 +1,261 @@
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
use std::future::Future;
|
||||
|
||||
use crate::io::{self, Write};
|
||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||
|
||||
cfg_unstable! {
|
||||
use once_cell::sync::Lazy;
|
||||
use std::io::Write as _;
|
||||
}
|
||||
|
||||
/// Constructs a new handle to the standard error of the current process.
|
||||
///
|
||||
/// This function is an async version of [`std::io::stderr`].
|
||||
///
|
||||
/// [`std::io::stderr`]: https://doc.rust-lang.org/std/io/fn.stderr.html
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let mut stderr = io::stderr();
|
||||
/// stderr.write_all(b"Hello, world!").await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
pub fn stderr() -> Stderr {
|
||||
Stderr(Mutex::new(State::Idle(Some(Inner {
|
||||
stderr: std::io::stderr(),
|
||||
buf: Vec::new(),
|
||||
last_op: None,
|
||||
}))))
|
||||
}
|
||||
|
||||
/// A handle to the standard error of the current process.
|
||||
///
|
||||
/// This writer is created by the [`stderr`] function. See its documentation for
|
||||
/// more.
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// [`stderr`]: fn.stderr.html
|
||||
#[derive(Debug)]
|
||||
pub struct Stderr(Mutex<State>);
|
||||
|
||||
/// A locked reference to the Stderr handle.
|
||||
///
|
||||
/// This handle implements the [`Write`] traits, and is constructed via the [`Stderr::lock`]
|
||||
/// method.
|
||||
///
|
||||
/// [`Write`]: trait.Read.html
|
||||
/// [`Stderr::lock`]: struct.Stderr.html#method.lock
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[derive(Debug)]
|
||||
pub struct StderrLock<'a>(std::io::StderrLock<'a>);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
unsafe impl Send for StderrLock<'_> {}
|
||||
|
||||
/// The state of the asynchronous stderr.
|
||||
///
|
||||
/// The stderr can be either idle or busy performing an asynchronous operation.
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
/// The stderr is idle.
|
||||
Idle(Option<Inner>),
|
||||
|
||||
/// The stderr is blocked on an asynchronous operation.
|
||||
///
|
||||
/// Awaiting this operation will result in the new state of the stderr.
|
||||
Busy(JoinHandle<State>),
|
||||
}
|
||||
|
||||
/// Inner representation of the asynchronous stderr.
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
/// The blocking stderr handle.
|
||||
stderr: std::io::Stderr,
|
||||
|
||||
/// The write buffer.
|
||||
buf: Vec<u8>,
|
||||
|
||||
/// The result of the last asynchronous operation on the stderr.
|
||||
last_op: Option<Operation>,
|
||||
}
|
||||
|
||||
/// Possible results of an asynchronous operation on the stderr.
|
||||
#[derive(Debug)]
|
||||
enum Operation {
|
||||
Write(io::Result<usize>),
|
||||
Flush(io::Result<()>),
|
||||
}
|
||||
|
||||
impl Stderr {
|
||||
/// Locks this handle to the standard error stream, returning a writable guard.
|
||||
///
|
||||
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Write trait for writing data.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let stderr = io::stderr();
|
||||
/// let mut handle = stderr.lock().await;
|
||||
///
|
||||
/// handle.write_all(b"hello world").await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
pub async fn lock(&self) -> StderrLock<'static> {
|
||||
static STDERR: Lazy<std::io::Stderr> = Lazy::new(std::io::stderr);
|
||||
|
||||
spawn_blocking(move || StderrLock(STDERR.lock())).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Stderr {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::Write(res)) = inner.last_op.take() {
|
||||
let n = res?;
|
||||
|
||||
// If more data was written than is available in the buffer, let's retry
|
||||
// the write operation.
|
||||
if n <= buf.len() {
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Set the length of the inner buffer to the length of the provided buffer.
|
||||
if inner.buf.len() < buf.len() {
|
||||
inner.buf.reserve(buf.len() - inner.buf.len());
|
||||
}
|
||||
unsafe {
|
||||
inner.buf.set_len(buf.len());
|
||||
}
|
||||
|
||||
// Copy the data to write into the inner buffer.
|
||||
inner.buf[..buf.len()].copy_from_slice(buf);
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
let res = std::io::Write::write(&mut inner.stderr, &inner.buf);
|
||||
inner.last_op = Some(Operation::Write(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stderr is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::Flush(res)) = inner.last_op.take() {
|
||||
return Poll::Ready(res);
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
let res = std::io::Write::flush(&mut inner.stderr);
|
||||
inner.last_op = Some(Operation::Flush(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stderr is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_flush(cx)
|
||||
}
|
||||
}
|
||||
|
||||
cfg_unix! {
|
||||
use crate::os::unix::io::{AsRawFd, RawFd};
|
||||
|
||||
impl AsRawFd for Stderr {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
std::io::stderr().as_raw_fd()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg_windows! {
|
||||
use crate::os::windows::io::{AsRawHandle, RawHandle};
|
||||
|
||||
impl AsRawHandle for Stderr {
|
||||
fn as_raw_handle(&self) -> RawHandle {
|
||||
std::io::stderr().as_raw_handle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
impl io::Write for StderrLock<'_> {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Poll::Ready(self.0.write(buf))
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(self.0.flush())
|
||||
}
|
||||
|
||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_flush(cx)
|
||||
}
|
||||
}
|
@ -0,0 +1,279 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::future;
|
||||
use crate::io::{self, Read};
|
||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||
use crate::utils::Context as _;
|
||||
|
||||
cfg_unstable! {
|
||||
use once_cell::sync::Lazy;
|
||||
use std::io::Read as _;
|
||||
}
|
||||
|
||||
/// Constructs a new handle to the standard input of the current process.
|
||||
///
|
||||
/// This function is an async version of [`std::io::stdin`].
|
||||
///
|
||||
/// [`std::io::stdin`]: https://doc.rust-lang.org/std/io/fn.stdin.html
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
///
|
||||
/// let stdin = io::stdin();
|
||||
/// let mut line = String::new();
|
||||
/// stdin.read_line(&mut line).await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
pub fn stdin() -> Stdin {
|
||||
Stdin(Mutex::new(State::Idle(Some(Inner {
|
||||
stdin: std::io::stdin(),
|
||||
line: String::new(),
|
||||
buf: Vec::new(),
|
||||
last_op: None,
|
||||
}))))
|
||||
}
|
||||
|
||||
/// A handle to the standard input of the current process.
|
||||
///
|
||||
/// This reader is created by the [`stdin`] function. See its documentation for
|
||||
/// more.
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// [`stdin`]: fn.stdin.html
|
||||
#[derive(Debug)]
|
||||
pub struct Stdin(Mutex<State>);
|
||||
|
||||
/// A locked reference to the Stdin handle.
|
||||
///
|
||||
/// This handle implements the [`Read`] traits, and is constructed via the [`Stdin::lock`] method.
|
||||
///
|
||||
/// [`Read`]: trait.Read.html
|
||||
/// [`Stdin::lock`]: struct.Stdin.html#method.lock
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[cfg(feature = "unstable")]
|
||||
#[derive(Debug)]
|
||||
pub struct StdinLock<'a>(std::io::StdinLock<'a>);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
unsafe impl Send for StdinLock<'_> {}
|
||||
|
||||
/// The state of the asynchronous stdin.
|
||||
///
|
||||
/// The stdin can be either idle or busy performing an asynchronous operation.
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
/// The stdin is idle.
|
||||
Idle(Option<Inner>),
|
||||
|
||||
/// The stdin is blocked on an asynchronous operation.
|
||||
///
|
||||
/// Awaiting this operation will result in the new state of the stdin.
|
||||
Busy(JoinHandle<State>),
|
||||
}
|
||||
|
||||
/// Inner representation of the asynchronous stdin.
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
/// The blocking stdin handle.
|
||||
stdin: std::io::Stdin,
|
||||
|
||||
/// The line buffer.
|
||||
line: String,
|
||||
|
||||
/// The write buffer.
|
||||
buf: Vec<u8>,
|
||||
|
||||
/// The result of the last asynchronous operation on the stdin.
|
||||
last_op: Option<Operation>,
|
||||
}
|
||||
|
||||
/// Possible results of an asynchronous operation on the stdin.
|
||||
#[derive(Debug)]
|
||||
enum Operation {
|
||||
ReadLine(io::Result<usize>),
|
||||
Read(io::Result<usize>),
|
||||
}
|
||||
|
||||
impl Stdin {
|
||||
/// Reads a line of input into the specified buffer.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
///
|
||||
/// let stdin = io::stdin();
|
||||
/// let mut line = String::new();
|
||||
/// stdin.read_line(&mut line).await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
pub async fn read_line(&self, buf: &mut String) -> io::Result<usize> {
|
||||
future::poll_fn(|cx| {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::ReadLine(res)) = inner.last_op.take() {
|
||||
let n = res?;
|
||||
|
||||
// Copy the read data into the buffer and return.
|
||||
buf.push_str(&inner.line);
|
||||
return Poll::Ready(Ok(n));
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
inner.line.clear();
|
||||
let res = inner.stdin.read_line(&mut inner.line);
|
||||
inner.last_op = Some(Operation::ReadLine(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stdin is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.context(|| String::from("could not read line on stdin"))
|
||||
}
|
||||
|
||||
/// Locks this handle to the standard input stream, returning a readable guard.
|
||||
///
|
||||
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Read trait for accessing the underlying data.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let mut buffer = String::new();
|
||||
///
|
||||
/// let stdin = io::stdin();
|
||||
/// let mut handle = stdin.lock().await;
|
||||
///
|
||||
/// handle.read_to_string(&mut buffer).await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
pub async fn lock(&self) -> StdinLock<'static> {
|
||||
static STDIN: Lazy<std::io::Stdin> = Lazy::new(std::io::stdin);
|
||||
|
||||
spawn_blocking(move || StdinLock(STDIN.lock())).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for Stdin {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::Read(res)) = inner.last_op.take() {
|
||||
let n = res?;
|
||||
|
||||
// If more data was read than fits into the buffer, let's retry the read
|
||||
// operation.
|
||||
if n <= buf.len() {
|
||||
// Copy the read data into the buffer and return.
|
||||
buf[..n].copy_from_slice(&inner.buf[..n]);
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Set the length of the inner buffer to the length of the provided buffer.
|
||||
if inner.buf.len() < buf.len() {
|
||||
inner.buf.reserve(buf.len() - inner.buf.len());
|
||||
}
|
||||
unsafe {
|
||||
inner.buf.set_len(buf.len());
|
||||
}
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
let res = std::io::Read::read(&mut inner.stdin, &mut inner.buf);
|
||||
inner.last_op = Some(Operation::Read(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stdin is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg_unix! {
|
||||
use crate::os::unix::io::{AsRawFd, RawFd};
|
||||
|
||||
impl AsRawFd for Stdin {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
std::io::stdin().as_raw_fd()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg_windows! {
|
||||
use crate::os::windows::io::{AsRawHandle, RawHandle};
|
||||
|
||||
impl AsRawHandle for Stdin {
|
||||
fn as_raw_handle(&self) -> RawHandle {
|
||||
std::io::stdin().as_raw_handle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
impl Read for StdinLock<'_> {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Poll::Ready(self.0.read(buf))
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
//! Internal types for stdio.
|
||||
//!
|
||||
//! This module is a port of `libstd/io/stdio.rs`,and contains internal types for `print`/`eprint`.
|
||||
|
||||
use crate::io::{stderr, stdout};
|
||||
use crate::prelude::*;
|
||||
use std::fmt;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub async fn _print(args: fmt::Arguments<'_>) {
|
||||
if let Err(e) = stdout().write_fmt(args).await {
|
||||
panic!("failed printing to stdout: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub async fn _eprint(args: fmt::Arguments<'_>) {
|
||||
if let Err(e) = stderr().write_fmt(args).await {
|
||||
panic!("failed printing to stderr: {}", e);
|
||||
}
|
||||
}
|
@ -0,0 +1,261 @@
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
use std::future::Future;
|
||||
|
||||
use crate::io::{self, Write};
|
||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||
|
||||
cfg_unstable! {
|
||||
use once_cell::sync::Lazy;
|
||||
use std::io::Write as _;
|
||||
}
|
||||
|
||||
/// Constructs a new handle to the standard output of the current process.
|
||||
///
|
||||
/// This function is an async version of [`std::io::stdout`].
|
||||
///
|
||||
/// [`std::io::stdout`]: https://doc.rust-lang.org/std/io/fn.stdout.html
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let mut stdout = io::stdout();
|
||||
/// stdout.write_all(b"Hello, world!").await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
pub fn stdout() -> Stdout {
|
||||
Stdout(Mutex::new(State::Idle(Some(Inner {
|
||||
stdout: std::io::stdout(),
|
||||
buf: Vec::new(),
|
||||
last_op: None,
|
||||
}))))
|
||||
}
|
||||
|
||||
/// A handle to the standard output of the current process.
|
||||
///
|
||||
/// This writer is created by the [`stdout`] function. See its documentation
|
||||
/// for more.
|
||||
///
|
||||
/// ### Note: Windows Portability Consideration
|
||||
///
|
||||
/// When operating in a console, the Windows implementation of this stream does not support
|
||||
/// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
|
||||
/// an error.
|
||||
///
|
||||
/// [`stdout`]: fn.stdout.html
|
||||
#[derive(Debug)]
|
||||
pub struct Stdout(Mutex<State>);
|
||||
|
||||
/// A locked reference to the Stderr handle.
|
||||
///
|
||||
/// This handle implements the [`Write`] traits, and is constructed via the [`Stdout::lock`]
|
||||
/// method.
|
||||
///
|
||||
/// [`Write`]: trait.Read.html
|
||||
/// [`Stdout::lock`]: struct.Stdout.html#method.lock
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[derive(Debug)]
|
||||
pub struct StdoutLock<'a>(std::io::StdoutLock<'a>);
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
unsafe impl Send for StdoutLock<'_> {}
|
||||
|
||||
/// The state of the asynchronous stdout.
|
||||
///
|
||||
/// The stdout can be either idle or busy performing an asynchronous operation.
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
/// The stdout is idle.
|
||||
Idle(Option<Inner>),
|
||||
|
||||
/// The stdout is blocked on an asynchronous operation.
|
||||
///
|
||||
/// Awaiting this operation will result in the new state of the stdout.
|
||||
Busy(JoinHandle<State>),
|
||||
}
|
||||
|
||||
/// Inner representation of the asynchronous stdout.
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
/// The blocking stdout handle.
|
||||
stdout: std::io::Stdout,
|
||||
|
||||
/// The write buffer.
|
||||
buf: Vec<u8>,
|
||||
|
||||
/// The result of the last asynchronous operation on the stdout.
|
||||
last_op: Option<Operation>,
|
||||
}
|
||||
|
||||
/// Possible results of an asynchronous operation on the stdout.
|
||||
#[derive(Debug)]
|
||||
enum Operation {
|
||||
Write(io::Result<usize>),
|
||||
Flush(io::Result<()>),
|
||||
}
|
||||
|
||||
impl Stdout {
|
||||
/// Locks this handle to the standard error stream, returning a writable guard.
|
||||
///
|
||||
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Write trait for writing data.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||
/// #
|
||||
/// use async_std::io;
|
||||
/// use async_std::prelude::*;
|
||||
///
|
||||
/// let stdout = io::stdout();
|
||||
/// let mut handle = stdout.lock().await;
|
||||
///
|
||||
/// handle.write_all(b"hello world").await?;
|
||||
/// #
|
||||
/// # Ok(()) }) }
|
||||
/// ```
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||
pub async fn lock(&self) -> StdoutLock<'static> {
|
||||
static STDOUT: Lazy<std::io::Stdout> = Lazy::new(std::io::stdout);
|
||||
|
||||
spawn_blocking(move || StdoutLock(STDOUT.lock())).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Stdout {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::Write(res)) = inner.last_op.take() {
|
||||
let n = res?;
|
||||
|
||||
// If more data was written than is available in the buffer, let's retry
|
||||
// the write operation.
|
||||
if n <= buf.len() {
|
||||
return Poll::Ready(Ok(n));
|
||||
}
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Set the length of the inner buffer to the length of the provided buffer.
|
||||
if inner.buf.len() < buf.len() {
|
||||
inner.buf.reserve(buf.len() - inner.buf.len());
|
||||
}
|
||||
unsafe {
|
||||
inner.buf.set_len(buf.len());
|
||||
}
|
||||
|
||||
// Copy the data to write into the inner buffer.
|
||||
inner.buf[..buf.len()].copy_from_slice(buf);
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
let res = std::io::Write::write(&mut inner.stdout, &inner.buf);
|
||||
inner.last_op = Some(Operation::Write(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stdout is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let state = &mut *self.0.lock().unwrap();
|
||||
|
||||
loop {
|
||||
match state {
|
||||
State::Idle(opt) => {
|
||||
let inner = opt.as_mut().unwrap();
|
||||
|
||||
// Check if the operation has completed.
|
||||
if let Some(Operation::Flush(res)) = inner.last_op.take() {
|
||||
return Poll::Ready(res);
|
||||
} else {
|
||||
let mut inner = opt.take().unwrap();
|
||||
|
||||
// Start the operation asynchronously.
|
||||
*state = State::Busy(spawn_blocking(move || {
|
||||
let res = std::io::Write::flush(&mut inner.stdout);
|
||||
inner.last_op = Some(Operation::Flush(res));
|
||||
State::Idle(Some(inner))
|
||||
}));
|
||||
}
|
||||
}
|
||||
// Poll the asynchronous operation the stdout is currently blocked on.
|
||||
State::Busy(task) => *state = futures_core::ready!(Pin::new(task).poll(cx)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_flush(cx)
|
||||
}
|
||||
}
|
||||
|
||||
cfg_unix! {
|
||||
use crate::os::unix::io::{AsRawFd, RawFd};
|
||||
|
||||
impl AsRawFd for Stdout {
|
||||
fn as_raw_fd(&self) -> RawFd {
|
||||
std::io::stdout().as_raw_fd()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cfg_windows! {
|
||||
use crate::os::windows::io::{AsRawHandle, RawHandle};
|
||||
|
||||
impl AsRawHandle for Stdout {
|
||||
fn as_raw_handle(&self) -> RawHandle {
|
||||
std::io::stdout().as_raw_handle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||
impl Write for StdoutLock<'_> {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Poll::Ready(self.0.write(buf))
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(self.0.flush())
|
||||
}
|
||||
|
||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
self.poll_flush(cx)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue