Files
leleka/crates/engine-core/src/memory.rs
T

54 lines
1.7 KiB
Rust

//! Host physical-memory admission, the pure half of `conversation_memory.{hpp,cpp}`.
use std::io::BufRead;
/// Whether `allocation` fits in `available` while leaving `floor` free.
pub fn memory_admit(available: Option<u64>, allocation: u64, floor: u64) -> bool {
available.is_some_and(|available| available >= floor && allocation <= available - floor)
}
const KEY: &[u8] = b"MemAvailable:";
fn fields(line: &[u8]) -> Vec<&[u8]> {
// The C++ stream extraction splits on the C-locale isspace set.
line.split(|b| matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r'))
.filter(|field| !field.is_empty())
.collect()
}
fn parse_kb(value: &[u8]) -> Option<u64> {
// `std::from_chars` for an unsigned type: digits only, no sign, no
// whitespace, whole token consumed, no overflow.
if value.is_empty() || !value.iter().all(u8::is_ascii_digit) {
return None;
}
std::str::from_utf8(value).ok()?.parse::<u64>().ok()
}
/// `MemAvailable` in bytes from `/proc/meminfo`-formatted text.
pub fn mem_available(mut meminfo: impl BufRead) -> Option<u64> {
let mut result: Option<u64> = None;
let mut line = Vec::new();
loop {
line.clear();
match meminfo.read_until(b'\n', &mut line) {
Ok(0) => break,
Ok(_) => {}
Err(_) => return None,
}
let parts = fields(&line);
if parts.first().copied() != Some(KEY) {
continue;
}
if result.is_some() || parts.len() != 3 || parts[2] != b"kB" {
return None;
}
let kb = parse_kb(parts[1])?;
if kb > u64::MAX / 1024 {
return None;
}
result = Some(kb * 1024);
}
result
}