embedded_storage_file/
backend_mmap.rs

1use crate::synhronous::{BufferBackend, Error, NorMemory};
2use memmap2;
3
4pub struct MmapFile {
5    pub file: std::fs::File,
6    pub mmap: memmap2::MmapMut,
7}
8
9pub type NorMemoryInFile<const READ_SIZE: usize, const WRITE_SIZE: usize, const ERASE_SIZE: usize> =
10    NorMemory<MmapFile, READ_SIZE, WRITE_SIZE, ERASE_SIZE>;
11
12impl<const READ_SIZE: usize, const WRITE_SIZE: usize, const ERASE_SIZE: usize>
13    NorMemoryInFile<READ_SIZE, WRITE_SIZE, ERASE_SIZE>
14{
15    pub fn new<P: std::convert::AsRef<std::path::Path>>(
16        path: P,
17        size: usize,
18    ) -> Result<Self, std::io::Error> {
19        let is_new = !path.as_ref().exists();
20        let file = std::fs::OpenOptions::new()
21            .read(true)
22            .write(true)
23            .create(true)
24            .open(path)?;
25        file.set_len(size as u64)?;
26        let mut mmap = unsafe { memmap2::MmapOptions::new().map_mut(&file)? };
27        if is_new {
28            for i in 0..size {
29                mmap[i] = 0xFF;
30            }
31        }
32        Ok(Self {
33            buffer: MmapFile { file, mmap },
34        })
35    }
36
37    pub fn new_from_mmap(mmap: MmapFile) -> Self {
38        Self { buffer: mmap }
39    }
40}
41
42impl BufferBackend for MmapFile {
43    fn with_data<F>(&self, from: usize, to: usize, mut f: F) -> Result<(), Error>
44    where
45        F: FnMut(&[u8]) -> Result<(), Error>,
46    {
47        if to > self.size() {
48            return Err(Error::OutOfBounds);
49        }
50        if from > to {
51            return Err(Error::OutOfBounds);
52        }
53        let b = &self.mmap[from..to];
54        f(b)
55    }
56
57    fn with_data_mut<F>(&mut self, from: usize, to: usize, mut f: F) -> Result<(), Error>
58    where
59        F: FnMut(&mut [u8]) -> Result<(), Error>,
60    {
61        if to > self.size() {
62            return Err(Error::OutOfBounds);
63        }
64        if from > to {
65            return Err(Error::OutOfBounds);
66        }
67        let b = &mut self.mmap[from..to];
68        f(b)
69    }
70
71    fn size(&self) -> usize {
72        self.mmap.len()
73    }
74}