use uzor::fonts::FontFamily;
use super::{FontId, PdfBuilder};
pub struct PdfFontCache(Vec<((FontFamily, bool, bool), FontId)>);
impl Default for PdfFontCache {
fn default() -> Self {
Self::new()
}
}
impl PdfFontCache {
pub fn new() -> Self {
Self(Vec::new())
}
pub fn id_for(&mut self, family: FontFamily, bold: bool, italic: bool, builder: &mut PdfBuilder) -> FontId {
let key = (family, bold, italic);
if let Some(&(_, id)) = self.0.iter().find(|&&(k, _)| k == key) {
return id;
}
let bytes = uzor::fonts::font_bytes(family, bold, italic);
let id = builder.register_font(bytes);
self.0.push((key, id));
id
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_same_family_bold_italic_combination_reuses_the_same_font_id() {
let mut builder = PdfBuilder::new();
let mut cache = PdfFontCache::new();
let a = cache.id_for(FontFamily::Roboto, false, false, &mut builder);
let b = cache.id_for(FontFamily::Roboto, false, false, &mut builder);
assert_eq!(a, b, "the same (family, bold, italic) key must resolve to the SAME FontId across calls");
}
#[test]
fn a_different_style_combination_registers_a_distinct_font_id() {
let mut builder = PdfBuilder::new();
let mut cache = PdfFontCache::new();
let regular = cache.id_for(FontFamily::Roboto, false, false, &mut builder);
let bold = cache.id_for(FontFamily::Roboto, true, false, &mut builder);
assert_ne!(regular, bold, "a different bold/italic combination must register its own FontId");
}
}