use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::sync::Arc;
use rustc_hash::FxHashMap;
#[derive(Clone, Debug, PartialEq)]
pub struct FontSpec {
pub family: Arc<str>,
pub size: f32,
pub weight: u16,
pub italic: bool,
}
impl FontSpec {
#[must_use]
pub fn css(&self) -> String {
self.to_string()
}
pub fn families(&self) -> impl Iterator<Item = &str> {
self.family
.split(',')
.map(|name| name.trim().trim_matches(['"', '\'']).trim())
.filter(|name| !name.is_empty())
}
#[must_use]
pub fn uses_family(&self, family: &str) -> bool {
let family = family.trim().trim_matches(['"', '\'']);
self.families()
.any(|name| name.eq_ignore_ascii_case(family))
}
}
impl fmt::Display for FontSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let style = if self.italic { "italic" } else { "normal" };
let size = crate::render::css_number(self.size);
write!(f, "{style} {} {size}px {}", self.weight, self.family)
}
}
impl Eq for FontSpec {}
impl Hash for FontSpec {
fn hash<H: Hasher>(&self, state: &mut H) {
self.family.hash(state);
self.size.to_bits().hash(state);
self.weight.hash(state);
self.italic.hash(state);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontId(pub(crate) u32);
impl FontId {
#[must_use]
pub const fn from_index(index: usize) -> Self {
Self(index as u32)
}
#[must_use]
pub const fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FontMetrics {
pub ascent: f32,
pub descent: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LineBox {
pub above: f32,
pub below: f32,
}
impl LineBox {
#[must_use]
pub fn from_metrics(metrics: FontMetrics, line_height: f32) -> Self {
let half_leading = (line_height - metrics.ascent - metrics.descent) / 2.0;
Self {
above: metrics.ascent + half_leading,
below: metrics.descent + half_leading,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct FontBook {
fonts: Vec<FontSpec>,
ids: FxHashMap<FontSpec, FontId>,
}
impl FontBook {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn intern(&mut self, spec: &FontSpec) -> FontId {
if let Some(&id) = self.ids.get(spec) {
return id;
}
let id = FontId(self.fonts.len() as u32);
self.fonts.push(spec.clone());
self.ids.insert(spec.clone(), id);
id
}
#[must_use]
pub fn find(&self, spec: &FontSpec) -> Option<FontId> {
self.ids.get(spec).copied()
}
#[must_use]
pub fn get(&self, id: FontId) -> Option<&FontSpec> {
self.fonts.get(id.index())
}
#[must_use]
pub fn fonts(&self) -> &[FontSpec] {
&self.fonts
}
#[must_use]
pub fn len(&self) -> usize {
self.fonts.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.fonts.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
const BODY_SIZE: f32 = 16.0;
const CODE_SIZE: f32 = 13.6;
fn inter(size: f32) -> FontSpec {
FontSpec {
family: Arc::from("Inter, sans-serif"),
size,
weight: 400,
italic: false,
}
}
#[test]
fn interning_is_stable() {
let mut book = FontBook::new();
let body = book.intern(&inter(BODY_SIZE));
let code = book.intern(&inter(CODE_SIZE));
assert_ne!(body, code);
assert_eq!(book.intern(&inter(BODY_SIZE)), body);
assert_eq!(book.get(code).map(|font| font.size), Some(CODE_SIZE));
assert_eq!(book.len(), 2);
}
#[test]
fn family_lists() {
let font = FontSpec {
family: Arc::from("Inter, \"Noto Sans JP\", 'Apple Color Emoji' , sans-serif"),
..inter(BODY_SIZE)
};
assert_eq!(
font.families().collect::<Vec<_>>(),
["Inter", "Noto Sans JP", "Apple Color Emoji", "sans-serif"]
);
assert!(font.uses_family("noto sans jp"));
assert!(font.uses_family("\"Inter\""));
assert!(!font.uses_family("Noto Sans"));
}
#[test]
fn css_shorthand() {
let font = FontSpec {
weight: 700,
italic: true,
..inter(BODY_SIZE)
};
assert_eq!(font.css(), "italic 700 16px Inter, sans-serif");
}
}