#[cfg(target_os = "linux")]
pub fn available_bytes() -> Option<u64> {
cgroup_v2_available().or_else(host_available)
}
#[cfg(not(target_os = "linux"))]
pub fn available_bytes() -> Option<u64> {
None
}
#[cfg(target_os = "linux")]
fn cgroup_v2_available() -> Option<u64> {
let limit = read_u64("/sys/fs/cgroup/memory.max")?;
let current = read_u64("/sys/fs/cgroup/memory.current")?;
Some(limit.saturating_sub(current))
}
#[cfg(target_os = "linux")]
fn host_available() -> Option<u64> {
let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
meminfo
.lines()
.find_map(|line| line.strip_prefix("MemAvailable:"))
.and_then(|rest| rest.split_whitespace().next())
.and_then(|kb| kb.parse::<u64>().ok())
.map(|kb| kb * 1024)
}
#[cfg(target_os = "linux")]
fn read_u64(path: &str) -> Option<u64> {
std::fs::read_to_string(path).ok()?.trim().parse().ok()
}
#[cfg(target_os = "linux")]
pub fn resident_set_bytes() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
status
.lines()
.find_map(|line| line.strip_prefix("VmRSS:"))
.and_then(|rest| rest.split_whitespace().next())
.and_then(|kb| kb.parse::<u64>().ok())
.map(|kb| kb * 1024)
}
#[cfg(not(target_os = "linux"))]
pub fn resident_set_bytes() -> Option<u64> {
None
}
pub fn has_headroom(reserve_bytes: u64) -> bool {
available_bytes().is_none_or(|available| available >= reserve_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_zero_reserve_always_has_headroom() {
assert!(has_headroom(0));
}
#[test]
fn an_unmeasurable_platform_does_not_refuse_work() {
let measured = available_bytes();
assert_eq!(has_headroom(u64::MAX), measured.is_none());
}
#[test]
fn process_rss_gauge_is_nonzero_on_linux() {
let rss = resident_set_bytes();
if cfg!(target_os = "linux") {
assert!(rss.is_some_and(|bytes| bytes > 0));
} else {
assert_eq!(rss, None);
}
}
#[test]
fn available_bytes_is_plausible_when_reported() {
if let Some(available) = available_bytes() {
assert!(
available < 128 * 1024 * 1024 * 1024 * 1024,
"available_bytes reported {available}, which is not a byte count"
);
}
}
}