smallbox2/
global_alloc.rs

1use core::alloc::Layout;
2
3// copied from stdlib
4#[cfg(all(not(feature = "std"), feature = "global_alloc_fill"))]
5extern "Rust" {
6    // These are the magic symbols to call the global allocator.  rustc generates
7    // them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
8    // (the code expanding that attribute macro generates those functions), or to call
9    // the default implementations in libstd (`__rdl_alloc` etc. in `library/std/src/alloc.rs`)
10    // otherwise.
11    // The rustc fork of LLVM also special-cases these function names to be able to optimize them
12    // like `malloc`, `realloc`, and `free`, respectively.
13    #[rustc_allocator]
14    #[rustc_allocator_nounwind]
15    fn __rust_alloc(size: usize, align: usize) -> *mut u8;
16    #[rustc_allocator_nounwind]
17    fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
18}
19
20// copied from stdlib
21#[inline(always)]
22pub unsafe fn alloc(layout: Layout) -> *mut u8 {
23    #[cfg(all(not(feature = "std"), feature = "global_alloc_fill"))]
24    return __rust_alloc(layout.size(), layout.align());
25    #[cfg(not(all(not(feature = "std"), feature = "global_alloc_fill")))]
26    std::alloc::alloc(layout)
27}
28
29// copied from stdlib
30#[inline(always)]
31pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
32    #[cfg(all(not(feature = "std"), feature = "global_alloc_fill"))]
33    return __rust_dealloc(ptr, layout.size(), layout.align());
34    #[cfg(not(all(not(feature = "std"), feature = "global_alloc_fill")))]
35    std::alloc::dealloc(ptr, layout)
36}