asset_io/mapped.rs
1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7// Unless required by applicable law or agreed to in writing,
8// this software is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
11// specific language governing permissions and limitations under
12// each license.
13
14//! Memory-mapped files, for zero-copy reads.
15
16use std::{fs::File, io::Cursor, ops::Deref};
17
18use crate::{error::Result, registry::HandlerRegistry, structure::Structure};
19
20/// A read-only memory map of a file.
21///
22/// Pair it with [`Structure::slice`], [`Structure::slice_item`] and
23/// [`Structure::read_slice`] to read without copying.
24///
25/// ```no_run
26/// # use asset_io::{HandlerRegistry, ItemKind, MappedFile};
27/// # fn main() -> asset_io::Result<()> {
28/// let file = std::fs::File::open("image.jpg")?;
29/// // SAFETY: the file is not modified or truncated while mapped.
30/// let map = unsafe { MappedFile::map(&file)? };
31/// // Register an application-provided handler before parsing.
32/// let registry = HandlerRegistry::new();
33/// let structure = map.parse(®istry, None)?;
34/// if let Some(xmp) = structure.item(ItemKind::Xmp)? {
35/// let bytes = structure.slice_item(&map, xmp)?; // borrowed from the map
36/// println!("{} bytes of XMP", bytes.len());
37/// }
38/// # Ok(())
39/// # }
40/// ```
41#[derive(Debug)]
42pub struct MappedFile {
43 map: memmap2::Mmap,
44}
45
46impl MappedFile {
47 /// Map `file` read-only.
48 ///
49 /// # Safety
50 ///
51 /// The file must not be truncated or modified, by this process or another,
52 /// while the map is alive. Doing so is undefined behavior, and truncation
53 /// can raise `SIGBUS`. Do not map files that untrusted parties can write.
54 /// Use ordinary reads (`read`) for those.
55 pub unsafe fn map(file: &File) -> Result<Self> {
56 Ok(Self {
57 map: memmap2::Mmap::map(file)?,
58 })
59 }
60
61 /// The mapped bytes.
62 pub fn as_bytes(&self) -> &[u8] {
63 &self.map
64 }
65
66 /// Parse the mapped file using an explicit extension or MIME type, or detect
67 /// its container from the leading bytes with `None`.
68 pub fn parse(&self, registry: &HandlerRegistry, format: Option<&str>) -> Result<Structure> {
69 Structure::parse(registry, &mut Cursor::new(self.as_bytes()), format)
70 }
71}
72
73impl Deref for MappedFile {
74 type Target = [u8];
75
76 fn deref(&self) -> &[u8] {
77 &self.map
78 }
79}
80
81impl AsRef<[u8]> for MappedFile {
82 fn as_ref(&self) -> &[u8] {
83 &self.map
84 }
85}