pub(crate) const H_EIGHTHS: [char; 9] = [
' ', '\u{258F}', '\u{258E}', '\u{258D}', '\u{258C}', '\u{258B}', '\u{258A}', '\u{2589}', '\u{2588}', ];
pub(crate) fn h_bar(width: u16, ratio: f64) -> String {
let ratio = ratio.clamp(0.0, 1.0);
let total_eighths = (ratio * width as f64 * 8.0).round() as u32;
let full = ((total_eighths / 8) as u16).min(width);
let rem = (total_eighths % 8) as usize;
let mut s = String::with_capacity(width as usize);
let mut cols = 0u16;
for _ in 0..full {
s.push('\u{2588}');
cols += 1;
}
if cols < width && rem > 0 {
s.push(H_EIGHTHS[rem]);
cols += 1;
}
while cols < width {
s.push(' ');
cols += 1;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
fn cols(s: &str) -> usize {
s.chars().count()
}
#[test]
fn full_ratio_fills_all_cells() {
let s = h_bar(8, 1.0);
assert_eq!(cols(&s), 8);
assert!(s.chars().all(|c| c == '\u{2588}'));
}
#[test]
fn zero_ratio_is_all_spaces() {
let s = h_bar(8, 0.0);
assert_eq!(cols(&s), 8);
assert!(s.chars().all(|c| c == ' '));
}
#[test]
fn half_of_eight_is_four_full_blocks() {
let s = h_bar(8, 0.5);
assert_eq!(cols(&s), 8);
assert_eq!(s.chars().filter(|&c| c == '\u{2588}').count(), 4);
assert_eq!(s.chars().filter(|&c| c == ' ').count(), 4);
}
#[test]
fn fractional_uses_a_partial_block() {
let s = h_bar(4, 0.375); assert_eq!(cols(&s), 4);
assert_eq!(s.chars().filter(|&c| c == '\u{2588}').count(), 1);
assert!(
s.contains('\u{258C}'),
"expected a half-block partial: {s:?}"
);
}
#[test]
fn always_exactly_width_columns() {
for w in 1..20u16 {
for r in [0.0, 0.1, 0.33, 0.5, 0.9, 1.0, 1.5, -0.2] {
assert_eq!(cols(&h_bar(w, r)), w as usize, "w={w} r={r}");
}
}
}
}