1use crate::core::error::Error;
21use crate::{Path, Result};
22
23#[derive(Default)]
29pub struct MappedFile {
30 path: Path,
31 inner: Option<MappedInner>,
32}
33
34enum MappedInner {
35 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
37 Mmap(memmap2::Mmap),
38 #[allow(dead_code)]
40 Owned(Vec<u8>),
41}
42
43impl MappedFile {
44 pub fn open_read_only(&mut self, path: &Path) -> Result<()> {
51 self.close();
52 self.path = path.clone();
53 self.inner = Some(Self::map_file(path)?);
54 Ok(())
55 }
56
57 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
58 fn map_file(path: &Path) -> Result<MappedInner> {
59 let file = std::fs::File::open(std::ops::Deref::deref(path))
60 .map_err(|e| Error::io("MappedFile::open", e))?;
61 let mmap =
64 unsafe { memmap2::Mmap::map(&file) }.map_err(|e| Error::io("MappedFile::mmap", e))?;
65 Ok(MappedInner::Mmap(mmap))
66 }
67
68 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
69 fn map_file(path: &Path) -> Result<MappedInner> {
70 let data = std::fs::read(path).map_err(|e| Error::io("MappedFile::read", e))?;
71 Ok(MappedInner::Owned(data))
72 }
73
74 pub fn close(&mut self) {
76 self.inner = None;
77 self.path = Path::default();
78 }
79
80 pub fn is_open(&self) -> bool {
82 self.inner.is_some()
83 }
84
85 pub fn path(&self) -> &Path {
87 &self.path
88 }
89
90 pub fn bytes(&self) -> &[u8] {
92 match &self.inner {
93 None => &[],
94 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
95 Some(MappedInner::Mmap(m)) => m,
96 Some(MappedInner::Owned(v)) => v,
97 }
98 }
99
100 pub fn size(&self) -> usize {
102 self.bytes().len()
103 }
104
105 pub fn slice(&self, offset: u64, len: u64) -> Result<&[u8]> {
109 let data = self.bytes();
110 let start = offset as usize;
111 let end = start
112 .checked_add(len as usize)
113 .filter(|&e| e <= data.len())
114 .ok_or_else(|| {
115 Error::out_of_range(format!(
116 "MappedFile::slice: [{offset}, {}) out of bounds (size={})",
117 offset + len,
118 data.len()
119 ))
120 })?;
121 Ok(&data[start..end])
122 }
123}