https://doc.rust-lang.org/alloc/

https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/the-stack-and-the-heap.html

crate ::alloc::

  • Provides: smart pointer and heap management
  • use alloc::* with #![no_std]

Pointers

Box the smart pointer type (to objects in the heap):

  • there can only be one owner of Box
  • Owner can decide to mutate the content.
  • Restrive inherited mutability

Rc the reference counted pointer

  • reference counter is NOT THREAD SAFE, is meant for intra-thread sharing.
  • Rc wraps type T, only allows access to &T
  • Often paired with Cell or RefCell

Arc the atomic reference counted pointer

  • threadsafe equivalent of Rc type

Heap interfaces

alloc::alloc Memory allocation APIs

#![allow(unused)]
fn main() {
// trait GlobalAlloc
// Register memory allocator as std's default.

#[global_allocator]
pub static GLOBAL_ALLOCATOR: MyAllocator = MyAllocator::New();

impl GlobalAlloc for MyAllocator {
    // Required methods
    unsafe fn alloc(&self, layout: Layout) -> *mut u8;
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);

    // Provided methods
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { ... }
    unsafe fn realloc(
        &self,
        ptr: *mut u8,
        layout: Layout,
        new_size: usize
    ) -> *mut u8 { ... }
}
}