use memmap2::MmapOptions;
use memvec::{MemVec, MmapAnon};
#[derive(Copy, Clone)]
#[repr(C, packed)]
struct Record {
id: u32,
timestamp: u64,
data: [u8; 16],
}
impl Record {
fn new(id: u32) -> Self {
Self {
id,
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
data: [0; 16],
}
}
}
fn main() {
println!("MemVec with Anonymous Memory Mapping Example");
let mmap = MmapAnon::with_size(0).expect("mmap failed");
let mut vec =
unsafe { MemVec::<Record, _>::try_from_memory(mmap) }.expect("memvec creation failed");
println!(
"Initial - Length: {}, Capacity: {}",
vec.len(),
vec.capacity()
);
for i in 0..5 {
vec.push(Record::new(i));
println!(
"Added record {}: Length: {}, Capacity: {}",
i,
vec.len(),
vec.capacity()
);
}
println!("\nRecords:");
for (i, record) in vec.iter().enumerate() {
let id = record.id;
let timestamp = record.timestamp;
println!(" [{}] id={}, timestamp={}", i, id, timestamp);
}
vec.reserve(20);
println!(
"\nAfter reserve(20) - Length: {}, Capacity: {}",
vec.len(),
vec.capacity()
);
for i in 5..10 {
vec.push(Record::new(i));
}
println!(
"Final - Length: {}, Capacity: {}",
vec.len(),
vec.capacity()
);
println!("Memory is automatically managed without any files!");
println!("\n--- Example with custom MmapOptions ---");
let mut options = MmapOptions::new();
options.len(1000);
#[cfg(target_os = "linux")]
options.populate();
let mmap2 = MmapAnon::with_options(options).expect("mmap with options failed");
let mut vec2 =
unsafe { MemVec::<Record, _>::try_from_memory(mmap2) }.expect("memvec creation failed");
for i in 0..3 {
vec2.push(Record::new(i + 100));
}
println!(
"Custom options vec - Length: {}, Capacity: {}",
vec2.len(),
vec2.capacity()
);
}