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
//! Mutex-locked Allocator for use as `#[global_allocator]`.

use crate::Allocator;
use alloc::alloc::Layout;
use core::alloc::GlobalAlloc;
use core::ops::Deref;
use core::ptr::NonNull;
use spin::Mutex;

/// A locked Allocator, which can be used as `#[global_allocator]`.
pub struct LockedAllocator(Mutex<Allocator>);

impl LockedAllocator {
    /// Creates an empty LockedAllocator with no regions.
    pub const fn empty() -> LockedAllocator {
        LockedAllocator(Mutex::new(Allocator::empty()))
    }
}

impl Deref for LockedAllocator {
    type Target = Mutex<Allocator>;

    fn deref(&self) -> &Mutex<Allocator> {
        &self.0
    }
}

unsafe impl GlobalAlloc for LockedAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.0
            .lock()
            .allocate(layout)
            .ok()
            .map_or(0 as *mut u8, |a| a.as_ptr())
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        self.0
            .lock()
            .deallocate(NonNull::new_unchecked(ptr), layout);
    }
}