use bytes::Bytes;
use hexz_common::Result;
use hexz_core::store::StorageBackend;
use memmap2::Mmap;
use std::fs::File;
#[derive(Debug)]
pub struct MmapBackend {
bytes: Bytes,
len: u64,
}
impl MmapBackend {
pub fn new(path: &std::path::Path) -> Result<Self> {
let file = File::open(path)?;
let len = file.metadata()?.len();
let map = unsafe { Mmap::map(&file)? };
let bytes = Bytes::from_owner(map);
Ok(Self { bytes, len })
}
}
impl StorageBackend for MmapBackend {
fn read_exact(&self, offset: u64, len: usize) -> Result<Bytes> {
let start = offset as usize;
let end = start + len;
if end > self.bytes.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"Read out of bounds",
)
.into());
}
Ok(self.bytes.slice(start..end))
}
fn len(&self) -> u64 {
self.len
}
}