use ratatui::style::Color;
pub mod colors {
use super::Color;
pub const BORDER: Color = Color::Rgb(58, 58, 92);
pub const TEXT: Color = Color::Rgb(224, 224, 224);
pub const EMPHASIS: Color = Color::Rgb(255, 255, 255);
pub const DIM: Color = Color::Rgb(96, 96, 96);
pub const PHASE_ACTIVE: Color = Color::Rgb(122, 193, 66);
pub const PHASE_PENDING: Color = Color::Rgb(128, 128, 128);
pub const PHASE_DONE: Color = Color::Rgb(76, 175, 80);
pub const PHASE_FAILED: Color = Color::Rgb(244, 67, 54);
pub const PHASE_RUNNING_TINT: Color = Color::Rgb(247, 201, 72);
pub const PHASE_DONE_WARN: Color = Color::Rgb(255, 140, 0);
pub const PHASE_DONE_BAD: Color = Color::Rgb(214, 70, 40);
pub const PROGRESS_HIGH: Color = Color::Rgb(122, 193, 66);
pub const LAT_P50: Color = Color::Rgb(77, 201, 246);
pub const LAT_P90: Color = Color::Rgb(247, 201, 72);
pub const LAT_P99: Color = Color::Rgb(247, 127, 0);
pub const LAT_MAX: Color = Color::Rgb(214, 40, 40);
pub const SPARK: Color = Color::Rgb(77, 201, 246);
pub const LOG_DEBUG: Color = Color::Rgb(96, 96, 96);
pub const LOG_INFO: Color = Color::Rgb(77, 201, 246);
pub const LOG_WARN: Color = Color::Rgb(247, 201, 72);
pub const LOG_ERROR: Color = Color::Rgb(244, 67, 54);
}
pub fn coords_root_first(leaf_first: &str) -> String {
if leaf_first.is_empty() {
return String::new();
}
let inner = leaf_first
.strip_prefix('(')
.and_then(|s| s.strip_suffix(')'))
.unwrap_or(leaf_first);
let parts: Vec<&str> = inner.split("), (").collect();
if parts.len() <= 1 {
return leaf_first.to_string();
}
let rev: Vec<&str> = parts.into_iter().rev().collect();
format!("({})", rev.join("), ("))
}
pub fn sparkline_str(values: &[f64], width: usize) -> String {
let blocks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
if values.is_empty() {
return " ".repeat(width);
}
let start = if values.len() > width {
values.len() - width
} else {
0
};
let visible = &values[start..];
let min = visible.iter().cloned().fold(f64::INFINITY, f64::min);
let max = visible.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let range = max - min;
let scale = min.abs().max(max.abs());
let flat = range <= 0.0 || range < scale * 1e-9;
let mut s = String::with_capacity(width * 3);
for &v in visible {
if flat {
s.push(blocks[4]);
} else {
let normalized = (v - min) / range;
let idx = (normalized * 7.0).round() as usize;
s.push(blocks[idx.min(7)]);
}
}
while s.chars().count() < width {
s.insert(0, ' ');
}
s
}
pub fn format_nanos(nanos: u64) -> String {
if nanos == 0 {
return "—".to_string();
}
if nanos < 1_000 {
format!("{nanos}ns")
} else if nanos < 1_000_000 {
format!("{:.1}µs", nanos as f64 / 1_000.0)
} else if nanos < 1_000_000_000 {
format!("{:.2}ms", nanos as f64 / 1_000_000.0)
} else {
format!("{:.2}s", nanos as f64 / 1_000_000_000.0)
}
}
pub fn format_elapsed(secs: f64) -> String {
let total = secs as u64;
let h = total / 3600;
let m = (total % 3600) / 60;
let s = total % 60;
if h > 0 {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m}:{s:02}")
}
}
pub fn format_dur_compact(secs: f64) -> String {
if secs < 60.0 {
format!("{secs:.1}s")
} else if secs < 3600.0 {
let total = secs as u64;
format!("{}m{:02}s", total / 60, total % 60)
} else {
let total = secs as u64;
format!("{}h{:02}m", total / 3600, (total % 3600) / 60)
}
}
#[allow(dead_code)]
pub fn margin_body_width(total_phases: usize) -> usize {
TIMING_MARK.chars().count()
+ 1
+ 8
+ 1
+ (total_phases.to_string().len().max(1) * 2 + 3)
+ 1
+ 8
}
pub const TIMING_MARK: &str = "◷";
pub fn margin_body(
total_phases: usize,
count: &str,
leaf: Option<f64>,
sess: Option<f64>,
) -> String {
let tw = total_phases.to_string().len().max(1);
let count_w = tw * 2 + 3;
let leaf_s = leaf
.map(format_dur_compact)
.unwrap_or_else(|| "—".to_string());
let sess_s = sess
.map(format_dur_compact)
.unwrap_or_else(|| "—".to_string());
format!("{TIMING_MARK} {sess_s:>8} {count:<count_w$} {leaf_s:>8}")
}
pub fn format_rate(rate: f64) -> String {
if rate >= 1_000_000.0 {
format!("{:.1}M", rate / 1_000_000.0)
} else if rate >= 1_000.0 {
format!("{:.1}K", rate / 1_000.0)
} else {
format!("{:.2}", rate)
}
}
pub fn format_count(n: u64) -> String {
if n >= 1_000_000 {
format!("{:.1}M", n as f64 / 1_000_000.0)
} else if n >= 1_000 {
format!("{:.1}K", n as f64 / 1_000.0)
} else {
format!("{n}")
}
}
pub fn bar_str(fraction: f64, width: usize) -> String {
let fill = (fraction.clamp(0.0, 1.0) * width as f64).round() as usize;
let mut s = String::with_capacity(width);
for _ in 0..fill {
s.push('━');
}
for _ in fill..width {
s.push('╌');
}
s
}
pub fn bar_str_braille(fraction: f64, width: usize) -> (String, String) {
if width == 0 {
return (String::new(), String::new());
}
let total_pips = width * 8;
let lit_pips = (fraction.clamp(0.0, 1.0) * total_pips as f64).round() as usize;
let full_cells = lit_pips / 8;
let partial = lit_pips % 8;
const PIP_ORDER: [u32; 8] = [
0x40, 0x04, 0x02, 0x01, 0x80, 0x20, 0x10, 0x08, ];
let mut filled = String::with_capacity(width * 3);
for _ in 0..full_cells {
filled.push('\u{2588}');
}
if partial > 0 && full_cells < width {
let mut bits: u32 = 0;
for &pip in &PIP_ORDER[..partial] {
bits |= pip;
}
let codepoint = 0x2800u32 + bits;
if let Some(c) = char::from_u32(codepoint) {
filled.push(c);
} else {
filled.push('\u{2800}');
}
}
let drawn = full_cells
+ if partial > 0 && full_cells < width {
1
} else {
0
};
let mut unfilled = String::with_capacity((width - drawn) * 3);
for _ in drawn..width {
unfilled.push('\u{28C0}');
}
(filled, unfilled)
}
pub fn nearest_pow2_half(n: usize) -> usize {
if n < 2 {
return 1;
}
let half = (n as f64) / 2.0;
let lo_exp = (half.log2().floor().max(0.0) as u32).min(31);
let (a, b) = (1usize << lo_exp, 1usize << (lo_exp + 1));
let pick = if (half - a as f64).abs() <= (b as f64 - half).abs() {
a
} else {
b
};
pick.clamp(1, n.saturating_sub(1).max(1))
}
pub struct DecimatingTrend {
hist: Vec<f64>,
raw: Vec<f64>,
hist_cap: usize,
raw_cap: usize,
stride: u32,
pending_sum: f64,
pending_n: u32,
pub min: f64,
pub max: f64,
}
impl DecimatingTrend {
pub fn new(cap: usize) -> Self {
let cap = cap.max(4);
let hist_cap = nearest_pow2_half(cap);
Self {
hist: Vec::new(),
raw: Vec::new(),
hist_cap,
raw_cap: cap - hist_cap,
stride: 1,
pending_sum: 0.0,
pending_n: 0,
min: f64::INFINITY,
max: f64::NEG_INFINITY,
}
}
pub fn resize(&mut self, cap: usize) {
let cap = cap.max(4);
let hist_cap = nearest_pow2_half(cap);
if hist_cap == self.hist_cap && cap - hist_cap == self.raw_cap {
return;
}
self.hist_cap = hist_cap;
self.raw_cap = cap - hist_cap;
while self.raw.len() > self.raw_cap {
self.evict_oldest_raw();
}
while self.hist.len() > self.hist_cap {
self.halve_hist();
}
}
fn halve_hist(&mut self) {
self.stride = self.stride.saturating_mul(2);
let mut merged = Vec::with_capacity(self.hist.len().div_ceil(2));
let mut it = self.hist.chunks_exact(2);
for pair in &mut it {
merged.push((pair[0] + pair[1]) / 2.0);
}
if let [last] = it.remainder() {
merged.push(*last);
}
self.hist = merged;
}
fn evict_oldest_raw(&mut self) {
if self.raw.is_empty() {
return;
}
let v = self.raw.remove(0);
self.pending_sum += v;
self.pending_n += 1;
if self.pending_n >= self.stride.max(1) {
let n = self.pending_n as f64;
self.hist.push(self.pending_sum / n);
self.pending_sum = 0.0;
self.pending_n = 0;
if self.hist.len() > self.hist_cap {
self.halve_hist();
}
}
}
pub fn push(&mut self, v: f64) {
self.min = self.min.min(v);
self.max = self.max.max(v);
self.raw.push(v);
while self.raw.len() > self.raw_cap {
self.evict_oldest_raw();
}
}
#[allow(dead_code)]
pub fn hist_len(&self) -> usize {
self.hist.len()
}
#[allow(dead_code)]
pub fn hist_cap(&self) -> usize {
self.hist_cap
}
#[allow(dead_code)]
pub fn raw_cap(&self) -> usize {
self.raw_cap
}
pub fn split_view(&self) -> (Vec<f64>, Vec<f64>) {
let hist = if self.hist.is_empty() {
Vec::new()
} else if self.hist.len() == self.hist_cap {
self.hist.clone()
} else {
(0..self.hist_cap)
.map(|i| {
let src = i * self.hist.len() / self.hist_cap;
self.hist[src.min(self.hist.len() - 1)]
})
.collect()
};
let start = self.raw.len().saturating_sub(self.raw_cap);
(hist, self.raw[start..].to_vec())
}
#[allow(dead_code)]
pub fn series(&self) -> Vec<f64> {
let mut s = self.hist.clone();
s.extend_from_slice(&self.raw);
s
}
}
#[cfg(test)]
mod trend_split_tests {
use super::*;
#[test]
fn nearest_pow2_half_picks_the_closer_power() {
assert_eq!(nearest_pow2_half(20), 8); assert_eq!(nearest_pow2_half(24), 8); assert_eq!(nearest_pow2_half(16), 8); assert_eq!(nearest_pow2_half(32), 16); assert_eq!(nearest_pow2_half(5), 2); for n in 2..64 {
assert!(nearest_pow2_half(n) < n, "n={n}");
}
}
#[test]
fn split_stays_fixed_as_samples_accumulate() {
let cap = 20;
let hist_cap = nearest_pow2_half(cap); let raw_cap = cap - hist_cap;
let mut t = DecimatingTrend::new(cap);
for i in 0..5_000 {
t.push(i as f64);
let (hist, raw) = t.split_view();
assert!(
raw.len() <= raw_cap,
"tail overdrew at push {i}: {}",
raw.len()
);
if i >= 64 {
assert_eq!(
hist.len(),
hist_cap,
"history view must stay fixed at {hist_cap}, got {} at push {i}",
hist.len()
);
assert_eq!(
raw.len(),
raw_cap,
"tail view must stay fixed at {raw_cap}, got {} at push {i}",
raw.len()
);
}
}
}
#[test]
fn tail_is_one_sample_per_cell_and_newest() {
let cap = 20;
let hist_cap = nearest_pow2_half(cap);
let raw_cap = cap - hist_cap;
let mut t = DecimatingTrend::new(cap);
for i in 0..1_000 {
t.push(i as f64);
}
let series = t.series();
let tail = &series[series.len() - raw_cap..];
let expected: Vec<f64> = ((1_000 - raw_cap)..1_000).map(|i| i as f64).collect();
assert_eq!(tail, &expected[..], "tail must be the newest raw samples");
}
#[test]
fn resize_rebalances_without_losing_the_series() {
let mut t = DecimatingTrend::new(20);
for i in 0..500 {
t.push(i as f64);
}
t.resize(40);
for i in 0..500 {
t.push(i as f64);
}
let (h, r) = t.split_view();
assert_eq!(h.len(), nearest_pow2_half(40));
assert_eq!(h.len() + r.len(), 40);
t.resize(12);
for i in 0..500 {
t.push(i as f64);
}
let (h, r) = t.split_view();
assert_eq!(h.len(), nearest_pow2_half(12));
assert_eq!(h.len() + r.len(), 12, "shrinking must not overdraw");
}
#[test]
fn lifetime_extrema_survive_decimation() {
let mut t = DecimatingTrend::new(16);
t.push(1000.0);
for i in 0..500 {
t.push(i as f64);
}
assert_eq!(t.max, 1000.0, "max must be the discrete lifetime max");
assert_eq!(t.min, 0.0);
}
}
#[cfg(test)]
mod sparkline_tests {
use super::sparkline_str;
#[test]
fn noise_flat_series_renders_flat() {
let base = 200.0 / 3.0; let noisy: Vec<f64> = (0..16).map(|i| base + (i as f64) * 5e-14).collect();
let s = sparkline_str(&noisy, 16);
let glyphs: std::collections::HashSet<char> = s.chars().collect();
assert_eq!(
glyphs.len(),
1,
"noise-flat series must render one glyph, got {s:?}"
);
assert!(s.chars().all(|c| c == '▅'), "mid-height flat: {s:?}");
let real: Vec<f64> = (0..16).map(|i| i as f64).collect();
let s = sparkline_str(&real, 16);
assert!(
s.contains('▁') && s.contains('█'),
"real spread must span the bar range: {s:?}"
);
}
}
#[cfg(test)]
mod decimating_trend_tests {
use super::{DecimatingTrend, nearest_pow2_half};
#[test]
fn tail_is_bounded_from_the_start() {
let cap = 8;
let raw_cap = cap - nearest_pow2_half(cap); let mut t = DecimatingTrend::new(cap);
for v in 0..cap {
t.push(v as f64);
}
let (_hist, raw) = t.split_view();
assert_eq!(raw.len(), raw_cap, "tail is bounded at {raw_cap}");
assert_eq!(
raw,
vec![4.0, 5.0, 6.0, 7.0],
"tail holds the newest samples, unaveraged"
);
assert!(
t.hist_len() > 0,
"older samples fold into history rather than being dropped"
);
}
#[test]
fn history_folds_and_keeps_a_fixed_width_view() {
let cap = 8;
let hist_cap = nearest_pow2_half(cap); let mut t = DecimatingTrend::new(cap);
for v in 0..64 {
t.push(v as f64);
}
let (hist, raw) = t.split_view();
assert_eq!(hist.len(), hist_cap, "history view is a constant width");
assert_eq!(
hist.len() + raw.len(),
cap,
"the two regions tile the cell exactly"
);
assert!(
hist.windows(2).all(|w| w[0] <= w[1]),
"history stays ordered: {hist:?}"
);
assert_eq!(raw, vec![60.0, 61.0, 62.0, 63.0]);
}
#[test]
fn tiny_capacity_never_overflows_or_stalls() {
let mut t = DecimatingTrend::new(4);
for i in 0..100_000 {
t.push((i % 37) as f64);
assert!(t.series().len() <= 4, "series stays within capacity");
}
}
#[test]
fn lifetime_extrema_are_discrete_not_averaged() {
let mut t = DecimatingTrend::new(4);
for v in [5.0, 100.0, 1.0, 7.0, 9.0, 2.0] {
t.push(v);
}
assert_eq!(t.min, 1.0, "min is the discrete lifetime minimum");
assert_eq!(
t.max, 100.0,
"max survives even after its sample is averaged away"
);
}
}