Migrating from alpha to stable Tokio

I have to ask again about what ought to be a trivial thing.

I had some code that worked in alpha version to read stdin but now in the new stable version none of it (codecs etc) works anymore, everything is suddenly "unimplemented". I am having trouble making any sense of the documentation. The usual problem of lots of weird and wonderful generic type conversions, traits, structs, modules, implementations and what-nots but not a single example on how to actually read anything with it.

How can I SIMPLY adapt:

use tokio::fs;
let contents = fs::read("foo.txt").await?;

so that it will work for stdin instead of "foo.txt"?

use tokio::io;
use tokio::io::AsyncReadExt;

let stdin = io::stdin();
let stuff = String::new();
stdin.read_to_string(&mut stuff).await?;

Note that tokio uses features heavily. For this, you will have to compile with "io-std" as well as "io-util".

1 Like

Most things in tokio are now behind cargo features (tokio features).
And Tokio's old codec module has moved to tokio-util under the feature codec.

Example

[dependencies]
tokio = { version = "0.2", features = ["io-std", "io-util", "fs", "macros"] }

# use "full" for the complete tokio experience
# tokio = { version = "0.2", features = ["full"] }

# tokio-util = { version = "0.2", features = ["codec"] }

tokio::io::AsyncReadExt::read_to_string(&mut String)
tokio::io::AsyncBufReadExt::lines()

use tokio::fs; // feature: fs
use tokio::io;

#[tokio::main] // feature: macros
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    {
        // using `/dev/stdin` on linux

        let contents = fs::read_to_string("/dev/stdin").await?;
        dbg!(contents);
    }

    {
        // AsyncReadExt::read_to_string(&mut String)

        use tokio::io::stdin; // feature: io-std
        use tokio::io::AsyncReadExt; // feature: io-util

        let mut contents = String::new();
        let mut r = stdin();
        r.read_to_string(&mut contents).await?;
        dbg!(contents);
    }

    {
        // AsyncBufReadExt::lines()

        use tokio::io::AsyncBufReadExt; // feature: io-util

        let r = io::BufReader::new(io::stdin());
        let mut lines = r.lines();
        while let Some(line) = lines.next_line().await? {
            dbg!(line);
        }
    }

    Ok(())
}
2 Likes

Thanks, I like the one-liner best!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.