Chained Readers With io::chain

Concatenate readers with io::chain so headers, bodies, and multiple sources are consumed as one continuous byte stream.

RustData Fetching

Code

rustsnippet
29 lines
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let header = io::Cursor::new(b"GET /health HTTP/1.1\r\n");
    let body = io::Cursor::new(b"Host: localhost\r\n\r\n");

    // chain 把两个 Reader 首尾相接,像读一个连续流
    let mut combined = header.chain(body);
    let mut raw = String::new();
    combined.read_to_string(&mut raw)?;
    print!("{raw}");

    // 三段拼接:前一段读完后自动切换下一段
    let mut three = io::Cursor::new(b"one")
        .chain(io::Cursor::new(b"-two"))
        .chain(io::Cursor::new(b"-three"));
    let mut text = String::new();
    three.read_to_string(&mut text)?;
    println!("joined: {text}");

    // BufRead 行读取同样跨段工作
    let mut lines = io::Cursor::new(b"a\nb\n").chain(io::Cursor::new(b"c\n"));
    let mut line = String::new();
    while lines.read_line(&mut line)? > 0 {
        print!("line: {line}");
        line.clear();
    }
    Ok(())
}

How it works

Chained Readers With io::chain comes down to the function main.

Iteration happens inside while lines.read_line(&mut line)? > 0 — everything outside it runs once. Result is the error channel: the caller receives the failure as a value instead of an exception.

What to watch for

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Putting it to use

Entry signature: fn main() -> io::Result<()>

The demo output is labeled (joined:), so every printed line maps back to its originating operation.

Core lines

combined.read_to_string(&mut raw)?;
three.read_to_string(&mut text)?;

FAQ

Is there exception handling?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Chained Readers With io::chain print when run?
Execute the whole file; each printed line is prefixed with a label like `joined:`.