Read Length Framed Bytes With read_exact
Parse length-prefixed frames with read_exact, which reports UnexpectedEof instead of a silent short read when the wire ends mid-frame.
Code
use std::io::{Cursor, Read};
// 帧格式:1 字节长度 + 载荷
fn read_frame(cursor: &mut Cursor<&[u8]>) -> std::io::Result<String> {
let mut length = [0u8; 1];
// read_exact:字节不够直接报 UnexpectedEof,绝不静默短读
cursor.read_exact(&mut length)?;
let mut payload = vec![0u8; length[0] as usize];
cursor.read_exact(&mut payload)?;
Ok(String::from_utf8_lossy(&payload).into_owned())
}
fn main() -> std::io::Result<()> {
let wire = [4u8, b'p', b'i', b'n', b'g', 2u8, b'o', b'k'];
let mut cursor = Cursor::new(&wire[..]);
println!("frame 1: {}", read_frame(&mut cursor)?);
println!("frame 2: {}", read_frame(&mut cursor)?);
// 尾部截断:长度字节宣称 9 字节,后面已经没有数据
let broken = [9u8];
match read_frame(&mut Cursor::new(&broken[..])) {
Ok(frame) => println!("unexpected: {frame}"),
Err(err) => println!("truncated: {err}"),
}
Ok(())
}The framing contract
read_frame reads a 1-byte length then exactly that many payload bytes via read_exact. Because read_exact errors with UnexpectedEof when fewer bytes exist, a truncated wire can never silently yield a short frame.
Two good frames, one broken
The wire [4 ping][2 ok] decodes as frame 1: ping and frame 2: ok. The broken input [9u8] declares 9 payload bytes that do not exist; read_exact fails and the demo prints truncated: failed to fill whole buffer.
Why not read()
A plain read may return fewer bytes than requested even mid-frame; read_exact loops until the buffer is full or errors, which is the guarantee frame parsing needs.
Interactive Tools for This Topic
FAQ
- Why prefer read_exact over read() for frames?
- read() may return short even mid-frame; read_exact fills the buffer fully or errors with UnexpectedEof, which turns truncation into an explicit failure.
- What does the demo print for the broken frame?
- The truncated branch prints the UnexpectedEof error text (failed to fill whole buffer) instead of accepting a partial frame.
Report a problem with this exampleOpens a pre-filled issue on GitHub.