pub struct Mmap { /* private fields */ }Expand description
A read-only, private memory map of an open file.
The map is never written. It keeps the mapped pages alive on its own,
so the caller can close the file descriptor after
Mmap::read_only returns.
§Truncation
A read of a mapped page with no file bytes behind it raises SIGBUS.
No safe API can expose this signal, so Mmap::read_only measures the
file and refuses a map longer than the file. Mmap::as_slice is
sound for the whole life of the map if no writer truncates the file.
The caller must map only a file that no other writer can truncate.
Implementations§
Source§impl Mmap
impl Mmap
Sourcepub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap>
pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap>
Maps the first len bytes of fd read-only.
len must be larger than zero and not larger than the size of the
file. Because the function refuses a len larger than the file, a
read of the map cannot raise SIGBUS while the file keeps its size.
§Errors
- An
Errnofromfstatif the function cannot read the size of the file. EINVALiflenis larger than the size of the file.EINVALfrommmapiflenis zero.- Another
Errnofrommmap, for exampleEACCESiffdis not open for reading.
§Examples
use std::fs::File;
use ostrya_sys::Mmap;
let path = std::env::temp_dir().join(format!("ostrya-sys-doc-{}", std::process::id()));
std::fs::write(&path, b"ostree")?;
let file = File::open(&path)?;
assert!(Mmap::read_only(&file, 7).is_err(), "longer than the file");
let map = Mmap::read_only(&file, 6)?;
// The map stays valid after the descriptor closes.
drop(file);
assert_eq!(map.as_slice(), b"ostree");
std::fs::remove_file(&path)?;Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the map covers zero bytes.
The result is always false, because Mmap::read_only refuses a
length of zero.