use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Trim {
collected_bytes: u64,
elapsed: Duration,
}
impl Trim {
pub(crate) fn collected_bytes(&self) -> u64 {
self.collected_bytes
}
pub(crate) fn elapsed(&self) -> Duration {
self.elapsed
}
}
#[cfg(target_env = "gnu")]
#[allow(unsafe_code)]
pub(crate) fn trim() -> Option<Trim> {
let before = super::resident_bytes();
let started = std::time::Instant::now();
unsafe {
libc::malloc_trim(0);
}
let elapsed = started.elapsed();
let collected_bytes = before
.zip(super::resident_bytes())
.map_or(0, |(before, after)| before.saturating_sub(after));
tracing::debug!(
collected_bytes,
"the unused allocator memory is returned to the operating system"
);
Some(Trim {
collected_bytes,
elapsed,
})
}
#[cfg(not(target_env = "gnu"))]
pub(crate) fn trim() -> Option<Trim> {
None
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use super::trim;
#[test]
fn trimming_returns_a_result_on_glibc() {
if cfg!(target_env = "gnu") {
let result = trim().expect("glibc supports trimming");
println!(
"trim collected {} bytes in {:?}",
result.collected_bytes(),
result.elapsed()
);
}
}
}