In-Memory Reads With io::Cursor

io::Cursor turns a byte vector into a Read/Seek/Write source, so framing and assembly code runs entirely in memory without touching the filesystem.

RustData Fetching

Code

rustsnippet
24 lines
use std::io::{Cursor, Read, Seek, SeekFrom, Write};

fn main() {
    // Cursor 把内存字节当成可 Read/Seek 的源,不需要真实文件
    let mut cursor = Cursor::new(b"header,body,rows".to_vec());

    let mut head = [0u8; 6];
    cursor.read_exact(&mut head).unwrap();
    println!("head: {}", String::from_utf8_lossy(&head));

    // Seek 负偏移从尾部倒数
    cursor.seek(SeekFrom::End(-4)).unwrap();
    let mut tail = String::new();
    cursor.read_to_string(&mut tail).unwrap();
    println!("tail: {tail}");

    // position 跟踪读取进度
    println!("position: {}", cursor.position());

    // Cursor 同样是 Write 目标:字节直接写进内存
    let mut out = Cursor::new(Vec::new());
    out.write_all(b"packed").unwrap();
    println!("written: {}", String::from_utf8_lossy(&out.into_inner()));
}

Inside the snippet

In-Memory Reads With io::Cursor keeps everything in the function main.

Putting it to use

The demo output is labeled (head:, tail:, position:), so every printed line maps back to its originating operation.

Core lines

cursor.read_to_string(&mut tail).unwrap();
cursor.seek(SeekFrom::End(-4)).unwrap();
cursor.read_exact(&mut head).unwrap();

Interactive Tools for This Topic

FAQ

What does In-Memory Reads With io::Cursor print when run?
No setup needed: run the file and look for labeled lines like `head:`, `tail:`, `position:` in the output.