Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading raw bytes from standard input in Rust

Tags:

rust

I am trying to read in bytes from standard input in Rust. The code below works perfectly for lines consisting of regular characters, but for raw bytes that don't have associated characters (such as 0xe0), this causes the program to panic. The documentation says that it will terminate at the newline character, but doesn't mention any issues with non-character bytes.

EDIT: I actually missed that it does say that all bytes must be UTF-8 encoded- is there another function I can use to do this?

    let mut input = String::new();
    io::stdin().read_line(&mut input)
        .ok()
        .expect("Couldn't read line");   
like image 507
Unsolved Cypher Avatar asked Nov 29 '18 18:11

Unsolved Cypher


1 Answers

It turns out that Stdin implements the Read trait, so I was able to use the bytes method:

for i in io::stdin().bytes() {
    println!("read byte {}", i.unwrap());
}

And this loop can be broken out of by checking each byte until it's the desired byte.

like image 64
Unsolved Cypher Avatar answered Sep 20 '22 17:09

Unsolved Cypher