use std::path::Path;
use memmap2::Mmap;
use crate::error::IndexError;
pub struct MmapIndex {
mmap: Mmap,
}
impl MmapIndex {
pub fn open(path: &Path) -> Result<Self, IndexError> {
let file = std::fs::File::open(path)?;
let mmap = unsafe { Mmap::map(&file)? };
Ok(Self { mmap })
}
pub fn as_bytes(&self) -> &[u8] {
&self.mmap
}
pub fn len(&self) -> usize {
self.mmap.len()
}
pub fn is_empty(&self) -> bool {
self.mmap.is_empty()
}
}
impl std::fmt::Debug for MmapIndex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MmapIndex")
.field("len", &self.mmap.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mmap_open_nonexistent() {
let result = MmapIndex::open(Path::new("/nonexistent/path/index.dat"));
assert!(result.is_err());
}
#[test]
fn test_mmap_open_existing() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.dat");
std::fs::write(&file_path, b"hello world").unwrap();
let mmap = MmapIndex::open(&file_path).unwrap();
assert_eq!(mmap.len(), 11);
assert_eq!(mmap.as_bytes(), b"hello world");
}
}