Course contentsShow
← Rust
Lesson 146 of 1,9102. The Ownership ModelFree lesson

Memory-Mapped File Mapping

Access disk-based files as memory addresses while adhering to safety rules.

In this lesson, you will learn how to treat the contents of a file on your disk as if they were a standard slice of memory residing in your computer's RAM.

The Concept: Files as Memory

Normally, to read a file, you use "I/O" (Input/Output) operations: you open the file, create a buffer, and copy data from the disk into that buffer. This involves multiple steps and can be slow if the file is massive.

Memory-mapping (often called mmap) bypasses this. Instead of copying data, the operating system maps the file’s address space directly into your process's virtual memory. When you read a byte from that memory address, the hardware triggers a "page fault," and the OS automatically pulls that specific piece of the file into RAM for you.

Integrating Ownership

In Rust, we must bridge the gap between "unmanaged" hardware memory and our strict ownership rules. When you map a file, the memory address returned is essentially an unsafe pointer. To make this safe, we use the patterns you’ve already mastered:

  1. RAII (Resource Acquisition Is Initialization): We wrap the memory-mapped pointer in a struct. The Drop trait is implemented to automatically unmap the memory when the struct goes out of scope.
  2. Lifetime Guarantees: We tie the lifetime of the returned slice to the lifetime of the "mapped file" object. This prevents us from accessing the memory after the file has been closed or unmapped.

Here is a simplified view of how this looks:

// The struct owns the mapping, ensuring it is unmapped when dropped
struct MmapFile {
    ptr: *const u8,
    len: usize,
}

impl MmapFile {
    // We return a reference tied to the lifetime of 'self'
    fn as_slice(&self) -> &[u8] {
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }
}

By encapsulating the unsafe pointer inside a struct that enforces ownership, we can safely treat disk storage as a read-only slice. The borrow checker ensures that as long as we hold a reference to the data, the file remains mapped, and when we are finished, the resource is cleaned up automatically.

Key Takeaway: Memory mapping allows you to access disk-based files as byte slices by using RAII to safely manage the lifetime of the underlying pointer.