Capped Reads With Read Take

Limit untrusted readers with Read::take so header reads and capped downloads never consume more bytes than the caller allows.

RustSecurity Boundaries

Code

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

fn main() -> io::Result<()> {
    let payload = b"0123456789abcdef";
    let mut cursor = io::Cursor::new(payload);

    // take(4):把这一次读取硬性截断到 4 字节
    let mut first = Vec::new();
    cursor.by_ref().take(4).read_to_end(&mut first)?;
    println!("first: {}", String::from_utf8_lossy(&first));

    // 底层游标只剩 12 字节,take 的上限大于剩余量时读到末尾为止
    let mut rest = String::new();
    cursor.take(100).read_to_string(&mut rest)?;
    println!("rest: {rest}");

    // 给不可信输入加读取上限,避免无界读取
    let mut limited = io::Cursor::new(vec![b'x'; 64]);
    let mut buf = [0u8; 8];
    let read = limited.take(8).read(&mut buf)?;
    println!("capped read: {read} bytes");
    Ok(())
}

How it works

Capped Reads With Read Take is built around the function main.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller.

Points of care

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The main signature reads fn main() -> io::Result<()>

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

Key statements

cursor.by_ref().take(4).read_to_end(&mut first)?;
cursor.take(100).read_to_string(&mut rest)?;
let read = limited.take(8).read(&mut buf)?;

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does Capped Reads With Read Take print when run?
Running the file directly is enough — expect labeled output lines such as `first:`, `rest:`, `capped read:`.