3 use std::ops::{Deref, DerefMut};
5 use crate::owning_ref::StableAddress;
7 /// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`].
8 #[cfg(not(target_arch = "wasm32"))]
9 pub struct Mmap(memmap2::Mmap);
11 #[cfg(target_arch = "wasm32")]
12 pub struct Mmap(Vec<u8>);
14 #[cfg(not(target_arch = "wasm32"))]
17 pub unsafe fn map(file: File) -> io::Result<Self> {
18 memmap2::Mmap::map(&file).map(Mmap)
22 #[cfg(target_arch = "wasm32")]
25 pub unsafe fn map(mut file: File) -> io::Result<Self> {
28 let mut data = Vec::new();
29 file.read_to_end(&mut data)?;
38 fn deref(&self) -> &[u8] {
43 // SAFETY: On architectures other than WASM, mmap is used as backing storage. The address of this
44 // memory map is stable. On WASM, `Vec<u8>` is used as backing storage. The `Mmap` type doesn't
45 // export any function that can cause the `Vec` to be re-allocated. As such the address of the
46 // bytes inside this `Vec` is stable.
47 unsafe impl StableAddress for Mmap {}
49 #[cfg(not(target_arch = "wasm32"))]
50 pub struct MmapMut(memmap2::MmapMut);
52 #[cfg(target_arch = "wasm32")]
53 pub struct MmapMut(Vec<u8>);
55 #[cfg(not(target_arch = "wasm32"))]
58 pub fn map_anon(len: usize) -> io::Result<Self> {
59 let mmap = memmap2::MmapMut::map_anon(len)?;
64 pub fn flush(&mut self) -> io::Result<()> {
69 pub fn make_read_only(self) -> std::io::Result<Mmap> {
70 let mmap = self.0.make_read_only()?;
75 #[cfg(target_arch = "wasm32")]
78 pub fn map_anon(len: usize) -> io::Result<Self> {
79 let data = Vec::with_capacity(len);
84 pub fn flush(&mut self) -> io::Result<()> {
89 pub fn make_read_only(self) -> std::io::Result<Mmap> {
94 impl Deref for MmapMut {
98 fn deref(&self) -> &[u8] {
103 impl DerefMut for MmapMut {
105 fn deref_mut(&mut self) -> &mut [u8] {