Frame And Seek Records With io::Cursor

Write length-prefixed binary records into an in-memory io::Cursor while capturing byte offsets via stream_position, then seek back and decode one.

RustData Integrity

Code

snippet
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};

fn write_frame<W: Write + Seek>(w: &mut W, payload: &[u8]) -> io::Result<u64> {
    let offset = w.stream_position()?;
    let len = u32::try_from(payload.len())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame too large"))?;
    w.write_all(&len.to_be_bytes())?;
    w.write_all(payload)?;
    Ok(offset)
}

fn read_frame_at<R: Read + Seek>(r: &mut R, offset: u64) -> io::Result<Vec<u8>> {
    r.seek(SeekFrom::Start(offset))?;
    let mut len_buf = [0_u8; 4];
    r.read_exact(&mut len_buf)?;
    let len = u32::from_be_bytes(len_buf) as usize;
    let mut body = vec![0_u8; len];
    r.read_exact(&mut body)?;
    Ok(body)
}

fn main() -> io::Result<()> {
    let mut cursor = Cursor::new(Vec::new());
    let mut offsets = Vec::new();
    for msg in [b"alpha".as_slice(), b"bravo-two", b"charlie"] {
        offsets.push(write_frame(&mut cursor, msg)?);
    }
    println!("total bytes={}, offsets={offsets:?}", cursor.get_ref().len());

    let second = read_frame_at(&mut cursor, offsets[1])?;
    println!("decoded[1]: {}", String::from_utf8_lossy(&second));
    let first = read_frame_at(&mut cursor, offsets[0])?;
    println!("decoded[0]: {}", String::from_utf8_lossy(&first));
    Ok(())
}

Walkthrough notes — Frame And Seek Records With io::Cursor

Frame And Seek Records With io::Cursor comes down to the functions write_frame, read_frame_at and main.

A single loop drives the file — for msg in [b"alpha".as_slice(), b"bravo-two", b"charlie"]. Result is the error channel: the caller receives the failure as a value instead of an exception.

Watch out for

  • Requires solely a stock language runtime — nothing additional gets installed.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Using it

The run emits 3 labeled sections — total bytes=, decoded[1]:, decoded[0]: — one per step.

Execute the file and main walks through write_frame and read_frame_at, in that order.

Key statements

fn read_frame_at<R: Read + Seek>(r: &mut R, offset: u64) -> io::Result<Vec<u8>> {
    r.seek(SeekFrom::Start(offset))?;
    let mut len_buf = [0_u8; 4];
    r.read_exact(&mut len_buf)?;
    let len = u32::from_be_bytes(len_buf) as usize;
    let mut body = vec![0_u8; len];
    r.read_exact(&mut body)?;
    Ok(body)
}
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame too large"))?;
let second = read_frame_at(&mut cursor, offsets[1])?;

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Frame And Seek Records With io::Cursor print when run?
The script runs standalone; its 3 labeled outputs include `total bytes=`, `decoded[1]:`, `decoded[0]:`.