use core::fmt;
use crate::frame::FontStyleRef;
use crate::geom::SizePx;
pub trait TextMeasurer {
fn ascii_advances(&self, style: FontStyleRef) -> &[f32; 128];
fn subscript_advances(&self, style: FontStyleRef) -> Option<&[f32; 10]> {
let _ = style;
None
}
fn measure(&self, text: &str, style: FontStyleRef) -> SizePx;
fn line_height(&self, style: FontStyleRef) -> f32;
}
pub fn text_width(m: &dyn TextMeasurer, text: &str, style: FontStyleRef) -> f32 {
let table = m.ascii_advances(style);
if text.is_ascii() {
return text
.bytes()
.map(|b| table[usize::from(b & 0x7F)])
.sum::<f32>()
* style.size;
}
if let Some(subs) = m.subscript_advances(style) {
let mut em = 0.0;
for c in text.chars() {
em += match c {
'\0'..='\x7F' => table[c as usize],
'\u{2080}'..='\u{2089}' => subs[c as usize - 0x2080],
_ => return m.measure(text, style).w,
};
}
return em * style.size;
}
m.measure(text, style).w
}
#[derive(Clone, Copy, Debug)]
pub struct StackStr<const N: usize> {
buf: [u8; N],
len: usize,
}
impl<const N: usize> StackStr<N> {
pub const fn new() -> Self {
Self {
buf: [0; N],
len: 0,
}
}
pub fn as_str(&self) -> &str {
core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
}
pub fn clear(&mut self) {
self.len = 0;
}
}
impl<const N: usize> Default for StackStr<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> fmt::Write for StackStr<N> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let end = self.len + s.len();
if end > N {
return Err(fmt::Error);
}
self.buf[self.len..end].copy_from_slice(s.as_bytes());
self.len = end;
Ok(())
}
}