From f25ce3949366a04f63d30b93def0a43b32ffba99 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:48:59 +0000 Subject: [PATCH] Share per-face shaping plan cache --- crates/font-catalog/src/lib.rs | 2 ++ crates/font-catalog/src/plan_cache.rs | 52 +++++++++++++++++++++++++++ crates/font-catalog/src/tests.rs | 19 ++++++++++ 3 files changed, 73 insertions(+) create mode 100644 crates/font-catalog/src/plan_cache.rs diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index 992b75080..b4271db7e 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -27,6 +27,7 @@ mod fontconfig; mod ligature; mod line_break; mod outline; +mod plan_cache; mod registry; mod scan; mod segments; @@ -42,6 +43,7 @@ pub use fontconfig::fontconfig_dirs; pub use ligature::ligature_caret_stops; pub use line_break::settle_line_break; pub use outline::{FontOutline, GlyphPen, OutlineError}; +pub use plan_cache::ShapePlanCache; pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width}; pub use segments::SegmentBoundary; pub use shape::{RunGlyph, RunInput, ShapeRunError, shape_run}; diff --git a/crates/font-catalog/src/plan_cache.rs b/crates/font-catalog/src/plan_cache.rs new file mode 100644 index 000000000..d428de4cd --- /dev/null +++ b/crates/font-catalog/src/plan_cache.rs @@ -0,0 +1,52 @@ +//! Per-face bounded shaping plan reuse. + +use std::sync::{Arc, Mutex}; + +/// A cache for one font face and variation instance. Do not share it across faces or instances. +/// Plans are created outside the lock, then checked again to avoid retaining duplicates. +#[derive(Default)] +pub struct ShapePlanCache { + plans: Mutex>>, +} + +impl ShapePlanCache { + /// Maximum number of plans retained; the oldest is evicted when this is reached. + pub const CAPACITY: usize = 32; + + /// Returns a matching plan or builds and retains one for this face. + pub fn get_or_create( + &self, + shaper: &harfrust::Shaper<'_>, + instance: Option<&harfrust::ShaperInstance>, + direction: harfrust::Direction, + script: Option, + language: Option<&harfrust::Language>, + features: &[harfrust::Feature], + ) -> Arc { + let key = harfrust::ShapePlanKey::new(script, direction).language(language).instance(instance).features(features); + let kept = |plans: &[Arc]| plans.iter().rev().find(|p| key.matches(p)).cloned(); + if let Some(plan) = kept(&self.plans.lock().unwrap_or_else(|e| e.into_inner())) { + return plan; + } + let plan = Arc::new(harfrust::ShapePlan::new(shaper, direction, script, language, features)); + let mut plans = self.plans.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(made) = kept(&plans) { + return made; + } + if plans.len() >= Self::CAPACITY { + plans.remove(0); + } + plans.push(plan.clone()); + plan + } + + /// Number of retained plans. + pub fn len(&self) -> usize { + self.plans.lock().unwrap_or_else(|e| e.into_inner()).len() + } + + /// Whether this cache contains no plans. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 5137a4295..c7623da43 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -568,3 +568,22 @@ fn a_read_is_capped_where_the_file_has_grown() { assert!(matches!(read_capped(&path.with_extension("missing"), 9), Err(FontFileError::Io(_)))); let _ = std::fs::remove_file(&path); } + +#[test] +fn shape_plan_cache_reuses_and_evicts_plans() { + let data = font(&spec("Test", "Regular", 400)); + let face = harfrust::FontRef::from_index(&data, 0).unwrap(); + let shaper_data = harfrust::ShaperData::new(&face); + let shaper = shaper_data.shaper(&face).build(); + let cache = ShapePlanCache::default(); + let make = |language: &harfrust::Language| cache.get_or_create(&shaper, None, harfrust::Direction::LeftToRight, None, Some(language), &[]); + let languages: Vec = ('a'..='z').flat_map(|a| ['a', 'b'].map(move |b| format!("{a}{b}").parse().unwrap())).collect(); + let first = make(&languages[0]); + assert!(Arc::ptr_eq(&first, &make(&languages[0]))); + for language in languages.iter().skip(1) { + make(language); + } + assert_eq!(cache.len(), ShapePlanCache::CAPACITY); + assert!(!Arc::ptr_eq(&first, &make(&languages[0]))); + assert_eq!(cache.len(), ShapePlanCache::CAPACITY); +}