Skip to main content

ferrochart_core/
text.rs

1//! Text measurement interface and allocation-free text helpers.
2//!
3//! The core needs text widths for axis sizing and label layout but must not depend
4//! on a font library. Hosts pass a [`TextMeasurer`] (implemented on top of
5//! `ferrochart-text` by the backends). ASCII text, which covers almost every axis
6//! label, is measured by summing a per-font advance table: no callback per label,
7//! no cache, no allocation.
8//!
9
10use core::fmt;
11
12use crate::frame::FontStyleRef;
13use crate::geom::SizePx;
14
15/// Measures text for layout.
16///
17/// Advance tables are given **per 1 px of font size** (em-normalized), because the
18/// core decides sizes at run time (theme size × device pixel ratio): the core
19/// multiplies by `style.size` itself.
20///
21/// # Examples
22///
23/// ```
24/// use ferrochart_core::frame::{FontId, FontStyleRef};
25/// use ferrochart_core::geom::SizePx;
26/// use ferrochart_core::text::{text_width, TextMeasurer};
27///
28/// struct Mono;
29/// impl TextMeasurer for Mono {
30///     fn ascii_advances(&self, _: FontStyleRef) -> &[f32; 128] { &[0.5; 128] }
31///     fn measure(&self, text: &str, style: FontStyleRef) -> SizePx {
32///         SizePx { w: text.chars().count() as f32 * 0.5 * style.size, h: style.size }
33///     }
34///     fn line_height(&self, style: FontStyleRef) -> f32 { style.size * 1.2 }
35/// }
36///
37/// let style = FontStyleRef { font: FontId(0), size: 10.0 };
38/// assert_eq!(text_width(&Mono, "1234", style), 20.0);
39/// ```
40pub trait TextMeasurer {
41    /// Advance widths of ASCII characters 0..128 at a font size of 1 px.
42    fn ascii_advances(&self, style: FontStyleRef) -> &[f32; 128];
43    /// Advance widths of the subscript digits `₀`..=`₉` (U+2080..=U+2089) at
44    /// a font size of 1 px. With a table, text made of ASCII and these digits
45    /// (small prices with automatic precision) takes the fast path; `None`
46    /// sends it to [`measure`](Self::measure).
47    fn subscript_advances(&self, style: FontStyleRef) -> Option<&[f32; 10]> {
48        let _ = style;
49        None
50    }
51    /// Size of arbitrary (non-ASCII) text in physical pixels. Slow path.
52    fn measure(&self, text: &str, style: FontStyleRef) -> SizePx;
53    /// Height of a line box (ascent - descent + line gap) in physical pixels.
54    fn line_height(&self, style: FontStyleRef) -> f32;
55}
56
57/// Width of `text` in physical pixels: the fast path for ASCII (and ASCII
58/// with subscript digits, when the measurer has their table),
59/// [`TextMeasurer::measure`] otherwise.
60pub fn text_width(m: &dyn TextMeasurer, text: &str, style: FontStyleRef) -> f32 {
61    let table = m.ascii_advances(style);
62    if text.is_ascii() {
63        return text
64            .bytes()
65            .map(|b| table[usize::from(b & 0x7F)])
66            .sum::<f32>()
67            * style.size;
68    }
69    if let Some(subs) = m.subscript_advances(style) {
70        let mut em = 0.0;
71        for c in text.chars() {
72            em += match c {
73                '\0'..='\x7F' => table[c as usize],
74                '\u{2080}'..='\u{2089}' => subs[c as usize - 0x2080],
75                _ => return m.measure(text, style).w,
76            };
77        }
78        return em * style.size;
79    }
80    m.measure(text, style).w
81}
82
83/// A fixed-capacity string on the stack, for formatting labels without allocating.
84/// Writes beyond the capacity fail with `fmt::Error`.
85///
86/// # Examples
87///
88/// ```
89/// use core::fmt::Write;
90/// use ferrochart_core::text::StackStr;
91///
92/// let mut s = StackStr::<16>::new();
93/// write!(s, "{:.2}", 3.14159).unwrap();
94/// assert_eq!(s.as_str(), "3.14");
95/// ```
96#[derive(Clone, Copy, Debug)]
97pub struct StackStr<const N: usize> {
98    buf: [u8; N],
99    len: usize,
100}
101
102impl<const N: usize> StackStr<N> {
103    /// An empty string.
104    pub const fn new() -> Self {
105        Self {
106            buf: [0; N],
107            len: 0,
108        }
109    }
110
111    /// The contents.
112    pub fn as_str(&self) -> &str {
113        // Only whole `&str`s are ever copied in, so this is valid UTF-8.
114        core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
115    }
116
117    /// Empties the string.
118    pub fn clear(&mut self) {
119        self.len = 0;
120    }
121}
122
123impl<const N: usize> Default for StackStr<N> {
124    fn default() -> Self {
125        Self::new()
126    }
127}
128
129impl<const N: usize> fmt::Write for StackStr<N> {
130    fn write_str(&mut self, s: &str) -> fmt::Result {
131        let end = self.len + s.len();
132        if end > N {
133            return Err(fmt::Error);
134        }
135        self.buf[self.len..end].copy_from_slice(s.as_bytes());
136        self.len = end;
137        Ok(())
138    }
139}