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.
Code
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
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.