1 | #![allow (clippy::all)] |
2 | // only used on Linux right now, so allow dead code elsewhere |
3 | #![cfg_attr (not(target_os = "linux" ), allow(dead_code))] |
4 | |
5 | use super::Mmap; |
6 | use alloc::vec; |
7 | use alloc::vec::Vec; |
8 | use core::cell::UnsafeCell; |
9 | |
10 | /// A simple arena allocator for byte buffers. |
11 | pub struct Stash { |
12 | buffers: UnsafeCell<Vec<Vec<u8>>>, |
13 | mmaps: UnsafeCell<Vec<Mmap>>, |
14 | } |
15 | |
16 | impl Stash { |
17 | pub fn new() -> Stash { |
18 | Stash { |
19 | buffers: UnsafeCell::new(Vec::new()), |
20 | mmaps: UnsafeCell::new(Vec::new()), |
21 | } |
22 | } |
23 | |
24 | /// Allocates a buffer of the specified size and returns a mutable reference |
25 | /// to it. |
26 | pub fn allocate(&self, size: usize) -> &mut [u8] { |
27 | // SAFETY: this is the only function that ever constructs a mutable |
28 | // reference to `self.buffers`. |
29 | let buffers = unsafe { &mut *self.buffers.get() }; |
30 | let i = buffers.len(); |
31 | buffers.push(vec![0; size]); |
32 | // SAFETY: we never remove elements from `self.buffers`, so a reference |
33 | // to the data inside any buffer will live as long as `self` does. |
34 | &mut buffers[i] |
35 | } |
36 | |
37 | /// Stores a `Mmap` for the lifetime of this `Stash`, returning a pointer |
38 | /// which is scoped to just this lifetime. |
39 | pub fn cache_mmap(&self, map: Mmap) -> &[u8] { |
40 | // SAFETY: this is the only location for a mutable pointer to |
41 | // `mmaps`, and this structure isn't threadsafe to shared across |
42 | // threads either. We also never remove elements from `self.mmaps`, |
43 | // so a reference to the data inside the map will live as long as |
44 | // `self` does. |
45 | unsafe { |
46 | let mmaps = &mut *self.mmaps.get(); |
47 | mmaps.push(map); |
48 | mmaps.last().unwrap() |
49 | } |
50 | } |
51 | } |
52 | |