expression
Collect response chunks under a byte cap
Check the cumulative decoded byte count before appending each received chunk. The cap bounds retained application bytes, not total transport buffers or decompression cost. A real request also needs deadlines, resource limits and a validated destination. External crate example; constructs requests or synthetic responses in memory; no request is sent. Expected stdout (not executed): 3 too large Common mistake: Trusting a Content-Length claim or loading an unbounded body before checking its size.
Formal Syntax & Structure
rust syntaxrust
while let Some(chunk) = response.chunk().await?Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { async fn collect(mut r: reqwest::Response, cap: usize) -> Result<Vec<u8>, &'static str> { let mut out = Vec::new(); while let Some(chunk) = r.chunk().await.map_err(|_| "read")? { if chunk.len() > cap.saturating_sub(out.len()) { return Err("too large"); } out.extend_from_slice(&chunk); } Ok(out) } let small: reqwest::Response = http::Response::new("abc").into(); let large: reqwest::Response = http::Response::new("abcd").into(); println!("{}", collect(small,3).await.unwrap().len()); println!("{}", collect(large,3).await.unwrap_err());}