pub fn set_heap_source(source: fn() -> usize) -> boolmemory only.Expand description
Register a process-wide source of total live-heap bytes.
When set, every MemoryGuard switches its read path
(current_bytes, pressure checks, and
try_reserve admission) from the per-batch
reservation counter to this source – a cheap, accurate, total-process
heap figure that also catches growth the per-batch reservations never see
(e.g. a transform ballooning a Vec).
Why a global hook and not a dependency: a tracking allocator must be
the binary’s single #[global_allocator], which is the application’s
choice, not a library’s – and rustlib is #![forbid(unsafe_code)], so it
cannot implement one anyway. The application installs its allocator and
wires it here in a few lines. This keeps rustlib allocator-agnostic with no
allocator dependency in its graph.
The first call wins and returns true; later calls are a no-op and return
false (the existing source is kept). Call once at startup, before
constructing guards.
The application picks a tracking allocator – prefer an actively-maintained
one such as tikv-jemalloc-ctl (stats.allocated); the cap crate also
works but is effectively unmaintained (last release 2023).
// In the application binary, using jemalloc:
#[global_allocator]
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
fn main() {
hyperi_rustlib::memory::set_heap_source(|| {
tikv_jemalloc_ctl::epoch::advance().ok();
tikv_jemalloc_ctl::stats::allocated::read().unwrap_or(0)
});
// ... build ServiceRuntime / MemoryGuard ...
}