#[cfg_attr(unix, path = "unix.rs")]
#[cfg_attr(windows, path = "windows.rs")]
#[cfg_attr(not(any(unix, windows)), path = "stub.rs")]
mod os;
use crate::os::{file_len, MmapInner};
#[cfg(unix)]
mod advice;
#[cfg(unix)]
pub use crate::advice::Advice;
use std::fmt;
#[cfg(not(any(unix, windows)))]
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::isize;
use std::mem;
use std::ops::{Deref, DerefMut};
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawHandle, RawHandle};
use std::slice;
#[cfg(not(any(unix, windows)))]
pub struct MmapRawDescriptor<'a>(&'a File);
#[cfg(unix)]
pub struct MmapRawDescriptor(RawFd);
#[cfg(windows)]
pub struct MmapRawDescriptor(RawHandle);
pub trait MmapAsRawDesc {
fn as_raw_desc(&self) -> MmapRawDescriptor;
}
#[cfg(not(any(unix, windows)))]
impl MmapAsRawDesc for &File {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self)
}
}
#[cfg(unix)]
impl MmapAsRawDesc for RawFd {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(*self)
}
}
#[cfg(unix)]
impl<'a, T> MmapAsRawDesc for &'a T
where
T: AsRawFd,
{
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self.as_raw_fd())
}
}
#[cfg(windows)]
impl MmapAsRawDesc for RawHandle {
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(*self)
}
}
#[cfg(windows)]
impl<'a, T> MmapAsRawDesc for &'a T
where
T: AsRawHandle,
{
fn as_raw_desc(&self) -> MmapRawDescriptor {
MmapRawDescriptor(self.as_raw_handle())
}
}
#[derive(Clone, Debug, Default)]
pub struct MmapOptions {
offset: u64,
len: Option<usize>,
stack: bool,
populate: bool,
}
impl MmapOptions {
pub fn new() -> MmapOptions {
MmapOptions::default()
}
pub fn offset(&mut self, offset: u64) -> &mut Self {
self.offset = offset;
self
}
pub fn len(&mut self, len: usize) -> &mut Self {
self.len = Some(len);
self
}
fn get_len<T: MmapAsRawDesc>(&self, file: &T) -> Result<usize> {
self.len.map(Ok).unwrap_or_else(|| {
let desc = file.as_raw_desc();
let file_len = file_len(desc.0)?;
if file_len < self.offset {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map offset is larger than length",
));
}
let len = file_len - self.offset;
if mem::size_of::<usize>() < 8 && len > isize::MAX as u64 {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map length overflows isize",
));
}
Ok(len as usize)
})
}
pub fn stack(&mut self) -> &mut Self {
self.stack = true;
self
}
pub fn populate(&mut self) -> &mut Self {
self.populate = true;
self
}
pub unsafe fn map<T: MmapAsRawDesc>(&self, file: T) -> Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| Mmap { inner })
}
pub unsafe fn map_exec<T: MmapAsRawDesc>(&self, file: T) -> Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map_exec(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| Mmap { inner })
}
pub unsafe fn map_mut<T: MmapAsRawDesc>(&self, file: T) -> Result<MmapMut> {
let desc = file.as_raw_desc();
MmapInner::map_mut(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| MmapMut { inner })
}
pub unsafe fn map_copy<T: MmapAsRawDesc>(&self, file: T) -> Result<MmapMut> {
let desc = file.as_raw_desc();
MmapInner::map_copy(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| MmapMut { inner })
}
pub unsafe fn map_copy_read_only<T: MmapAsRawDesc>(&self, file: T) -> Result<Mmap> {
let desc = file.as_raw_desc();
MmapInner::map_copy_read_only(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| Mmap { inner })
}
pub fn map_anon(&self) -> Result<MmapMut> {
let len = self.len.unwrap_or(0);
if mem::size_of::<usize>() < 8 && len > isize::MAX as usize {
return Err(Error::new(
ErrorKind::InvalidData,
"memory map length overflows isize",
));
}
MmapInner::map_anon(len, self.stack, self.populate).map(|inner| MmapMut { inner })
}
pub fn map_raw<T: MmapAsRawDesc>(&self, file: T) -> Result<MmapRaw> {
let desc = file.as_raw_desc();
MmapInner::map_mut(self.get_len(&file)?, desc.0, self.offset, self.populate)
.map(|inner| MmapRaw { inner })
}
}
pub struct Mmap {
inner: MmapInner,
}
impl Mmap {
pub unsafe fn map<T: MmapAsRawDesc>(file: T) -> Result<Mmap> {
MmapOptions::new().map(file)
}
pub fn make_mut(mut self) -> Result<MmapMut> {
self.inner.make_mut()?;
Ok(MmapMut { inner: self.inner })
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> Result<()> {
self.inner.advise(advice, 0, self.inner.len())
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> Result<()> {
self.inner.advise(advice, offset, len)
}
#[cfg(unix)]
pub fn lock(&mut self) -> Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&mut self) -> Result<()> {
self.inner.unlock()
}
}
#[cfg(feature = "stable_deref_trait")]
unsafe impl stable_deref_trait::StableDeref for Mmap {}
impl Deref for Mmap {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.inner.ptr(), self.inner.len()) }
}
}
impl AsRef<[u8]> for Mmap {
#[inline]
fn as_ref(&self) -> &[u8] {
self.deref()
}
}
impl fmt::Debug for Mmap {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Mmap")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
pub struct MmapRaw {
inner: MmapInner,
}
impl MmapRaw {
pub fn map_raw<T: MmapAsRawDesc>(file: T) -> Result<MmapRaw> {
MmapOptions::new().map_raw(file)
}
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.inner.ptr()
}
#[inline]
pub fn as_mut_ptr(&self) -> *mut u8 {
self.inner.ptr() as _
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn flush(&self) -> Result<()> {
let len = self.len();
self.inner.flush(0, len)
}
pub fn flush_async(&self) -> Result<()> {
let len = self.len();
self.inner.flush_async(0, len)
}
pub fn flush_range(&self, offset: usize, len: usize) -> Result<()> {
self.inner.flush(offset, len)
}
pub fn flush_async_range(&self, offset: usize, len: usize) -> Result<()> {
self.inner.flush_async(offset, len)
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> Result<()> {
self.inner.advise(advice, 0, self.inner.len())
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> Result<()> {
self.inner.advise(advice, offset, len)
}
#[cfg(unix)]
pub fn lock(&mut self) -> Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&mut self) -> Result<()> {
self.inner.unlock()
}
}
impl fmt::Debug for MmapRaw {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("MmapRaw")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
impl From<Mmap> for MmapRaw {
fn from(value: Mmap) -> Self {
Self { inner: value.inner }
}
}
impl From<MmapMut> for MmapRaw {
fn from(value: MmapMut) -> Self {
Self { inner: value.inner }
}
}
pub struct MmapMut {
inner: MmapInner,
}
impl MmapMut {
pub unsafe fn map_mut<T: MmapAsRawDesc>(file: T) -> Result<MmapMut> {
MmapOptions::new().map_mut(file)
}
pub fn map_anon(length: usize) -> Result<MmapMut> {
MmapOptions::new().len(length).map_anon()
}
pub fn flush(&self) -> Result<()> {
let len = self.len();
self.inner.flush(0, len)
}
pub fn flush_async(&self) -> Result<()> {
let len = self.len();
self.inner.flush_async(0, len)
}
pub fn flush_range(&self, offset: usize, len: usize) -> Result<()> {
self.inner.flush(offset, len)
}
pub fn flush_async_range(&self, offset: usize, len: usize) -> Result<()> {
self.inner.flush_async(offset, len)
}
pub fn make_read_only(mut self) -> Result<Mmap> {
self.inner.make_read_only()?;
Ok(Mmap { inner: self.inner })
}
pub fn make_exec(mut self) -> Result<Mmap> {
self.inner.make_exec()?;
Ok(Mmap { inner: self.inner })
}
#[cfg(unix)]
pub fn advise(&self, advice: Advice) -> Result<()> {
self.inner.advise(advice, 0, self.inner.len())
}
#[cfg(unix)]
pub fn advise_range(&self, advice: Advice, offset: usize, len: usize) -> Result<()> {
self.inner.advise(advice, offset, len)
}
#[cfg(unix)]
pub fn lock(&mut self) -> Result<()> {
self.inner.lock()
}
#[cfg(unix)]
pub fn unlock(&mut self) -> Result<()> {
self.inner.unlock()
}
}
#[cfg(feature = "stable_deref_trait")]
unsafe impl stable_deref_trait::StableDeref for MmapMut {}
impl Deref for MmapMut {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.inner.ptr(), self.inner.len()) }
}
}
impl DerefMut for MmapMut {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.inner.mut_ptr(), self.inner.len()) }
}
}
impl AsRef<[u8]> for MmapMut {
#[inline]
fn as_ref(&self) -> &[u8] {
self.deref()
}
}
impl AsMut<[u8]> for MmapMut {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.deref_mut()
}
}
impl fmt::Debug for MmapMut {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("MmapMut")
.field("ptr", &self.as_ptr())
.field("len", &self.len())
.finish()
}
}
#[cfg(test)]
mod test {
extern crate tempfile;
#[cfg(unix)]
use crate::advice::Advice;
use std::fs::OpenOptions;
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
#[cfg(windows)]
use std::os::windows::fs::OpenOptionsExt;
#[cfg(windows)]
const GENERIC_ALL: u32 = 0x10000000;
use super::{Mmap, MmapMut, MmapOptions};
#[test]
fn map_file() {
let expected_len = 128;
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(expected_len as u64).unwrap();
let mut mmap = unsafe { MmapMut::map_mut(&file).unwrap() };
let len = mmap.len();
assert_eq!(expected_len, len);
let zeros = vec![0; len];
let incr: Vec<u8> = (0..len as u8).collect();
assert_eq!(&zeros[..], &mmap[..]);
(&mut mmap[..]).write_all(&incr[..]).unwrap();
assert_eq!(&incr[..], &mmap[..]);
}
#[test]
#[cfg(unix)]
fn map_fd() {
let expected_len = 128;
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(expected_len as u64).unwrap();
let mut mmap = unsafe { MmapMut::map_mut(file.as_raw_fd()).unwrap() };
let len = mmap.len();
assert_eq!(expected_len, len);
let zeros = vec![0; len];
let incr: Vec<u8> = (0..len as u8).collect();
assert_eq!(&zeros[..], &mmap[..]);
(&mut mmap[..]).write_all(&incr[..]).unwrap();
assert_eq!(&incr[..], &mmap[..]);
}
#[test]
fn map_empty_file() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
let mmap = unsafe { Mmap::map(&file).unwrap() };
assert!(mmap.is_empty());
let mmap = unsafe { MmapMut::map_mut(&file).unwrap() };
assert!(mmap.is_empty());
}
#[test]
fn map_anon() {
let expected_len = 128;
let mut mmap = MmapMut::map_anon(expected_len).unwrap();
let len = mmap.len();
assert_eq!(expected_len, len);
let zeros = vec![0; len];
let incr: Vec<u8> = (0..len as u8).collect();
assert_eq!(&zeros[..], &mmap[..]);
(&mut mmap[..]).write_all(&incr[..]).unwrap();
assert_eq!(&incr[..], &mmap[..]);
}
#[test]
fn map_anon_zero_len() {
assert!(MmapOptions::new().map_anon().unwrap().is_empty())
}
#[test]
#[cfg(target_pointer_width = "32")]
fn map_anon_len_overflow() {
let res = MmapMut::map_anon(0x80000000);
assert_eq!(
res.unwrap_err().to_string(),
"memory map length overflows isize"
);
}
#[test]
fn file_write() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(128).unwrap();
let write = b"abc123";
let mut read = [0u8; 6];
let mut mmap = unsafe { MmapMut::map_mut(&file).unwrap() };
(&mut mmap[..]).write_all(write).unwrap();
mmap.flush().unwrap();
file.read_exact(&mut read).unwrap();
assert_eq!(write, &read);
}
#[test]
fn flush_range() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(128).unwrap();
let write = b"abc123";
let mut mmap = unsafe {
MmapOptions::new()
.offset(2)
.len(write.len())
.map_mut(&file)
.unwrap()
};
(&mut mmap[..]).write_all(write).unwrap();
mmap.flush_async_range(0, write.len()).unwrap();
mmap.flush_range(0, write.len()).unwrap();
}
#[test]
fn map_copy() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(128).unwrap();
let nulls = b"\0\0\0\0\0\0";
let write = b"abc123";
let mut read = [0u8; 6];
let mut mmap = unsafe { MmapOptions::new().map_copy(&file).unwrap() };
(&mut mmap[..]).write_all(write).unwrap();
mmap.flush().unwrap();
(&mmap[..]).read_exact(&mut read).unwrap();
assert_eq!(write, &read);
file.read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
let mmap2 = unsafe { MmapOptions::new().map(&file).unwrap() };
(&mmap2[..]).read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
}
#[test]
fn map_copy_read_only() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(128).unwrap();
let nulls = b"\0\0\0\0\0\0";
let mut read = [0u8; 6];
let mmap = unsafe { MmapOptions::new().map_copy_read_only(&file).unwrap() };
(&mmap[..]).read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
let mmap2 = unsafe { MmapOptions::new().map(&file).unwrap() };
(&mmap2[..]).read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
}
#[test]
fn map_offset() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
let offset = u32::max_value() as u64 + 2;
let len = 5432;
file.set_len(offset + len as u64).unwrap();
let mmap = unsafe { MmapOptions::new().offset(offset).map_mut(&file).unwrap() };
assert_eq!(len, mmap.len());
let mut mmap = unsafe {
MmapOptions::new()
.offset(offset)
.len(len)
.map_mut(&file)
.unwrap()
};
assert_eq!(len, mmap.len());
let zeros = vec![0; len];
let incr: Vec<_> = (0..len).map(|i| i as u8).collect();
assert_eq!(&zeros[..], &mmap[..]);
(&mut mmap[..]).write_all(&incr[..]).unwrap();
assert_eq!(&incr[..], &mmap[..]);
}
#[test]
fn index() {
let mut mmap = MmapMut::map_anon(128).unwrap();
mmap[0] = 42;
assert_eq!(42, mmap[0]);
}
#[test]
fn sync_send() {
let mmap = MmapMut::map_anon(129).unwrap();
fn is_sync_send<T>(_val: T)
where
T: Sync + Send,
{
}
is_sync_send(mmap);
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn jit_x86(mut mmap: MmapMut) {
mmap[0] = 0xB8; mmap[1] = 0xAB;
mmap[2] = 0x00;
mmap[3] = 0x00;
mmap[4] = 0x00;
mmap[5] = 0xC3;
let mmap = mmap.make_exec().expect("make_exec");
let jitfn: extern "C" fn() -> u8 = unsafe { std::mem::transmute(mmap.as_ptr()) };
assert_eq!(jitfn(), 0xab);
}
#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn jit_x86_anon() {
jit_x86(MmapMut::map_anon(4096).unwrap());
}
#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn jit_x86_file() {
let tempdir = tempfile::tempdir().unwrap();
let mut options = OpenOptions::new();
#[cfg(windows)]
options.access_mode(GENERIC_ALL);
let file = options
.read(true)
.write(true)
.create(true)
.open(&tempdir.path().join("jit_x86"))
.expect("open");
file.set_len(4096).expect("set_len");
jit_x86(unsafe { MmapMut::map_mut(&file).expect("map_mut") });
}
#[test]
fn mprotect_file() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let mut options = OpenOptions::new();
#[cfg(windows)]
options.access_mode(GENERIC_ALL);
let mut file = options
.read(true)
.write(true)
.create(true)
.open(&path)
.expect("open");
file.set_len(256_u64).expect("set_len");
let mmap = unsafe { MmapMut::map_mut(&file).expect("map_mut") };
let mmap = mmap.make_read_only().expect("make_read_only");
let mut mmap = mmap.make_mut().expect("make_mut");
let write = b"abc123";
let mut read = [0u8; 6];
(&mut mmap[..]).write_all(write).unwrap();
mmap.flush().unwrap();
(&mmap[..]).read_exact(&mut read).unwrap();
assert_eq!(write, &read);
file.read_exact(&mut read).unwrap();
assert_eq!(write, &read);
let mmap2 = unsafe { MmapOptions::new().map(&file).unwrap() };
(&mmap2[..]).read_exact(&mut read).unwrap();
assert_eq!(write, &read);
let mmap = mmap.make_exec().expect("make_exec");
drop(mmap);
}
#[test]
fn mprotect_copy() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap");
let mut options = OpenOptions::new();
#[cfg(windows)]
options.access_mode(GENERIC_ALL);
let mut file = options
.read(true)
.write(true)
.create(true)
.open(&path)
.expect("open");
file.set_len(256_u64).expect("set_len");
let mmap = unsafe { MmapOptions::new().map_copy(&file).expect("map_mut") };
let mmap = mmap.make_read_only().expect("make_read_only");
let mut mmap = mmap.make_mut().expect("make_mut");
let nulls = b"\0\0\0\0\0\0";
let write = b"abc123";
let mut read = [0u8; 6];
(&mut mmap[..]).write_all(write).unwrap();
mmap.flush().unwrap();
(&mmap[..]).read_exact(&mut read).unwrap();
assert_eq!(write, &read);
file.read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
let mmap2 = unsafe { MmapOptions::new().map(&file).unwrap() };
(&mmap2[..]).read_exact(&mut read).unwrap();
assert_eq!(nulls, &read);
let mmap = mmap.make_exec().expect("make_exec");
drop(mmap);
}
#[test]
fn mprotect_anon() {
let mmap = MmapMut::map_anon(256).expect("map_mut");
let mmap = mmap.make_read_only().expect("make_read_only");
let mmap = mmap.make_mut().expect("make_mut");
let mmap = mmap.make_exec().expect("make_exec");
drop(mmap);
}
#[test]
fn raw() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmapraw");
let mut options = OpenOptions::new();
let mut file = options
.read(true)
.write(true)
.create(true)
.open(&path)
.expect("open");
file.write_all(b"abc123").unwrap();
let mmap = MmapOptions::new().map_raw(&file).unwrap();
assert_eq!(mmap.len(), 6);
assert!(!mmap.as_ptr().is_null());
assert_eq!(unsafe { std::ptr::read(mmap.as_ptr()) }, b'a');
}
#[test]
#[cfg(feature = "stable_deref_trait")]
fn owning_ref() {
extern crate owning_ref;
let mut map = MmapMut::map_anon(128).unwrap();
map[10] = 42;
let owning = owning_ref::OwningRef::new(map);
let sliced = owning.map(|map| &map[10..20]);
assert_eq!(42, sliced[0]);
let map = sliced.into_owner().make_read_only().unwrap();
let owning = owning_ref::OwningRef::new(map);
let sliced = owning.map(|map| &map[10..20]);
assert_eq!(42, sliced[0]);
}
#[test]
#[cfg(unix)]
fn advise() {
let expected_len = 128;
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap_advise");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(expected_len as u64).unwrap();
let mut mmap = unsafe { MmapMut::map_mut(&file).unwrap() };
mmap.advise(Advice::Random)
.expect("mmap advising should be supported on unix");
let len = mmap.len();
assert_eq!(expected_len, len);
let zeros = vec![0; len];
let incr: Vec<u8> = (0..len as u8).collect();
assert_eq!(&zeros[..], &mmap[..]);
mmap.advise_range(Advice::Sequential, 0, mmap.len())
.expect("mmap advising should be supported on unix");
(&mut mmap[..]).write_all(&incr[..]).unwrap();
assert_eq!(&incr[..], &mmap[..]);
let mmap = unsafe { Mmap::map(&file).unwrap() };
mmap.advise(Advice::Random)
.expect("mmap advising should be supported on unix");
assert_eq!(&incr[..], &mmap[..]);
}
#[cfg(target_os = "linux")]
fn is_locked() -> bool {
let status = &std::fs::read_to_string("/proc/self/status")
.expect("/proc/self/status should be available");
for line in status.lines() {
if line.starts_with("VmLck:") {
let numbers = line.replace(|c: char| !c.is_ascii_digit(), "");
return numbers != "0";
}
}
panic!("cannot get VmLck information")
}
#[test]
#[cfg(unix)]
fn lock() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("mmap_lock");
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)
.unwrap();
file.set_len(128).unwrap();
let mut mmap = unsafe { Mmap::map(&file).unwrap() };
#[cfg(target_os = "linux")]
assert!(!is_locked());
mmap.lock().expect("mmap lock should be supported on unix");
#[cfg(target_os = "linux")]
assert!(is_locked());
mmap.lock()
.expect("mmap lock again should not cause problems");
#[cfg(target_os = "linux")]
assert!(is_locked());
mmap.unlock()
.expect("mmap unlock should be supported on unix");
#[cfg(target_os = "linux")]
assert!(!is_locked());
mmap.unlock()
.expect("mmap unlock again should not cause problems");
#[cfg(target_os = "linux")]
assert!(!is_locked());
}
}