pub(crate) const STATUS_PATH: &str = "/proc/self/status";
pub(crate) fn resident_bytes() -> Option<u64> {
let text = std::fs::read_to_string(STATUS_PATH).ok()?;
match resident_from_status(&text) {
Some(bytes) => Some(bytes),
None => {
tracing::debug!(
path = STATUS_PATH,
"process resident memory usage is unavailable: the status file is not recognized"
);
None
}
}
}
pub(crate) fn resident_from_status(text: &str) -> Option<u64> {
status_field_bytes(text, "VmRSS:")
}
pub(crate) fn status_field_bytes(text: &str, label: &str) -> Option<u64> {
let line = text.lines().find(|line| {
let after_label = line.strip_prefix(label);
after_label.is_some_and(|rest| rest.starts_with(' ') || rest.starts_with('\t'))
})?;
let value = line[label.len()..].trim();
let value = value.strip_suffix(" kB").unwrap_or(value);
value.parse::<u64>().ok().map(|kib| kib * 1024)
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
use super::{resident_bytes, resident_from_status, status_field_bytes};
const STATUS_SAMPLE: &str = "\
Name:\tcat
Umask:\t0022
State:\tS (sleeping)
VmPeak:\t 26214 kB
VmSize:\t 26214 kB
VmLck:\t 0 kB
VmHWM:\t 768 kB
VmRSS:\t 1536 kB
RssAnon:\t 512 kB
VmData:\t 2048 kB
Threads:\t1
";
#[test]
fn sample_status_is_parsed() {
assert_eq!(resident_from_status(STATUS_SAMPLE), Some(1_536 * 1024));
}
#[test]
fn vmrss_without_kib_suffix_is_parsed() {
assert_eq!(resident_from_status("VmRSS:\t2048\n"), Some(2_048 * 1024));
}
#[test]
fn status_field_reads_other_labels() {
assert_eq!(
status_field_bytes(STATUS_SAMPLE, "VmHWM:"),
Some(768 * 1024)
);
assert_eq!(
status_field_bytes(STATUS_SAMPLE, "VmRSS:"),
Some(1_536 * 1024)
);
assert_eq!(status_field_bytes(STATUS_SAMPLE, "VmSwap:"), None);
}
#[test]
fn zero_rss_is_zero_bytes() {
assert_eq!(resident_from_status("VmRSS: 0 kB\n"), Some(0));
}
#[test]
fn missing_or_broken_vmrss_is_none() {
assert_eq!(resident_from_status(""), None);
assert_eq!(resident_from_status("Name:\tcat\n"), None);
assert_eq!(
resident_from_status("RSS: 100 kB\nVmRSSPeak:\t 99 kB\n"),
None
);
assert_eq!(resident_from_status("VmRSS:\tabsent\n"), None);
}
#[test]
fn resident_bytes_does_not_panic() {
let resident = resident_bytes();
println!("resident_bytes on this machine: {resident:?}");
assert!(resident.is_some());
}
}