Skip to main content

oa/core/
mapped_file.rs

1//! Read-only whole-file memory mapping with RAII ownership.
2//!
3//! Port provenance: `oa/core/mappedFile.h`.
4//!
5//! On Linux/macOS/Windows uses [`memmap2`] for true kernel-page-backed
6//! access. Other platforms fall back to a heap-owned `Vec<u8>` until a
7//! native mapping implementation is added.
8//!
9//! # Usage
10//!
11//! ```rust,ignore
12//! use oa::{MappedFile, Path};
13//!
14//! let mut mf = MappedFile::default();
15//! mf.open_read_only(&Path::from("weights.safetensors"))?;
16//! let data: &[u8] = mf.bytes();
17//! // file is unmapped when `mf` is dropped
18//! ```
19
20use crate::core::error::Error;
21use crate::{Path, Result};
22
23// ─── MappedFile ───────────────────────────────────────────────────────────────
24
25/// Read-only whole-file mapping with RAII lifetime.
26///
27/// Port provenance: `oa::MappedFile`.
28#[derive(Default)]
29pub struct MappedFile {
30	path: Path,
31	inner: Option<MappedInner>,
32}
33
34enum MappedInner {
35	/// `memmap2`-backed true OS mapping.
36	#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
37	Mmap(memmap2::Mmap),
38	/// Heap fallback for platforms without a native mmap implementation.
39	#[allow(dead_code)]
40	Owned(Vec<u8>),
41}
42
43impl MappedFile {
44	/// Open `path` for read-only access.
45	///
46	/// On supported platforms this performs a true OS-level memory mapping;
47	/// elsewhere it reads the file into a heap buffer.
48	///
49	/// Port provenance: `oa::MappedFile::openReadOnly`.
50	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		// SAFETY: the mapping is read-only; the file stays open while the
62		// `Mmap` is alive and both are owned by `MappedInner`.
63		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	/// Unmap and release the underlying resource.
75	pub fn close(&mut self) {
76		self.inner = None;
77		self.path = Path::default();
78	}
79
80	/// `true` when a file is currently open.
81	pub fn is_open(&self) -> bool {
82		self.inner.is_some()
83	}
84
85	/// The path this file was opened from.
86	pub fn path(&self) -> &Path {
87		&self.path
88	}
89
90	/// Raw byte slice over the mapped data. Empty when not open.
91	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	/// Length in bytes. Zero when not open.
101	pub fn size(&self) -> usize {
102		self.bytes().len()
103	}
104
105	/// Return a sub-slice `[offset, offset+len)` or an error if out of range.
106	///
107	/// Port provenance: `oa::MappedFile::slice`.
108	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}