Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-alloc/tests/support/alloc_counter.rs

Raw
// Test-only allocation bounds (`SMH-SPEC-SPEC0001`, memory accounting).

use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Cost {
    pub allocations: u64,
    pub bytes: u64,
}

thread_local! {
    static ACTIVE: Cell<bool> = const { Cell::new(false) };
    static COST: Cell<Cost> = const { Cell::new(Cost { allocations: 0, bytes: 0 }) };
}

pub struct Counting;

struct Measurement;

impl Drop for Measurement {
    fn drop(&mut self) {
        ACTIVE.set(false);
    }
}

pub fn measure<T>(work: impl FnOnce() -> T) -> (T, Cost) {
    assert!(!ACTIVE.replace(true), "allocation measurement must not nest");
    COST.set(Cost::default());
    let measurement = Measurement;
    let output = work();
    let cost = COST.get();
    drop(measurement);
    (output, cost)
}

fn record(bytes: usize) {
    if ACTIVE.get() {
        let mut cost = COST.get();
        cost.allocations += 1;
        cost.bytes += bytes as u64;
        COST.set(cost);
    }
}

#[expect(
    unsafe_code,
    reason = "GlobalAlloc requires unsafe calls into System for test-only allocation measurement"
)]
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        // SAFETY: forwards allocator-provided valid layout unchanged to System.
        let pointer = unsafe { System.alloc(layout) };
        if !pointer.is_null() {
            record(layout.size());
        }
        pointer
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        // SAFETY: forwards allocator-provided valid layout unchanged to System.
        let pointer = unsafe { System.alloc_zeroed(layout) };
        if !pointer.is_null() {
            record(layout.size());
        }
        pointer
    }

    unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
        // SAFETY: forwards allocation pointer and its original layout unchanged to System.
        unsafe { System.dealloc(pointer, layout) };
    }

    unsafe fn realloc(
        &self,
        pointer: *mut u8,
        layout: Layout,
        new_size: usize,
    ) -> *mut u8 {
        // SAFETY: forwards allocation pointer, original layout, and requested size unchanged to System.
        let pointer = unsafe { System.realloc(pointer, layout, new_size) };
        if !pointer.is_null() {
            record(new_size);
        }
        pointer
    }
}