1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use crate::{read_file_size, validate};
use core::{ffi::CStr, ptr::null_mut, slice};

pub struct Mmap {
    ptr: *mut u8,
    len: usize,
}

impl Mmap {
    /// Creates a new mmap opening a file at a path.
    pub fn new(path: &CStr) -> Self {
        let len = read_file_size(path);

        Self {
            ptr: unsafe {
                libc::mmap(
                    null_mut(),
                    len,
                    libc::PROT_READ,
                    libc::MAP_PRIVATE,
                    // spell-checker: disable-next-line
                    libc::open(path.as_ptr(), libc::O_RDONLY),
                    0,
                )
            } as _,
            len,
        }
    }

    pub fn as_slice(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.ptr, self.len) }
    }
}

impl Drop for Mmap {
    fn drop(&mut self) {
        unsafe {
            validate(libc::munmap(self.ptr as _, self.len));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_file() {
        Mmap::new(c"src/lib.rs");
    }
}