croft-software 0.2.232

VSCode-style TUI written in Rust
//! Test builds count the heap allocations each thread makes, so a test can
//! hold a piece of croft to an allocation budget (#2062): an idle pass of the
//! main loop, or one frame. Only test builds install it; the shipped binary
//! keeps the system allocator untouched.
//!
//! Counts are per thread: each test runs on its own thread, so a count is
//! the measured code's own and not a sibling test's. Work croft hands to a
//! background thread is not counted, as it does not run on the UI thread.

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

thread_local! {
    /// Allocations and reallocations made on this thread so far.
    static MADE: Cell<u64> = const { Cell::new(0) };
}

/// The system allocator, counting each allocation and reallocation on the
/// thread that asks for it. A thread being torn down, whose counter is gone,
/// is not counted.
struct Counting;

impl Counting {
    fn note() {
        let _ = MADE.try_with(|made| made.set(made.get() + 1));
    }
}

// SAFETY: every call goes straight to `System` with the caller's arguments;
// the counter is a plain thread-local cell, which allocates nothing.
unsafe impl GlobalAlloc for Counting {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        Self::note();
        // SAFETY: the caller's contract for `alloc` is passed on unchanged.
        unsafe { System.alloc(layout) }
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        Self::note();
        // SAFETY: as for `alloc`.
        unsafe { System.alloc_zeroed(layout) }
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        Self::note();
        // SAFETY: the caller's contract for `realloc` is passed on unchanged.
        unsafe { System.realloc(ptr, layout, new_size) }
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        // SAFETY: the caller's contract for `dealloc` is passed on unchanged.
        unsafe { System.dealloc(ptr, layout) }
    }
}

#[global_allocator]
static COUNTING: Counting = Counting;

/// Run `f` and say how many allocations it made on this thread.
pub fn allocations_in<T>(f: impl FnOnce() -> T) -> (T, u64) {
    let before = MADE.with(Cell::get);
    let out = f();
    (out, MADE.with(Cell::get) - before)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_vec_that_grows_twice_counts_its_allocations() {
        let (v, made) = allocations_in(|| {
            let mut v: Vec<u8> = Vec::with_capacity(1);
            v.extend_from_slice(&[1, 2, 3]);
            v
        });
        assert_eq!(v, [1, 2, 3]);
        assert_eq!(made, 2, "one allocation, then one growth");
        let ((), none) = allocations_in(|| {
            std::hint::black_box(1 + 1);
        });
        assert_eq!(none, 0);
    }

    #[test]
    fn another_threads_allocations_are_its_own() {
        let ((), made) = allocations_in(|| {
            std::thread::scope(|s| {
                s.spawn(|| std::hint::black_box(vec![0u8; 64]));
            });
        });
        assert!(
            made < 8,
            "the spawned thread's vector is not counted here, only the spawn's own bookkeeping: {made}"
        );
    }
}