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.
Code
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 ownmatch.
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.