]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/memmap.rs
Auto merge of #103975 - oli-obk:tracing, r=jackh726
[rust.git] / compiler / rustc_data_structures / src / memmap.rs
1 use std::fs::File;
2 use std::io;
3 use std::ops::{Deref, DerefMut};
4
5 use crate::owning_ref::StableAddress;
6
7 /// A trivial wrapper for [`memmap2::Mmap`] that implements [`StableAddress`].
8 #[cfg(not(target_arch = "wasm32"))]
9 pub struct Mmap(memmap2::Mmap);
10
11 #[cfg(target_arch = "wasm32")]
12 pub struct Mmap(Vec<u8>);
13
14 #[cfg(not(target_arch = "wasm32"))]
15 impl Mmap {
16     #[inline]
17     pub unsafe fn map(file: File) -> io::Result<Self> {
18         memmap2::Mmap::map(&file).map(Mmap)
19     }
20 }
21
22 #[cfg(target_arch = "wasm32")]
23 impl Mmap {
24     #[inline]
25     pub unsafe fn map(mut file: File) -> io::Result<Self> {
26         use std::io::Read;
27
28         let mut data = Vec::new();
29         file.read_to_end(&mut data)?;
30         Ok(Mmap(data))
31     }
32 }
33
34 impl Deref for Mmap {
35     type Target = [u8];
36
37     #[inline]
38     fn deref(&self) -> &[u8] {
39         &*self.0
40     }
41 }
42
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 {}
48
49 #[cfg(not(target_arch = "wasm32"))]
50 pub struct MmapMut(memmap2::MmapMut);
51
52 #[cfg(target_arch = "wasm32")]
53 pub struct MmapMut(Vec<u8>);
54
55 #[cfg(not(target_arch = "wasm32"))]
56 impl MmapMut {
57     #[inline]
58     pub fn map_anon(len: usize) -> io::Result<Self> {
59         let mmap = memmap2::MmapMut::map_anon(len)?;
60         Ok(MmapMut(mmap))
61     }
62
63     #[inline]
64     pub fn flush(&mut self) -> io::Result<()> {
65         self.0.flush()
66     }
67
68     #[inline]
69     pub fn make_read_only(self) -> std::io::Result<Mmap> {
70         let mmap = self.0.make_read_only()?;
71         Ok(Mmap(mmap))
72     }
73 }
74
75 #[cfg(target_arch = "wasm32")]
76 impl MmapMut {
77     #[inline]
78     pub fn map_anon(len: usize) -> io::Result<Self> {
79         let data = Vec::with_capacity(len);
80         Ok(MmapMut(data))
81     }
82
83     #[inline]
84     pub fn flush(&mut self) -> io::Result<()> {
85         Ok(())
86     }
87
88     #[inline]
89     pub fn make_read_only(self) -> std::io::Result<Mmap> {
90         Ok(Mmap(self.0))
91     }
92 }
93
94 impl Deref for MmapMut {
95     type Target = [u8];
96
97     #[inline]
98     fn deref(&self) -> &[u8] {
99         &*self.0
100     }
101 }
102
103 impl DerefMut for MmapMut {
104     #[inline]
105     fn deref_mut(&mut self) -> &mut [u8] {
106         &mut *self.0
107     }
108 }