Skip to main content

MmapOptions

Struct MmapOptions 

pub struct MmapOptions { /* private fields */ }
Expand description

A memory map builder, providing advanced options and flags for specifying memory map behavior.

MmapOptions can be used to create an anonymous memory map using map_anon(), or a file-backed memory map using one of map(), map_mut(), map_exec(), map_copy(), or map_copy_read_only().

§Safety

All file-backed memory map constructors are marked unsafe because of the potential for Undefined Behavior (UB) using the map if the underlying file is subsequently modified, in or out of process. Applications must consider the risk and take appropriate precautions when using file-backed maps. Solutions such as file permissions, locks or process-private (e.g. unlinked) files exist but are platform specific and limited.

Implementations§

§

impl MmapOptions

pub fn new() -> MmapOptions

Creates a new set of options for configuring and creating a memory map.

§Example
use memmap2::{MmapMut, MmapOptions};

// Create a new memory map builder.
let mut mmap_options = MmapOptions::new();

// Configure the memory map builder using option setters, then create
// a memory map using one of `mmap_options.map_anon`, `mmap_options.map`,
// `mmap_options.map_mut`, `mmap_options.map_exec`, or `mmap_options.map_copy`:
let mut mmap: MmapMut = mmap_options.len(36).map_anon()?;

// Use the memory map:
mmap.copy_from_slice(b"...data to copy to the memory map...");

pub fn offset(&mut self, offset: u64) -> &mut MmapOptions

Configures the memory map to start at byte offset from the beginning of the file.

This option has no effect on anonymous memory maps.

By default, the offset is 0.

§Example
use memmap2::MmapOptions;
use std::fs::File;

let mmap = unsafe {
    MmapOptions::new()
                .offset(30)
                .map(&File::open("LICENSE-APACHE")?)?
};
assert_eq!(&b"Apache License"[..],
           &mmap[..14]);

pub fn len(&mut self, len: usize) -> &mut MmapOptions

Configures the created memory mapped buffer to be len bytes long.

This option is mandatory for anonymous memory maps.

For file-backed memory maps, the length will default to the file length.

§Example
use memmap2::MmapOptions;
use std::fs::File;

let mmap = unsafe {
    MmapOptions::new()
                .len(9)
                .map(&File::open("README.md")?)?
};
assert_eq!(&b"# memmap2"[..], &mmap[..]);

pub fn stack(&mut self) -> &mut MmapOptions

Configures the anonymous memory map to be suitable for a process or thread stack.

This option corresponds to the MAP_STACK flag on Linux. It has no effect on Windows.

This option has no effect on file-backed memory maps.

§Example
use memmap2::MmapOptions;

let stack = MmapOptions::new().stack().len(4096).map_anon();

pub fn huge(&mut self, page_bits: Option<u8>) -> &mut MmapOptions

Configures the anonymous memory map to be allocated using huge pages.

This option corresponds to the MAP_HUGETLB flag on Linux. It has no effect on Windows.

The size of the requested page can be specified in page bits. If not provided, the system default is requested. The requested length should be a multiple of this, or the mapping will fail.

This option has no effect on file-backed memory maps.

§Example
use memmap2::MmapOptions;

let stack = MmapOptions::new().huge(Some(21)).len(2*1024*1024).map_anon();

The number 21 corresponds to MAP_HUGE_2MB. See mmap(2) for more details.

pub fn populate(&mut self) -> &mut MmapOptions

Populate (prefault) page tables for a mapping.

For a file mapping, this causes read-ahead on the file. This will help to reduce blocking on page faults later.

This option corresponds to the MAP_POPULATE flag on Linux. It has no effect on Windows.

§Example
use memmap2::MmapOptions;
use std::fs::File;

let file = File::open("LICENSE-MIT")?;

let mmap = unsafe {
    MmapOptions::new().populate().map(&file)?
};

assert_eq!(&b"Copyright"[..], &mmap[..9]);

pub fn no_reserve_swap(&mut self) -> &mut MmapOptions

Do not reserve swap space for the memory map.

By default, platforms may reserve swap space for memory maps. This guarantees that a write to the mapped memory will succeed, even if physical memory is exhausted. Otherwise, the write to memory could fail (on Linux with a segfault).

This option requests that no swap space will be allocated for the memory map, which can be useful for extremely large maps that are only written to sparsely.

This option is currently supported on Linux, Android, Apple platforms (macOS, iOS, visionOS, etc.), NetBSD, Solaris and Illumos. On those platforms, this option corresponds to the MAP_NORESERVE flag. On Linux, this option is ignored if vm.overcommit_memory is set to 2.

§Example
use memmap2::MmapOptions;
use std::fs::File;

let file = File::open("LICENSE-MIT")?;

let mmap = unsafe {
    MmapOptions::new().no_reserve_swap().map_copy(&file)?
};

assert_eq!(&b"Copyright"[..], &mmap[..9]);

pub unsafe fn map<T>(&self, file: T) -> Result<Mmap, Error>
where T: MmapAsRawDesc,

Creates a read-only memory map backed by a file.

§Safety

See the type-level docs for why this function is unsafe.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with read permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

§Example
use memmap2::MmapOptions;
use std::fs::File;
use std::io::Read;

let mut file = File::open("LICENSE-APACHE")?;

let mut contents = Vec::new();
file.read_to_end(&mut contents)?;

let mmap = unsafe {
    MmapOptions::new().map(&file)?
};

assert_eq!(&contents[..], &mmap[..]);

pub unsafe fn map_exec<T>(&self, file: T) -> Result<Mmap, Error>
where T: MmapAsRawDesc,

Creates a readable and executable memory map backed by a file.

§Safety

See the type-level docs for why this function is unsafe.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with read permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

pub unsafe fn map_mut<T>(&self, file: T) -> Result<MmapMut, Error>
where T: MmapAsRawDesc,

Creates a writeable memory map backed by a file.

§Safety

See the type-level docs for why this function is unsafe.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with read and write permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

§Example
use std::fs::OpenOptions;
use std::path::PathBuf;

use memmap2::MmapOptions;
let path: PathBuf = /* path to file */
let file = OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path)?;
file.set_len(13)?;

let mut mmap = unsafe {
    MmapOptions::new().map_mut(&file)?
};

mmap.copy_from_slice(b"Hello, world!");

pub unsafe fn map_copy<T>(&self, file: T) -> Result<MmapMut, Error>
where T: MmapAsRawDesc,

Creates a copy-on-write memory map backed by a file.

Data written to the memory map will not be visible by other processes, and will not be carried through to the underlying file.

§Safety

See the type-level docs for why this function is unsafe.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with writable permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

§Example
use memmap2::MmapOptions;
use std::fs::File;
use std::io::Write;

let file = File::open("LICENSE-APACHE")?;
let mut mmap = unsafe { MmapOptions::new().map_copy(&file)? };
(&mut mmap[..]).write_all(b"Hello, world!")?;

pub unsafe fn map_copy_read_only<T>(&self, file: T) -> Result<Mmap, Error>
where T: MmapAsRawDesc,

Creates a copy-on-write read-only memory map backed by a file.

§Safety

See the type-level docs for why this function is unsafe.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with read permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

§Example
use memmap2::MmapOptions;
use std::fs::File;
use std::io::Read;

let mut file = File::open("README.md")?;

let mut contents = Vec::new();
file.read_to_end(&mut contents)?;

let mmap = unsafe {
    MmapOptions::new().map_copy_read_only(&file)?
};

assert_eq!(&contents[..], &mmap[..]);

pub fn map_anon(&self) -> Result<MmapMut, Error>

Creates an anonymous memory map.

The memory map length should be configured using MmapOptions::len() before creating an anonymous memory map, otherwise a zero-length mapping will be crated.

§Errors

This method returns an error when the underlying system call fails or when len > isize::MAX.

Returns ErrorKind::Unsupported on unsupported platforms.

pub fn map_raw<T>(&self, file: T) -> Result<MmapRaw, Error>
where T: MmapAsRawDesc,

Creates a raw memory map.

§Errors

This method returns an error when the underlying system call fails, which can happen for a variety of reasons, such as when the file is not open with read and write permissions.

Returns ErrorKind::Unsupported on unsupported platforms.

pub fn map_raw_read_only<T>(&self, file: T) -> Result<MmapRaw, Error>
where T: MmapAsRawDesc,

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.

Returns ErrorKind::Unsupported on unsupported platforms.

Trait Implementations§

§

impl Clone for MmapOptions

§

fn clone(&self) -> MmapOptions

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for MmapOptions

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for MmapOptions

§

fn default() -> MmapOptions

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> Ungil for T
where T: Send,