From d0a8e5d6f2921fadc51a9612f6fe558e4213560f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Thu, 15 Aug 2019 22:10:17 +0200 Subject: [PATCH] tokio-fs: rewrite std echo example using async/await (#1442) This PR fixes the echo example in tokio-fs. Refs: #1255 --- tokio-fs/examples/std-echo.rs | 34 ++++++++++++++++++++++++ tokio-fs/examples_old/std-echo.rs | 43 ------------------------------- 2 files changed, 34 insertions(+), 43 deletions(-) create mode 100644 tokio-fs/examples/std-echo.rs delete mode 100644 tokio-fs/examples_old/std-echo.rs diff --git a/tokio-fs/examples/std-echo.rs b/tokio-fs/examples/std-echo.rs new file mode 100644 index 000000000..3a5eca676 --- /dev/null +++ b/tokio-fs/examples/std-echo.rs @@ -0,0 +1,34 @@ +//! Echo everything received on STDIN to STDOUT and STDERR. +#![feature(async_await)] + +use futures_util::{FutureExt, SinkExt, StreamExt, TryFutureExt}; + +use tokio::codec::{FramedRead, FramedWrite, LinesCodec, LinesCodecError}; +use tokio::future::ready; +use tokio_fs::{stderr, stdin, stdout}; +use tokio_threadpool::Builder; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let pool = Builder::new().pool_size(1).build(); + + pool.spawn( + async { + let mut input = FramedRead::new(stdin(), LinesCodec::new()); + let mut output = FramedWrite::new(stdout(), LinesCodec::new()); + let mut error = FramedWrite::new(stderr(), LinesCodec::new()); + + while let Some(line) = input.next().await { + let line = line?; + output.send(format!("OUT: {}", line)).await?; + error.send(format!("ERR: {}", line)).await?; + } + Ok(()) + } + .map_err(|e: LinesCodecError| panic!(e)) + .then(|_| ready(())), + ); + + pool.shutdown_on_idle().await; + Ok(()) +} diff --git a/tokio-fs/examples_old/std-echo.rs b/tokio-fs/examples_old/std-echo.rs deleted file mode 100644 index 774cec14a..000000000 --- a/tokio-fs/examples_old/std-echo.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Echo everything received on STDIN to STDOUT. -#![feature(async_await)] - -use tokio_codec::{FramedRead, FramedWrite, LinesCodec}; -use tokio_fs::{stderr, stdin, stdout}; -use tokio_threadpool::Builder; - -use futures_util::sink::SinkExt; - -use std::io; - -#[tokio::main] -async fn main() -> Result<(), Box> { - let pool = Builder::new().pool_size(1).build(); - - pool.spawn({ - let input = FramedRead::new(stdin(), LinesCodec::new()); - - let output = FramedWrite::new(stdout(), LinesCodec::new()).with(|line: String| { - let mut out = "OUT: ".to_string(); - out.push_str(&line); - Ok::<_, io::Error>(out) - }); - - let error = FramedWrite::new(stderr(), LinesCodec::new()).with(|line: String| { - let mut out = "ERR: ".to_string(); - out.push_str(&line); - Ok::<_, io::Error>(out) - }); - - let dst = output.fanout(error); - - input - .forward(dst) - .map(|_| ()) - .map_err(|e| panic!("io error = {:?}", e)) - }); - - pool.shutdown_on_idle() - .wait() - .map_err(|_| "failed to shutdown the thread pool")?; - Ok(()) -}