Custom Read Implementations Track EOF

Implementing io::Read by hand shows the contract: fill the caller buffer, decrement a budget, and return Ok(0) at EOF so read_to_end terminates cleanly.

RustData Fetching

Code

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

// 只放行前 N 个字节的截断读取器:Ok(0) 表示 EOF,这是 Read 契约的关键
struct TakeReader<T> {
    inner: T,
    remaining: usize,
}

impl<T: Read> Read for TakeReader<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.remaining == 0 {
            return Ok(0); // 上限用尽:报告 EOF,不再碰内部读取器
        }
        let cap = buf.len().min(self.remaining);
        let n = self.inner.read(&mut buf[..cap])?;
        self.remaining -= n;
        Ok(n)
    }
}

fn main() {
    let mut reader = TakeReader { inner: "abcdefg".as_bytes(), remaining: 3 };
    let mut out = Vec::new();
    // read_to_end 反复调用 read,直到 Ok(0)
    reader.read_to_end(&mut out).unwrap();
    println!("read: {}", String::from_utf8_lossy(&out));

    // 上限为 0:第一次调用就是 EOF
    let mut none = TakeReader { inner: "abcdefg".as_bytes(), remaining: 0 };
    let mut sink = Vec::new();
    none.read_to_end(&mut sink).unwrap();
    println!("empty: {} bytes", sink.len());
}

What happens when it runs

The parts in motion are the functions read and main.

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

What to watch for

  • No external packages: the language’s built-in APIs carry everything.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The leading signature is: fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>

The demo output is labeled (read:, empty:), which lets each printed line be traced to its producing operation.

Key statements

return Ok(0); // 上限用尽:报告 EOF,不再碰内部读取器
}
let n = self.inner.read(&mut buf[..cap])?;
reader.read_to_end(&mut out).unwrap();

FAQ

What is the error handling style?
Through the type system: failures are `Result` variants the caller must consume.
What does Custom Read Implementations Track EOF print when run?
Run it as a complete program — the output lines carry labels such as `read:`, `empty:`.