use std::fs::File;
use std::io::Write;
use std::path::Path;
use membase::{MmapOptions, Mmap, MmapMut};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("membase Basic Usage Example");
println!("===========================");
let path = Path::new("example_data.bin");
let mut file = File::create(&path)?;
let data = b"Hello, membase!";
file.write_all(data)?;
file.sync_all()?;
drop(file);
let file = File::open(&path)?;
println!("Creating read-only memory map...");
let map = unsafe { MmapOptions::new().map(&file)? };
let contents = std::str::from_utf8(&map)?;
println!("Read from memory map: {}", contents);
drop(map);
let file = File::open(&path)?;
println!("\nCreating writable memory map...");
let mut map = unsafe { MmapOptions::new().write(true).map_mut(&file)? };
if map.len() >= 7 {
map[7..13].copy_from_slice(b"membase");
}
println!("Flushing changes to disk...");
map.flush()?;
drop(map);
let file = File::open(&path)?;
let map = unsafe { Mmap::map(&file)? };
let contents = std::str::from_utf8(&map)?;
println!("Read after modification: {}", contents);
drop(map);
std::fs::remove_file(&path)?;
println!("\nCreating anonymous memory map...");
let mut map = unsafe { MmapMut::map_anon(1024)? };
let message = b"This is an anonymous memory map";
map[0..message.len()].copy_from_slice(message);
let contents = std::str::from_utf8(&map[0..message.len()])?;
println!("Read from anonymous map: {}", contents);
println!("\nExample completed successfully!");
Ok(())
}