const AVG_CHAR_WIDTH_RATIO: f64 = 0.6;
pub fn approx_width(text: &str, font_size: f64) -> f64 {
text.split('\n')
.map(|line| line.chars().count() as f64 * font_size * AVG_CHAR_WIDTH_RATIO)
.fold(0.0_f64, f64::max)
}
const LINE_SPACING: f64 = 1.2;
const LINE_HEIGHT: f64 = 1.0;
pub fn approx_height(text: &str, font_size: f64) -> f64 {
let line_count = text.split('\n').count().max(1) as f64;
let ems = if line_count > 1.0 {
line_count * LINE_SPACING
} else {
LINE_HEIGHT
};
ems * font_size
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn single_line_width_scales_with_chars_and_size() {
let w = approx_width("hello", 13.0);
assert!((w - 39.0).abs() < 0.01, "got {}", w);
}
#[test]
fn multi_line_picks_widest() {
let w = approx_width("hi\nhello", 10.0);
assert!((w - 30.0).abs() < 0.01, "got {}", w);
}
#[test]
fn height_grows_with_lines() {
let h1 = approx_height("a", 10.0);
let h2 = approx_height("a\nb", 10.0);
assert!((h1 - 10.0).abs() < 0.01, "got {h1}");
assert!((h2 - 24.0).abs() < 0.01, "got {h2}");
}
}