Skip to main content

euv_core/runtime/vfs/mapping/
impl.rs

1use super::*;
2
3/// Immutable read-only OS mappings are safely transferable across threads.
4#[cfg(any(unix, windows))]
5unsafe impl Send for EuvPakOsMap {}
6
7/// Immutable read-only OS mappings can be shared concurrently across background I/O workers.
8#[cfg(any(unix, windows))]
9unsafe impl Sync for EuvPakOsMap {}
10
11/// Deterministic RAII unmapping when the last `Arc<EuvPakOsMap>` drops.
12#[cfg(any(unix, windows))]
13impl Drop for EuvPakOsMap {
14    /// Releases the underlying OS virtual memory mapping without leaking descriptors or pages.
15    fn drop(&mut self) {
16        #[cfg(unix)]
17        {
18            let Self { ptr, len } = *self;
19            unmap_posix_region(ptr, len);
20        }
21        #[cfg(windows)]
22        {
23            let Self {
24                ptr,
25                mapping_handle,
26                ..
27            } = *self;
28            unmap_win32_region(ptr, mapping_handle);
29        }
30    }
31}
32
33/// Default empty heap-backed `EuvPakMapping`.
34impl Default for EuvPakMapping {
35    /// Creates an empty read-only `EuvPakMapping`.
36    ///
37    /// # Returns
38    ///
39    /// - `Self` - Empty in-memory mapping.
40    fn default() -> Self {
41        Self::from_bytes(Arc::new(Vec::new()))
42    }
43}
44
45/// Cross-platform zero-copy constructors, OS `mmap` lifecycle, and paging hints for `EuvPakMapping`.
46impl EuvPakMapping {
47    /// Creates an in-memory zero-copy mapping over an `Arc<Vec<u8>>` buffer.
48    ///
49    /// # Arguments
50    ///
51    /// - `Arc<Vec<u8>>` - Shared immutable `.euvpak` archive byte buffer.
52    ///
53    /// # Returns
54    ///
55    /// - `Self` - Ready read-only `EuvPakMapping`.
56    #[must_use]
57    pub fn from_bytes(bytes: Arc<Vec<u8>>) -> Self {
58        Self {
59            backing: EuvPakBacking::Owned(bytes),
60        }
61    }
62
63    /// Opens an `.euvpak` archive from `path` using a single OS virtual memory map on native targets.
64    ///
65    /// # Arguments
66    ///
67    /// - `&Path` - Filesystem path to an `.euvpak` archive.
68    ///
69    /// # Returns
70    ///
71    /// - `Result<Self, String>` - Zero-copy OS-mapped archive view or structured I/O error.
72    #[cfg(not(target_arch = "wasm32"))]
73    pub fn open_mmap(path: &Path) -> Result<Self, String> {
74        #[cfg(unix)]
75        {
76            let mut file: File = File::open(path)
77                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
78            let raw_fd: i32 = file.as_raw_fd();
79            if raw_fd < 0 {
80                return Err(ERR_EUVPAK_INVALID_HANDLE.to_string());
81            }
82            let file_len: u64 = file
83                .seek(SeekFrom::End(0))
84                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
85            if file_len == 0 {
86                return Ok(Self::from_bytes(Arc::new(Vec::new())));
87            }
88            if file_len > usize::MAX as u64 {
89                return Err(ERR_EUVPAK_TOO_LARGE.to_string());
90            }
91            let os_map: EuvPakOsMap = map_posix_readonly(raw_fd, file_len as usize)?;
92            Ok(Self {
93                backing: EuvPakBacking::OsMapped(Arc::new(os_map)),
94            })
95        }
96        #[cfg(windows)]
97        {
98            let mut file: File = File::open(path)
99                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
100            let raw_handle: *mut c_void = file.as_raw_handle();
101            if raw_handle.is_null() || raw_handle as isize == -1 {
102                return Err(ERR_EUVPAK_INVALID_HANDLE.to_string());
103            }
104            let file_len: u64 = file
105                .seek(SeekFrom::End(0))
106                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
107            if file_len == 0 {
108                return Ok(Self::from_bytes(Arc::new(Vec::new())));
109            }
110            if file_len > usize::MAX as u64 {
111                return Err(ERR_EUVPAK_TOO_LARGE.to_string());
112            }
113            let os_map: EuvPakOsMap = map_win32_readonly(raw_handle, file_len as usize)?;
114            Ok(Self {
115                backing: EuvPakBacking::OsMapped(Arc::new(os_map)),
116            })
117        }
118        #[cfg(not(any(unix, windows)))]
119        {
120            let mut file: File = File::open(path)
121                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
122            let file_len: u64 = file
123                .seek(SeekFrom::End(0))
124                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
125            let _: u64 = file
126                .seek(SeekFrom::Start(0))
127                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
128            let mut buffer: Vec<u8> = Vec::with_capacity(file_len as usize);
129            let _: usize = file
130                .read_to_end(&mut buffer)
131                .map_err(|err: io::Error| format!("{ERR_EUVPAK_OPEN_FAILED}: {err}"))?;
132            Ok(Self::from_bytes(Arc::new(buffer)))
133        }
134    }
135
136    /// Returns an error on `wasm32` where direct OS filesystem `mmap` is unavailable.
137    ///
138    /// # Arguments
139    ///
140    /// - `&Path` - Unused filesystem path on `wasm32`.
141    ///
142    /// # Returns
143    ///
144    /// - `Result<Self, String>` - Always returns an unsupported error instructing callers to use `from_bytes`.
145    #[cfg(target_arch = "wasm32")]
146    pub fn open_mmap(_path: &Path) -> Result<Self, String> {
147        Err(ERR_EUVPAK_WASM_UNSUPPORTED.to_string())
148    }
149
150    /// Advises the OS kernel to prefetch `[offset..offset+len]` via `MADV_WILLNEED` when OS-mapped.
151    ///
152    /// # Arguments
153    ///
154    /// - `usize` - Starting byte offset inside the mapping.
155    /// - `usize` - Byte length to pre-fault sequentially.
156    pub fn advise_willneed(&self, offset: usize, len: usize) {
157        #[cfg(unix)]
158        {
159            let Self { backing } = self;
160            if let EuvPakBacking::OsMapped(os_map) = backing {
161                advise_posix_region(os_map, offset, len, POSIX_MADV_WILLNEED);
162            }
163        }
164        #[cfg(not(unix))]
165        {
166            let _: (usize, usize) = (offset, len);
167        }
168    }
169
170    /// Advises the OS kernel that `[offset..offset+len]` will be accessed randomly (`MADV_RANDOM`).
171    ///
172    /// # Arguments
173    ///
174    /// - `usize` - Starting byte offset inside the mapping.
175    /// - `usize` - Byte length expected to experience random access.
176    pub fn advise_random(&self, offset: usize, len: usize) {
177        #[cfg(unix)]
178        {
179            let Self { backing } = self;
180            if let EuvPakBacking::OsMapped(os_map) = backing {
181                advise_posix_region(os_map, offset, len, POSIX_MADV_RANDOM);
182            }
183        }
184        #[cfg(not(unix))]
185        {
186            let _: (usize, usize) = (offset, len);
187        }
188    }
189
190    /// Returns the mapped archive payload as an immutable zero-copy byte slice.
191    ///
192    /// # Returns
193    ///
194    /// - `&[u8]` - Borrowed view of the mapped `.euvpak` bytes.
195    #[must_use]
196    pub fn as_bytes(&self) -> &[u8] {
197        let Self { backing } = self;
198        match backing {
199            EuvPakBacking::Owned(bytes) => bytes.as_slice(),
200            #[cfg(any(unix, windows))]
201            EuvPakBacking::OsMapped(os_map) => {
202                let EuvPakOsMap { ptr, len, .. } = **os_map;
203                unsafe { from_raw_parts(ptr.as_ptr(), len) }
204            }
205        }
206    }
207
208    /// Returns the non-null base pointer of the backing byte buffer on native targets when non-empty.
209    ///
210    /// # Returns
211    ///
212    /// - `Option<NonNull<u8>>` - Non-null pointer to the first byte or `None` when empty.
213    #[cfg(any(unix, windows))]
214    #[must_use]
215    pub fn base_non_null(&self) -> Option<NonNull<u8>> {
216        let Self { backing } = self;
217        match backing {
218            EuvPakBacking::Owned(bytes) => {
219                if bytes.is_empty() {
220                    None
221                } else {
222                    NonNull::new(bytes.as_ptr().cast_mut())
223                }
224            }
225            EuvPakBacking::OsMapped(os_map) => Some(os_map.ptr),
226        }
227    }
228
229    /// Returns the byte length of this mapped archive.
230    ///
231    /// # Returns
232    ///
233    /// - `usize` - Mapped byte length.
234    #[must_use]
235    pub fn len(&self) -> usize {
236        self.as_bytes().len()
237    }
238
239    /// Returns `true` when the mapped archive contains zero bytes.
240    ///
241    /// # Returns
242    ///
243    /// - `bool` - Whether the mapped byte slice is empty.
244    #[must_use]
245    pub fn is_empty(&self) -> bool {
246        self.as_bytes().is_empty()
247    }
248
249    /// Returns `true` when backed by an OS virtual memory mapping (`mmap` / `MapViewOfFile`).
250    ///
251    /// # Returns
252    ///
253    /// - `bool` - Whether OS virtual memory mapping is active.
254    #[must_use]
255    pub fn is_os_mapped(&self) -> bool {
256        let Self { backing } = self;
257        match backing {
258            EuvPakBacking::Owned(_) => false,
259            #[cfg(any(unix, windows))]
260            EuvPakBacking::OsMapped(_) => true,
261        }
262    }
263}