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
//! A simple global allocator for Rust which hooks into `libc`.
//! Useful in `no_std` + `alloc` contexts.
//!
//! Uses `posix_memalign` for allocations, and `free` for deallocations.
//!
//! ## Example
//!
//! ```
//! use libc_alloc::LibcAlloc;
//!
//! #[global_allocator]
//! static ALLOCATOR: LibcAlloc = LibcAlloc;
//! ```

#![no_std]

use core::alloc::{GlobalAlloc, Layout};
use core::ffi::c_void;

/// Global Allocator which uses `malloc` and `free` under the hood.
pub struct LibcAlloc;

unsafe impl GlobalAlloc for LibcAlloc {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let mut ptr = core::ptr::null_mut();
        // `posix_memalign` returns an error int, but we can safely ignore it:
        // - EINVAL cannot occur, as layout.align() is guaranteed to be a power of two
        // - ENOMEM will leave `ptr` as a nullptr, which we return from this method to
        //   indicate an allocation failure.
        libc::posix_memalign(
            &mut ptr,
            core::mem::size_of::<usize>() * layout.align(),
            layout.size(),
        );

        ptr as *mut u8
    }

    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
        libc::free(ptr as *mut c_void);
    }
}