use std::fs::File;
use std::io;
use std::path::Path;
use memmap2::Mmap;
pub struct MappedFile {
_file: File,
mmap: Mmap,
}
impl MappedFile {
pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
let file = File::open(path.as_ref())?;
let mmap = unsafe { memmap2::MmapOptions::new().map(&file)? };
Ok(Self { _file: file, mmap })
}
#[inline]
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.mmap
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.mmap.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.mmap.is_empty()
}
}
impl AsRef<[u8]> for MappedFile {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn open_reads_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sample.bin");
{
let mut f = File::create(&path).unwrap();
f.write_all(b"TESS").unwrap();
f.write_all(&[0u8; 60]).unwrap();
}
let map = MappedFile::open(&path).unwrap();
assert_eq!(map.len(), 64);
assert_eq!(&map.as_bytes()[..4], b"TESS");
}
}