Crate stalloc

Source
Expand description

Stalloc (Stack + alloc) is a fast first-fit memory allocator. From my benchmarking, it can be over 3x as fast as the default OS allocator! This is because all memory is allocated from the stack, which allows it to avoid all OS overhead. Since it doesn’t rely on the OS (aside from SyncStalloc), this library is no_std compatible.

use stalloc::SyncStalloc;

// Create a global allocator with 1000 blocks, each 4 bytes in length.
#[global_allocator]
static GLOBAL: SyncStalloc<1000, 4> = SyncStalloc::new();

fn main() {
    // All of these allocations are being handled by the global `SyncStalloc` instance.
    let s1 = String::from("Hello");
    let s2 = String::from("world");
    let msg = format!("{s1}, {s2}!");

    assert!(!GLOBAL.is_oom());
    println!("Allocator state: {GLOBAL:?}");
}

To avoid the risk of OOM, you can “chain” your allocator to the system allocator, using it as a fallback.

use stalloc::{AllocChain, SyncStalloc};
use std::alloc::System;

#[global_allocator]
static GLOBAL: AllocChain<SyncStalloc<1000, 8>, System> = SyncStalloc::new().chain(&System);

Structs§

Align
A ZST with a given alignment. Align and Alignment are used to ensure that Block, and hence Stalloc, are aligned to a particular value.
AllocChain
A chain of allocators. If the first allocator is exhuasted, the second one is used as a fallback.
AllocError
An error type representing some kind of allocation error due to memory exhaustion. This is a polyfill for core::alloc::AllocError, available through the nightly Allocator API.
Stalloc
A fast first-fit memory allocator.
StallocGuard
A lock around SyncStalloc. Constructing this type is proof that the user holds an exclusive lock on the inner UnsafeStalloc. When this falls out of scope, the SyncStalloc is unlocked.
SyncStalloc
A wrapper around UnsafeStalloc that is safe to create because it prevents data races using a Mutex. In comparison to UnsafeStalloc, the mutex may cause a slight overhead.
UnsafeStalloc
A wrapper around Stalloc that implements both Sync and GlobalAlloc.

Traits§

ChainableAlloc
A trait representing an allocator that another allocator can be chained to.