Skip to main content

mmap_guard/
lib.rs

1//! Safe, guarded memory-mapped file I/O for Rust.
2//!
3//! A thin wrapper around [`memmap2`] that encapsulates the single `unsafe` call
4//! behind a safe API, so downstream crates can use `#![forbid(unsafe_code)]`
5//! while still benefiting from zero-copy file access.
6//!
7//! # Overview
8//!
9//! This crate provides [`FileData`], an enum that transparently holds either a
10//! memory-mapped file or a heap-allocated buffer. Both variants deref to `&[u8]`,
11//! so consumers never need to know which backing store is in use.
12//!
13//! # Examples
14//!
15//! ```no_run
16//! use mmap_guard::map_file;
17//!
18//! let data = map_file("large-file.bin").unwrap();
19//! assert!(!data.is_empty());
20//! // data derefs to &[u8] — use it like any byte slice
21//! ```
22//!
23//! For CLI tools that accept both file paths and stdin, pass the user-supplied
24//! path straight to [`load()`] — it routes `"-"` to stdin internally:
25//!
26//! ```no_run
27//! use mmap_guard::load;
28//!
29//! // In a real CLI you'd get `path` from clap / std::env::args.
30//! let path = std::env::args().nth(1).unwrap_or_else(|| "-".to_string());
31//!
32//! // No manual `if path == "-"` branch needed — `load` handles the dispatch.
33//! let data = load(&path)?;
34//! assert!(!data.is_empty());
35//! # Ok::<(), std::io::Error>(())
36//! ```
37//!
38//! If you need a custom byte cap for stdin, call [`load_stdin`] directly
39//! (e.g. `load_stdin(Some(10 * 1024 * 1024))` for a 10 MiB limit).
40//!
41//! # Safety
42//!
43//! This crate contains exactly **one** `unsafe` block: the call to
44//! [`memmap2::Mmap::map()`]. See the [`map_file`] documentation for the full
45//! safety argument.
46//!
47//! # Known Limitations
48//!
49//! Advisory locks acquired by this crate are **cooperative**: they are only
50//! effective when all processes accessing the same file honour the `fs4`
51//! locking protocol. A process that truncates a file without acquiring the
52//! advisory lock first may cause the OS to deliver `SIGBUS` (Unix) or an
53//! access violation (Windows) when a mapped region is read. This is inherent
54//! to memory-mapped I/O and cannot be fully eliminated.
55//!
56//! See [`map_file`]'s *Known Limitations* section for the full detail.
57
58#![deny(clippy::undocumented_unsafe_blocks)]
59
60mod file_data;
61mod load;
62mod map;
63
64pub use file_data::FileData;
65pub use load::{load, load_stdin};
66pub use map::map_file;