oomtop-cli 0.2.3

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
//! Plain, aligned tables for answer-first command output (`stale`, `ports`): terminal width, bold/dim only on a
//! tty without `NO_COLOR`, and width-safe padding.

/// Terminal columns for laying out the table: the tty's width, else `$COLUMNS`, else 100.
pub(crate) fn term_width() -> usize {
    #[cfg(unix)]
    {
        use std::io::IsTerminal;
        if std::io::stdout().is_terminal() {
            let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
            // SAFETY: TIOCGWINSZ fills a winsize for a terminal fd; the struct is zero-initialised.
            if unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) } == 0 && ws.ws_col > 0 {
                return ws.ws_col as usize;
            }
        }
    }
    std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.parse().ok())
        .filter(|&c: &usize| c >= 40)
        .unwrap_or(100)
}

/// Bold / dim only on a terminal and never with `NO_COLOR`; meaning never depends on it.
pub(crate) struct Ink(pub(crate) bool);
impl Ink {
    pub(crate) fn detect() -> Self {
        use std::io::IsTerminal;
        Ink(std::io::stdout().is_terminal()
            && std::env::var_os("NO_COLOR").is_none()
            && std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true))
    }
    pub(crate) fn bold(&self, t: &str) -> String {
        if self.0 {
            format!("\x1b[1m{t}\x1b[0m")
        } else {
            t.to_string()
        }
    }
    pub(crate) fn dim(&self, t: &str) -> String {
        if self.0 {
            format!("\x1b[2m{t}\x1b[0m")
        } else {
            t.to_string()
        }
    }
}

pub(crate) fn clip(t: &str, w: usize) -> String {
    if t.chars().count() <= w {
        return t.to_string();
    }
    let mut out: String = t.chars().take(w.saturating_sub(1)).collect();
    out.push('…');
    out
}

pub(crate) fn pad(t: &str, w: usize) -> String {
    let t = clip(t, w);
    let n = t.chars().count();
    format!("{t}{}", " ".repeat(w.saturating_sub(n)))
}

pub(crate) fn rpad(t: &str, w: usize) -> String {
    let n = t.chars().count();
    format!("{}{t}", " ".repeat(w.saturating_sub(n)))
}

#[cfg(test)]
mod tests {
    #[test]
    fn columns_clip_and_pad_to_width() {
        assert_eq!(super::pad("abc", 5), "abc  ");
        assert_eq!(super::pad("abcdefgh", 5), "abcd…");
        assert_eq!(super::rpad("3.1G", 6), "  3.1G");
        assert_eq!(super::clip("short", 10), "short");
    }
}