Skip to main content

mln_engine/text/
glyph_cache.rs

1// Cached glyphs are held through `std::sync::Weak`, in a map from hash to a
2// bucket of weak references.
3
4use std::collections::BTreeMap;
5use std::hash::{DefaultHasher, Hash, Hasher};
6use std::sync::{Arc, Weak};
7
8use mln_style::hash::HashMap;
9use parking_lot::Mutex;
10
11use crate::text::glyph::{Glyph, GlyphID};
12
13/// The glyphs parsed from one glyph range.
14pub(crate) type GlyphCacheRange = BTreeMap<GlyphID, Arc<Glyph>>;
15
16/// The table sizes below which expired entries are left in place.
17const MIN_SWEEP: usize = 4096;
18
19/// Keeps one copy of equal glyphs and glyph ranges. It only holds weak
20/// references, so it never keeps a glyph alive. Renderers given the same
21/// cache share the glyphs they parse from glyph PBFs, across maps and font
22/// stacks. Thread-safe.
23#[derive(Default)]
24pub struct GlyphCache {
25    inner: Mutex<Inner>,
26}
27
28#[derive(Default)]
29struct Inner {
30    glyphs: Table<Glyph>,
31    ranges: Table<GlyphCacheRange>,
32}
33
34struct Table<T> {
35    buckets: HashMap<u64, Vec<Weak<T>>>,
36    /// Entries in `buckets`, expired or not.
37    len: usize,
38    next_sweep: usize,
39}
40
41impl<T> Default for Table<T> {
42    fn default() -> Self {
43        Table { buckets: HashMap::default(), len: 0, next_sweep: MIN_SWEEP }
44    }
45}
46
47impl<T> Table<T> {
48    /// The live entry equal to `value` by `eq`, or `value` added.
49    fn intern(&mut self, hash: u64, value: T, eq: impl Fn(&T, &T) -> bool) -> Arc<T> {
50        let bucket = self.buckets.entry(hash).or_default();
51        for weak in bucket.iter() {
52            if let Some(alive) = weak.upgrade()
53                && eq(&alive, &value)
54            {
55                return alive;
56            }
57        }
58        let added = Arc::new(value);
59        bucket.push(Arc::downgrade(&added));
60        self.len += 1;
61        if self.len >= self.next_sweep {
62            self.sweep();
63        }
64        added
65    }
66
67    /// Drops the expired entries. The next sweep waits until the table has
68    /// doubled, so sweeping costs constant time per insertion.
69    fn sweep(&mut self) {
70        self.buckets.retain(|_, bucket| {
71            bucket.retain(|weak| weak.strong_count() > 0);
72            !bucket.is_empty()
73        });
74        self.len = self.buckets.values().map(Vec::len).sum();
75        self.next_sweep = MIN_SWEEP.max(2 * self.len);
76    }
77}
78
79fn hash_glyph(glyph: &Glyph) -> u64 {
80    let mut hasher = DefaultHasher::new();
81    let metrics = &glyph.metrics;
82    glyph.id.hash().hash(&mut hasher);
83    metrics.width.hash(&mut hasher);
84    metrics.height.hash(&mut hasher);
85    metrics.left.to_bits().hash(&mut hasher);
86    metrics.top.to_bits().hash(&mut hasher);
87    metrics.advance.hash(&mut hasher);
88    metrics.is_double_resolution.hash(&mut hasher);
89    glyph.bitmap.size.width.hash(&mut hasher);
90    glyph.bitmap.size.height.hash(&mut hasher);
91    glyph.bitmap.data.hash(&mut hasher);
92    hasher.finish()
93}
94
95/// Ranges are the same when they point to the same glyphs.
96fn same_range(a: &GlyphCacheRange, b: &GlyphCacheRange) -> bool {
97    a.len() == b.len() && a.iter().zip(b).all(|((a_id, a), (b_id, b))| a_id == b_id && Arc::ptr_eq(a, b))
98}
99
100impl GlyphCache {
101    #[must_use]
102    #[cfg(test)]
103    pub(crate) fn new() -> Self {
104        Self::default()
105    }
106
107    /// `intern(Glyph&&)`: the cached glyph equal to `glyph`, or `glyph`
108    /// cached.
109    pub(crate) fn intern_glyph(&self, glyph: Glyph) -> Arc<Glyph> {
110        let hash = hash_glyph(&glyph);
111        self.inner.lock().glyphs.intern(hash, glyph, |a, b| a == b)
112    }
113
114    /// `intern(Range&&)`: the cached range that points to the same glyphs as
115    /// `range`, or `range` cached. Ranges are matched by the glyphs they
116    /// point to: intern the glyphs first.
117    pub(crate) fn intern_range(&self, range: GlyphCacheRange) -> Arc<GlyphCacheRange> {
118        let mut hasher = DefaultHasher::new();
119        for (id, glyph) in &range {
120            GlyphID::hash(*id).hash(&mut hasher);
121            Arc::as_ptr(glyph).hash(&mut hasher);
122        }
123        let hash = hasher.finish();
124        self.inner.lock().ranges.intern(hash, range, same_range)
125    }
126
127    /// The number of glyphs alive, not counting ranges. Walks the whole
128    /// table.
129    #[cfg(test)]
130    pub(crate) fn live_glyphs(&self) -> usize {
131        let inner = self.inner.lock();
132        inner.glyphs.buckets.values().flatten().filter(|weak| weak.strong_count() > 0).count()
133    }
134}