[][src]Crate interloc

interloc

This crate defines an interface for creating allocator middleware, i.e. code that runs when your allocator is run.

Examples

use interloc::{AllocMonitor, AllocAction, InterAlloc, StatsMonitor, ThreadMonitor};
use std::alloc::System;
use core::alloc::Layout;

struct MyMonitor {
    pub global: StatsMonitor,
    pub local: ThreadMonitor
}

impl MyMonitor {

    // This needs to be const to be usable in static variable declarations.
    pub const fn new() -> Self {
        Self {
            global: StatsMonitor::new(),
            local: ThreadMonitor::new(),
        }
    }
}

impl AllocMonitor for MyMonitor {
    fn monitor(&self, layout: Layout, action: AllocAction) {
        self.global.monitor(layout, action);
        self.local.monitor(layout, action);
    }
}

static MONITOR: MyMonitor = MyMonitor::new();

// This needs to be done at the project root, i.e. `lib.rs` or `main.rs`
#[global_allocator]
static GLOBAL: InterAlloc<System, MyMonitor> = InterAlloc {
    inner: System,
    monitor: &MONITOR,
};

fn use_monitor_in_thread() {
    let alloc_info = MONITOR.local.info();
    let _allocation_test = Vec::<u8>::with_capacity(100);
    println!("{:#?}", MONITOR.local.info().relative_to(&alloc_info));
}

Structs

AllocInfo

Information about allocations by the allocator.

InterAlloc

An allocator that watches the calls to its API, sends them to a struct, and then makes the calls.

Layout

Layout of a block of memory.

StatsMonitor

Monitor of global memory usage statistics. Uses a read-write lock to prevent data corruption.

ThreadMonitor

Thread-local statistics on memory usage.

Enums

AllocAction

An action that an allocator can take, either right before, or right after it happens.

AllocRel

Before or after an allocation call is executed.

Traits

AllocMonitor

When attached to an InterAlloc instance, this struct's monitor method is called before and after calls to the inner allocator. The ordering of these method calls is enforced by std::sync::atomic::fence with std::sync::atomic::Ordering::SeqCst.