Skip to content

Commit

Permalink
Add MmapOptions::map_raw_read_only to avoid intermediate invalid Mmap…
Browse files Browse the repository at this point in the history
… instances.
  • Loading branch information
adamreichold authored May 10, 2023
1 parent 0220b23 commit f62a3cb
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,21 @@ impl MmapOptions {
MmapInner::map_mut(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| MmapRaw { inner })
}

/// Creates a read-only raw memory map
///
/// This is primarily useful to avoid intermediate `Mmap` instances when
/// read-only access to files modified elsewhere are required.
///
/// # Errors
///
/// This method returns an error when the underlying system call fails
pub fn map_raw_read_only<T: MmapAsRawDesc>(&self, file: T) -> Result<MmapRaw> {
let desc = file.as_raw_desc();

MmapInner::map(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| MmapRaw { inner })
}
}

/// A handle to an immutable memory mapped buffer.
Expand Down Expand Up @@ -1166,7 +1181,7 @@ mod test {

#[cfg(unix)]
use crate::advice::Advice;
use std::fs::OpenOptions;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
Expand Down Expand Up @@ -1633,6 +1648,22 @@ mod test {
assert_eq!(unsafe { std::ptr::read(mmap.as_ptr()) }, b'a');
}

#[test]
fn raw_read_only() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmaprawro");

File::create(&path).unwrap().write_all(b"abc123").unwrap();

let mmap = MmapOptions::new()
.map_raw_read_only(&File::open(&path).unwrap())
.unwrap();

assert_eq!(mmap.len(), 6);
assert!(!mmap.as_ptr().is_null());
assert_eq!(unsafe { std::ptr::read(mmap.as_ptr()) }, b'a');
}

/// Something that relies on StableDeref
#[test]
#[cfg(feature = "stable_deref_trait")]
Expand Down

0 comments on commit f62a3cb

Please sign in to comment.