Read Bytes Iterator With Result Items

Read::bytes turns a reader into an iterator of io::Result<u8>, letting per-byte read errors be handled inside the loop instead of aborting the stream.

RustData Integrity

Code

rustsnippet
22 lines
use std::io::{Cursor, Read};

fn main() {
    // 含高位字节的字节流,模拟从网络分块读到的原始字节
    let payload: Vec<u8> = vec![0x68, 0xC3, 0xA9, 0xFF, 0x21];
    let mut cursor = Cursor::new(payload);

    // Read::bytes:每项都是 io::Result<u8>,读错误在循环里处理而不中断整个流
    let mut bytes = Vec::new();
    for item in cursor.by_ref().bytes() {
        match item {
            Ok(b) => bytes.push(b),
            Err(e) => println!("read failed: {e}"),
        }
    }
    println!("bytes: {bytes:?}");

    // Cursor 支持 set_position:回到开头重新读一遍
    cursor.set_position(0);
    let again = cursor.bytes().map(|b| b.unwrap_or(b'?')).collect::<Vec<_>>();
    println!("again: {again:?}");
}

How the snippet works

Read Bytes Iterator With Result Items keeps everything in the function main.

The one repetition in this snippet is the loop for item in cursor.by_ref().bytes(). Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Watch out for

  • The only prerequisite is the language toolchain itself.

Using it

Signature: fn main()

The run emits 3 labeled sections — read failed:, bytes:, again: — one per step.

Key statements

let again = cursor.bytes().map(|b| b.unwrap_or(b'?')).collect::<Vec<_>>();
match item {
    Ok(b) => bytes.push(b),
    Err(e) => println!("read failed: {e}"),
}

Interactive Tools for This Topic

FAQ

What does Read Bytes Iterator With Result Items print when run?
Run it as a complete program — the output lines carry labels such as `read failed:`, `bytes:`, `again:`.