#[derive(Debug, Clone, PartialEq)]
pub struct SimpleWidths {
first_char: u32,
widths: Vec<f32>,
missing_width: f32,
default_width: f32,
}
impl SimpleWidths {
pub fn new(first_char: u32, widths: Vec<f32>, missing_width: f32) -> Self {
Self {
first_char,
widths,
missing_width,
default_width: 500.0,
}
}
pub fn empty() -> Self {
Self {
first_char: 0,
widths: Vec::new(),
missing_width: 0.0,
default_width: 500.0,
}
}
pub fn advance(&self, code: u32) -> f32 {
if self.widths.is_empty() {
return self.default_width;
}
if code >= self.first_char {
let idx = (code - self.first_char) as usize;
if idx < self.widths.len() {
return self.widths[idx];
}
}
self.missing_width
}
pub fn has_widths(&self) -> bool {
!self.widths.is_empty()
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn in_range_and_out_of_range() {
let w = SimpleWidths::new(65, vec![600.0, 700.0, 800.0], 250.0);
assert_eq!(w.advance(65), 600.0);
assert_eq!(w.advance(67), 800.0);
assert_eq!(w.advance(64), 250.0, "below range → missing");
assert_eq!(w.advance(200), 250.0, "above range → missing");
}
#[test]
fn zero_width_is_honored() {
let w = SimpleWidths::new(0, vec![0.0, 500.0], 100.0);
assert_eq!(w.advance(0), 0.0, "explicit 0 width is not 'missing'");
}
#[test]
fn empty_uses_default() {
let w = SimpleWidths::empty();
assert_eq!(w.advance(42), 500.0);
assert!(!w.has_widths());
}
}