#limit #memory #allocator #alloc #allocated #byte #const-limit

limit-alloc

A custom allocator that allows to limit the available memory

1 unstable release

0.1.0 Jul 9, 2022

#527 in Memory management

GPL-3.0 license

15KB
111 lines

limit-alloc

A custom allocator that allows to limit the available memory.

Usage

use limit_alloc::Limit;
use std::alloc::System;

// Limit available RAM to 4MB
#[global_allocator]
static A: Limit<System> = Limit::new(4_000_000, System);

fn main() {
    let _huge_vec: Vec<u8> = Vec::with_capacity(4_000_001);
}

You can run that example locally and see how the process crashes:

$ cargo run --example huge_vec
memory allocation of 4000001 bytes failed
Aborted

lib.rs:

Allocator that allows to limit the available memory.

This crate implements a few similar types, you can choose the best depending on your use case:

  • Use ConstLimit if you know the limit at compile time, because that makes the allocator zero-sized (as long as the inner allocator is also zero-sized).
  • Use Limit if you are not sure, or if you need more than one limit in the same application. This is needed because ConstLimit uses a static counter to store the allocated memory, so it is impossible to track the memory allocated by different instances of the allocator, we can only track the total allocated memory. The size of Limit is 1 * usize.
  • Use ArcLimit if you need a Limit that implements Clone. Ideally you would have been able to use Arc<Limit<A>> instead, but Arc<T> cannot implement GlobalAlloc.

Note on alignment: an allocation of 1 byte with alignment greater than 1, for example 2 bytes, will allocate 2 bytes because of padding. But this crate only counts 1 byte. So the limit may not be completely accurate.

No runtime deps