use bstack::{BStack, BStackByteVec, LinearBStackAllocator};
use std::io;
use std::path::PathBuf;
fn print_bytes(v: &BStackByteVec<LinearBStackAllocator>) -> io::Result<()> {
let len = v.len()?;
print!(" {} byte(s): [", len);
for (i, item) in v.iter()?.enumerate() {
if i > 0 {
print!(", ");
}
print!("0x{:02X}", item?);
}
println!("]");
Ok(())
}
fn main() -> io::Result<()> {
let path = PathBuf::from("bytevec_example.bstack");
println!("=== Session 1: creating byte buffer ===");
let block_bytes: [u8; 16] = {
let alloc = LinearBStackAllocator::new(BStack::open(&path)?);
let mut buf: BStackByteVec<_> = BStackByteVec::new(&alloc)?;
for &b in b"Hello, BStack!" {
buf.push(b)?;
}
println!("After initial push:");
print_bytes(&buf)?;
println!(" capacity={}", buf.capacity()?);
let last = buf.pop()?.expect("expected a byte");
println!("\nPopped: 0x{:02X} ('{}')", last, last as char);
buf.push(b'!')?;
buf.push(b'!')?;
println!("\nAfter replacement:");
print_bytes(&buf)?;
let all = buf.read_bytes()?;
println!("\nread_bytes(): {:?}", String::from_utf8_lossy(&all));
let bytes: [u8; 16] = buf.into_raw_block().into();
bytes
};
println!("\nFile closed. Block handle: {:?}", block_bytes);
println!("\n=== Session 2: reopen and recover ===");
{
let alloc = LinearBStackAllocator::new(BStack::open(&path)?);
let block = unsafe { bstack::BStackSlice::from_bytes(&alloc, block_bytes) };
let buf: BStackByteVec<_> = unsafe { BStackByteVec::from_raw_block(block) };
println!("Recovered {} byte(s):", buf.len()?);
print_bytes(&buf)?;
let recovered = buf.read_bytes()?;
assert_eq!(recovered, b"Hello, BStack!!");
println!("\nVerified: {:?}", String::from_utf8_lossy(&recovered));
let mut buf = buf;
buf.resize(20, b' ')?;
println!("\nAfter resize to 20 (space-filled):");
print_bytes(&buf)?;
buf.truncate(15)?;
println!("\nAfter truncate to 15:");
print_bytes(&buf)?;
buf.dealloc()?;
}
std::fs::remove_file(&path)?;
println!("\nDone.");
Ok(())
}