1use crate::{read_file_size, validate};
2use core::{ffi::CStr, ptr::null_mut, slice};
3
4pub struct Mmap {
6 ptr: *mut u8,
7 len: usize,
8}
9
10impl Mmap {
11 pub fn new(path: &CStr) -> Self {
13 let len = read_file_size(path);
14
15 Self {
16 ptr: unsafe {
17 libc::mmap(
18 null_mut(),
19 len,
20 libc::PROT_READ,
21 libc::MAP_PRIVATE,
22 libc::open(path.as_ptr(), libc::O_RDONLY),
24 0,
25 )
26 } as _,
27 len,
28 }
29 }
30
31 pub fn as_slice(&self) -> &[u8] {
33 unsafe { slice::from_raw_parts(self.ptr, self.len) }
34 }
35}
36
37impl Drop for Mmap {
38 fn drop(&mut self) {
39 unsafe {
40 validate(libc::munmap(self.ptr as _, self.len));
41 }
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn read_file() {
51 Mmap::new(c"src/lib.rs");
52 }
53}