legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! What memory the machine has left, and what this process holds, read from Linux's `/proc` and
//! cgroup files. Elsewhere, and where the files can't be read, each says it doesn't know.

use std::fs;
use std::path::PathBuf;

/// The bytes this process could still allocate without the kernel reclaiming more than its page
/// cache: the lower of the machine's `MemAvailable` and, in a cgroup with a memory limit, the limit
/// less what the group uses besides inactive file pages. `None` where neither can be read.
///
/// ```
/// if let Some(bytes) = legit_hamming::service::available_memory() {
///     assert!(bytes > 0);
/// }
/// ```
#[must_use]
pub fn available_memory() -> Option<u64> {
    let machine = meminfo("MemAvailable:");
    match (machine, cgroup_available()) {
        (Some(machine), Some(group)) => Some(machine.min(group)),
        (machine, group) => machine.or(group),
    }
}

/// The bytes of this process's resident set, and the most it has held, `VmRSS` and `VmHWM` of
/// `/proc/self/status`. `None` where they can't be read.
///
/// ```
/// if let Some((now, peak)) = legit_hamming::service::process_rss() {
///     assert!(peak >= now);
/// }
/// ```
#[must_use]
pub fn process_rss() -> Option<(u64, u64)> {
    let status = fs::read_to_string("/proc/self/status").ok()?;
    Some((kib_field(&status, "VmRSS:")?, kib_field(&status, "VmHWM:")?))
}

fn meminfo(field: &str) -> Option<u64> {
    kib_field(&fs::read_to_string("/proc/meminfo").ok()?, field)
}

/// A `Name:   1234 kB` line's value, in bytes.
fn kib_field(text: &str, field: &str) -> Option<u64> {
    let line = text.lines().find(|line| line.starts_with(field))?;
    let kib: u64 = line[field.len()..].trim().trim_end_matches("kB").trim().parse().ok()?;
    kib.checked_mul(1024)
}

/// The memory left under this process's cgroup v2 limit, if it has one.
fn cgroup_available() -> Option<u64> {
    let membership = fs::read_to_string("/proc/self/cgroup").ok()?;
    let path = membership.lines().find_map(|line| line.strip_prefix("0::"))?;
    let dir = PathBuf::from("/sys/fs/cgroup").join(path.trim().trim_start_matches('/'));
    let limit: u64 = fs::read_to_string(dir.join("memory.max")).ok()?.trim().parse().ok()?;
    let current: u64 = fs::read_to_string(dir.join("memory.current"))
        .ok()?
        .trim()
        .parse()
        .ok()?;
    let inactive_file = fs::read_to_string(dir.join("memory.stat"))
        .ok()
        .and_then(|stat| {
            stat.lines()
                .find_map(|line| line.strip_prefix("inactive_file "))
                .and_then(|value| value.trim().parse::<u64>().ok())
        })
        .unwrap_or(0);
    Some(limit.saturating_sub(current.saturating_sub(inactive_file)))
}