ps_mmap/
lib.rs

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
mod error;
mod guards;
mod readable;
mod writable;

pub use error::PsMmapError;
pub use guards::{ReadGuard, WriteGuard};
pub use readable::ReadableMemoryMap;
pub use writable::WritableMemoryMap;

#[derive(Clone, Debug)]
pub enum MemoryMap {
    Readable(ReadableMemoryMap),
    Writable(WritableMemoryMap),
}

impl MemoryMap {
    pub fn map_readable(file_path: &str) -> Result<Self, PsMmapError> {
        Ok(Self::Readable(ReadableMemoryMap::map(file_path)?))
    }

    pub fn map_writable(file_path: &str) -> Result<Self, PsMmapError> {
        Ok(Self::Writable(WritableMemoryMap::map(file_path)?))
    }

    pub fn read(&self) -> ReadGuard {
        self.into()
    }

    pub fn into_read(self) -> ReadGuard {
        self.into()
    }

    pub fn try_write(&self) -> Result<WriteGuard, PsMmapError> {
        self.try_into()
    }

    pub fn try_into_write(self) -> Result<WriteGuard, PsMmapError> {
        self.try_into()
    }

    pub fn read_with<F, R>(&self, closure: F) -> R
    where
        F: FnOnce(&[u8]) -> R,
    {
        match self {
            Self::Readable(mmap) => closure(mmap),
            Self::Writable(mmap) => closure(&mmap.read()),
        }
    }

    pub fn try_write_with<F, R>(&self, closure: F) -> Result<R, PsMmapError>
    where
        F: FnOnce(&mut [u8]) -> R,
    {
        match self {
            Self::Readable(_) => Err(PsMmapError::ReadOnly),
            Self::Writable(mmap) => Ok(closure(&mut mmap.write())),
        }
    }

    pub fn as_ptr(&self) -> *const u8 {
        match self {
            Self::Readable(value) => value.as_ptr(),
            Self::Writable(value) => value.as_ptr(),
        }
    }

    pub fn try_as_mut_ptr(&self) -> Result<*mut u8, PsMmapError> {
        match self {
            Self::Readable(_) => Err(PsMmapError::ReadOnly),
            Self::Writable(value) => Ok(value.as_mut_ptr()),
        }
    }
}