use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use std::io;
use ticklog::{info, warm_up, Level, WriterSink};
thread_local! {
static ALLOCATIONS: Cell<u64> = const { Cell::new(0) };
static COUNTING: Cell<bool> = const { Cell::new(false) };
}
fn note_alloc() {
COUNTING.with(|on| {
if on.get() {
ALLOCATIONS.with(|n| n.set(n.get() + 1));
}
});
}
struct CountingAlloc;
unsafe impl GlobalAlloc for CountingAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
note_alloc();
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
note_alloc();
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
note_alloc();
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: CountingAlloc = CountingAlloc;
#[test]
fn warm_up_is_idempotent_and_first_log_is_allocation_free() {
let guard = ticklog::builder()
.sink(WriterSink::new(io::sink()))
.max_level(Level::Trace)
.build()
.expect("first build in a fresh process must succeed");
warm_up().expect("warm_up after build must succeed");
warm_up().expect("warm_up must be idempotent");
COUNTING.with(|on| on.set(false));
ALLOCATIONS.with(|n| n.set(0));
COUNTING.with(|on| on.set(true));
info!("warm {}", 1u64);
COUNTING.with(|on| on.set(false));
let allocations = ALLOCATIONS.with(|n| n.get());
assert_eq!(
allocations, 0,
"first log after warm_up allocated {allocations} time(s) on the caller"
);
drop(guard);
}