#![cfg(feature = "allocator")]
use kernal_api::allocator::{
dump_file, dump_to_vec, is_enabled, live_sample_count, start, stats, stop, Allocator,
};
#[global_allocator]
static GLOBAL: Allocator = Allocator::new();
#[test]
fn dump_to_vec_captures_a_sampled_allocation() {
if is_enabled() {
stop();
}
let baseline = dump_to_vec().len();
assert!(start(1), "heap profiler should start exactly once");
let retained = vec![0x5a_u8; 1024 * 1024];
std::hint::black_box(&retained);
assert!(
live_sample_count() > 0,
"retained allocation was not sampled"
);
let snapshot = dump_to_vec();
let counters = stats();
assert!(counters.enabled());
assert_eq!(counters.sample_rate(), 1);
assert!(counters.live_samples() > 0);
assert!(counters.live_bytes() >= retained.len());
assert!(counters.dropped_samples() >= counters.stack_table_overflows());
let heap = counters.heap();
assert!(heap.committed() >= retained.len(), "{heap:?}");
assert!(heap.reserved() >= heap.committed(), "{heap:?}");
let directory = tempfile::tempdir().unwrap();
let text_path = directory.path().join("heap.prof");
dump_file(&text_path).unwrap();
let text = std::fs::read_to_string(&text_path).unwrap();
assert!(text.starts_with("heap profile:"), "{text:.80}");
assert!(text.contains("MAPPED_LIBRARIES:"));
stop();
assert!(!stats().enabled());
assert!(
snapshot.len() > baseline,
"pprof snapshot ({} bytes) must carry the sampled allocation beyond \
the dormant scaffolding ({baseline} bytes)",
snapshot.len()
);
}