use std::time::Duration;
pub(crate) fn visible_width(s: &str) -> usize {
let mut n = 0;
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\u{1b}' {
for e in chars.by_ref() {
if e == 'm' {
break;
}
}
} else {
n += 1;
}
}
n
}
pub(crate) fn pad(s: &str, width: usize, right: bool) -> String {
let fill = " ".repeat(width.saturating_sub(visible_width(s)));
match right {
true => format!("{fill}{s}"),
false => format!("{s}{fill}"),
}
}
pub(crate) fn trim_lines(block: &str) -> String {
let mut out = String::with_capacity(block.len());
for line in block.split_inclusive('\n') {
let (text, nl) = match line.strip_suffix('\n') {
Some(t) => (t, "\n"),
None => (line, ""),
};
out.push_str(text.trim_end());
out.push_str(nl);
}
out
}
const EIGHTHS: [char; 8] = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
pub(crate) fn bar(count: u64, max: u64, width: usize) -> String {
if width == 0 {
return String::new();
}
let units = match max {
0 => 0.0,
max => count as f64 / max as f64 * width as f64,
};
let full = (units.floor() as usize).min(width);
let rem = ((units - units.floor()) * 8.0).round() as usize;
let mut out = "█".repeat(full);
if rem > 0 && full < width {
out.push(EIGHTHS[rem.min(7)]);
}
let drawn = visible_width(&out);
out.push_str(&" ".repeat(width.saturating_sub(drawn)));
out
}
pub(crate) fn split_bar(a: u64, b: u64, width: usize) -> (String, String) {
let total = a + b;
if total == 0 || width == 0 {
return (" ".repeat(width), String::new());
}
let na = ((a as f64 / total as f64) * width as f64).round() as usize;
let na = match (a, na) {
(0, _) => 0,
(_, 0) => 1,
(_, n) => n.min(width.saturating_sub(if b > 0 { 1 } else { 0 })),
};
("█".repeat(na), "▒".repeat(width - na))
}
const SPARKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
pub(crate) fn spark(vals: &[f64]) -> String {
if vals.is_empty() {
return String::new();
}
let lo = vals.iter().copied().fold(f64::INFINITY, f64::min);
let hi = vals.iter().copied().fold(f64::NEG_INFINITY, f64::max);
if !lo.is_finite() || !hi.is_finite() || (hi - lo).abs() < f64::EPSILON {
return SPARKS[SPARKS.len() / 2].to_string().repeat(vals.len());
}
vals.iter()
.map(|v| {
let i = ((v - lo) / (hi - lo) * (SPARKS.len() - 1) as f64).round() as usize;
SPARKS[i.min(SPARKS.len() - 1)]
})
.collect()
}
pub(crate) fn boxed(lines: &[String]) -> String {
use colored::Colorize;
let inner = lines.iter().map(|l| visible_width(l)).max().unwrap_or(0) + 4;
let mut out = String::new();
out.push_str(&format!(
" {}\n",
format!("╭{}╮", "─".repeat(inner)).cyan()
));
for line in lines {
out.push_str(&format!(
" {} {} {}\n",
"│".cyan(),
pad(line, inner - 4, false),
"│".cyan()
));
}
out.push_str(&format!(
" {}\n",
format!("╰{}╯", "─".repeat(inner)).cyan()
));
out
}
pub(crate) fn term_width() -> usize {
if let Some(w) = std::env::var("COLUMNS")
.ok()
.and_then(|c| c.trim().parse::<usize>().ok())
.filter(|w| *w >= 40)
{
return w.min(220);
}
ioctl_width().filter(|w| *w >= 40).unwrap_or(96).min(220)
}
#[cfg(unix)]
fn ioctl_width() -> Option<usize> {
use std::io::IsTerminal;
if !std::io::stdout().is_terminal() {
return None;
}
unsafe {
let mut ws: libc::winsize = std::mem::zeroed();
match libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) {
0 if ws.ws_col > 0 => Some(ws.ws_col as usize),
_ => None,
}
}
}
#[cfg(not(unix))]
fn ioctl_width() -> Option<usize> {
None
}
pub(crate) fn grouped(n: u64) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push('\u{2009}');
}
out.push(c);
}
out
}
pub(crate) fn fmt_us(us: u64) -> String {
match us {
0 => "—".to_string(),
us if us < 1_000 => format!("{us}µs"),
us if us < 1_000_000 => format!("{:.1}ms", us as f64 / 1_000.0),
us => format!("{:.2}s", us as f64 / 1_000_000.0),
}
}
pub(crate) fn fmt_ms(ms: f64) -> String {
fmt_us((ms.max(0.0) * 1000.0).round() as u64)
}
pub(crate) fn fmt_tick(us: u64) -> String {
let s = fmt_us(us);
match s.strip_suffix("ms").and_then(|n| n.strip_suffix(".0")) {
Some(n) => format!("{n}ms"),
None => match s.strip_suffix('s').and_then(|n| n.strip_suffix(".00")) {
Some(n) => format!("{n}s"),
None => s,
},
}
}
pub(crate) fn precise_duration(d: std::time::Duration) -> String {
match d.as_secs() {
0..=59 => format!("{:.1}s", d.as_secs_f64()),
_ => short_duration(d),
}
}
pub(crate) fn fmt_zkcr(v: f64) -> String {
format!("{v:.4}")
}
pub(crate) fn eta(done: u64, total: u64, elapsed: Duration) -> Option<Duration> {
if done == 0 || done >= total {
return None;
}
let per = elapsed.as_secs_f64() / done as f64;
Some(Duration::from_secs_f64(per * (total - done) as f64))
}
pub(crate) fn short_duration(d: Duration) -> String {
let s = d.as_secs();
match s {
0..=59 => format!("{s}s"),
60..=3599 => format!("{}m{:02}s", s / 60, s % 60),
_ => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
}
}
pub(crate) fn wrap_visible(s: &str, width: usize, indent: usize) -> Vec<String> {
let hang = " ".repeat(indent);
let mut lines: Vec<String> = Vec::new();
let mut line = String::new();
let mut used = 0usize;
for word in s.split(' ').filter(|w| !w.is_empty()) {
let w = visible_width(word);
if !line.is_empty() && used + 1 + w > width {
lines.push(std::mem::take(&mut line));
line.push_str(&hang);
used = indent;
}
if !line.is_empty() && !line.ends_with(' ') {
line.push(' ');
used += 1;
}
line.push_str(word);
used += w;
}
if !line.trim().is_empty() {
lines.push(line);
}
lines
}
pub(crate) fn fit(width: usize, candidates: &[String]) -> String {
candidates
.iter()
.find(|c| c.lines().all(|l| visible_width(l) <= width))
.cloned()
.unwrap_or_else(|| candidates.last().cloned().unwrap_or_default())
}
pub(crate) trait Muted {
fn muted(&self) -> String;
fn muted_bold(&self) -> String;
}
impl<T: std::fmt::Display + ?Sized> Muted for T {
fn muted(&self) -> String {
let s = self.to_string();
match colored::control::SHOULD_COLORIZE.should_colorize() {
true => format!("\x1b[38;5;245m{s}\x1b[0m"),
false => s,
}
}
fn muted_bold(&self) -> String {
let s = self.to_string();
match colored::control::SHOULD_COLORIZE.should_colorize() {
true => format!("\x1b[1;38;5;245m{s}\x1b[0m"),
false => s,
}
}
}
pub(crate) fn short_worker(name: &str) -> String {
let trimmed = name.strip_prefix("worker-zc-worker-").unwrap_or(name);
match trimmed.chars().count() > 22 {
true => format!("{}…", trimmed.chars().take(21).collect::<String>()),
false => trimmed.to_string(),
}
}
pub(crate) fn worker_leaf(worker: &str) -> String {
let node = super::metrics::node_of(worker);
match worker.rsplit_once(&format!("{node}-")) {
Some((_, leaf)) if !leaf.is_empty() => leaf.to_string(),
_ => worker.to_string(),
}
}
#[cfg(test)]
pub(crate) fn colour_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
LOCK.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
use colored::Colorize;
fn plain(s: &str) -> String {
let mut out = String::new();
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\u{1b}' {
for e in chars.by_ref() {
if e == 'm' {
break;
}
}
} else {
out.push(c);
}
}
out
}
#[test]
fn width_is_what_the_eye_sees_not_what_is_stored() {
let _colour = colour_lock();
colored::control::set_override(true);
let coloured = "abc".red().to_string();
assert!(coloured.len() > 3);
assert_eq!(visible_width(&coloured), 3);
colored::control::unset_override();
}
#[test]
fn padding_lines_up_coloured_and_plain_alike() {
let _colour = colour_lock();
colored::control::set_override(true);
let a = pad(&"ab".green().to_string(), 6, false);
let b = pad("ab", 6, false);
assert_eq!(visible_width(&a), visible_width(&b));
colored::control::unset_override();
}
#[test]
fn a_bar_is_proportional_and_never_overflows_its_width() {
assert_eq!(visible_width(&bar(0, 10, 8)), 8);
assert_eq!(visible_width(&bar(10, 10, 8)), 8);
assert_eq!(visible_width(&bar(99, 10, 8)), 8);
assert_eq!(bar(10, 10, 8), "████████");
assert_eq!(bar(5, 10, 8), "████ ");
}
#[test]
fn a_small_share_still_draws_something() {
let b = bar(1, 400, 28);
assert!(b.trim().is_empty() || b.starts_with('▏'), "{b:?}");
let b = bar(12, 400, 28);
assert!(!b.trim().is_empty(), "a 3% bucket must be visible");
}
#[test]
fn a_split_bar_reads_without_colour() {
let (a, b) = split_bar(3, 1, 8);
assert_eq!(a, "██████");
assert_eq!(b, "▒▒");
assert_eq!(visible_width(&format!("{a}{b}")), 8);
}
#[test]
fn a_single_billed_request_is_not_rounded_away() {
let (_, billed) = split_bar(9_999, 1, 20);
assert!(!billed.is_empty(), "a billed request must leave a mark");
}
#[test]
fn a_split_bar_with_nothing_in_it_is_blank() {
let (a, b) = split_bar(0, 0, 6);
assert_eq!(a, " ");
assert_eq!(b, "");
}
#[test]
fn a_sparkline_has_one_cell_per_sample() {
let s = spark(&[1.0, 2.0, 3.0, 4.0]);
assert_eq!(s.chars().count(), 4);
assert_eq!(s.chars().next(), Some('▁'));
assert_eq!(s.chars().last(), Some('█'));
}
#[test]
fn a_flat_rate_draws_a_flat_line_not_a_divide_by_zero() {
let s = spark(&[7.0, 7.0, 7.0]);
assert_eq!(s.chars().count(), 3);
assert!(s.chars().all(|c| c == s.chars().next().unwrap()));
}
#[test]
fn secondary_text_is_a_colour_not_the_faint_attribute() {
let _colour = colour_lock();
colored::control::set_override(true);
let m = "p50".muted();
assert!(!m.contains("\x1b[2m"), "SGR 2 disappears on some terminals");
assert!(m.contains("38;5;245"), "a real 256-colour grey: {m:?}");
assert_eq!(visible_width(&m), 3);
colored::control::unset_override();
}
#[test]
fn secondary_text_carries_no_escapes_when_colour_is_off() {
let _colour = colour_lock();
colored::control::set_override(false);
assert_eq!("p50".muted(), "p50");
assert_eq!("o".muted_bold(), "o");
colored::control::unset_override();
}
#[test]
fn an_axis_label_is_a_round_number() {
assert_eq!(fmt_tick(250_000), "250ms");
assert_eq!(fmt_tick(1_000_000), "1s");
assert_eq!(fmt_tick(1_240_000), "1.24s");
assert_eq!(fmt_tick(820), "820µs");
}
#[test]
fn a_short_run_is_timed_to_a_tenth() {
assert_eq!(precise_duration(Duration::from_millis(20_900)), "20.9s");
assert_eq!(precise_duration(Duration::from_secs(600)), "10m00s");
}
#[test]
fn a_duration_reads_in_the_unit_that_suits_it() {
assert_eq!(short_duration(Duration::from_secs(9)), "9s");
assert_eq!(short_duration(Duration::from_secs(64)), "1m04s");
assert_eq!(short_duration(Duration::from_secs(7200)), "2h00m");
}
#[test]
fn how_much_longer_is_extrapolated_from_what_is_done() {
let left = eta(10, 110, Duration::from_secs(10)).unwrap();
assert_eq!(left.as_secs(), 100);
assert!(eta(0, 100, Duration::from_secs(1)).is_none());
assert!(eta(100, 100, Duration::from_secs(1)).is_none());
}
#[test]
fn a_long_counter_reads_at_a_glance() {
assert_eq!(grouped(786), "786");
assert_eq!(plain(&grouped(100_000)), "100\u{2009}000");
}
#[test]
fn a_worker_name_is_shortened_to_fit_the_line() {
assert_eq!(short_worker("worker-zc-worker-i9-1"), "i9-1");
assert_eq!(short_worker("dd715b7f-w0"), "dd715b7f-w0");
assert!(short_worker(&"x".repeat(40)).chars().count() <= 22);
}
#[test]
fn wrapping_counts_columns_not_bytes() {
let _colour = colour_lock();
colored::control::set_override(true);
let text = format!("{} two three four five six", "one".red());
let lines = wrap_visible(&text, 12, 4);
assert!(lines.len() > 1, "{lines:?}");
for l in &lines {
assert!(visible_width(l) <= 12, "{l:?} is {}", visible_width(l));
}
colored::control::unset_override();
}
#[test]
fn a_header_drops_what_does_not_fit_rather_than_wrapping() {
let wide = "a".repeat(80);
let narrow = "a".repeat(20);
assert_eq!(fit(100, &[wide.clone(), narrow.clone()]), wide);
assert_eq!(fit(40, &[wide.clone(), narrow.clone()]), narrow);
assert_eq!(fit(5, &[wide, narrow.clone()]), narrow);
}
#[test]
fn the_terminal_width_can_be_pinned_for_a_recording() {
std::env::set_var("COLUMNS", "132");
assert_eq!(term_width(), 132);
std::env::set_var("COLUMNS", "12");
assert!(term_width() >= 40, "an absurd width falls back");
std::env::remove_var("COLUMNS");
}
}