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
//! This module provides an example file backed allocator, which can be used with
//! the scoped allocator methods provided by this crate.
//! It is a simple wrapper for the [`linked_list_allocator`] crate.

use super::Store;
use ::std::sync::Mutex;
use ::std::io;
use ::std::path::Path;
use ::std::fs::OpenOptions;
use ::std::alloc::Layout;
use ::core::ptr::NonNull;
use ::memmap2::MmapMut;
use ::linked_list_allocator::Heap;

pub struct FileBacked {
    _mmap: MmapMut,
    heap: Mutex<Heap>,
}
impl FileBacked {
    pub fn open(capacity: u64, path: &Path) -> Result<Self, io::Error> {
        let cap = capacity.try_into().map_err(|_| {
            io::Error::new(io::ErrorKind::Unsupported, "tried to allocate more than usize::MAX")
        })?;
        let file = OpenOptions::new().read(true).write(true).create(true).open(&path)?;
        file.set_len(capacity)?;
        let mut mmap = unsafe { MmapMut::map_mut(&file)? };
        let base = (&mut *mmap).as_mut_ptr();
        let heap = Mutex::new(unsafe { Heap::new(base, cap) });
        Ok(Self { _mmap: mmap, heap })
    }
}

// It seems like a bad idea to use this for your true global allocator,
// so I'm preventing that usage for now.
unsafe impl Store for FileBacked {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.heap.lock().unwrap()
            .allocate_first_fit(layout)
            .map(|x| x.as_ptr())
            .unwrap_or(::core::ptr::null_mut())
    }
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        let ptr = unsafe { NonNull::new_unchecked(ptr) };
        unsafe { self.heap.lock().unwrap().deallocate(ptr, layout); }
    }
}