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::{BuildHasher, Hash, Hasher};
6use std::sync::{Arc, Weak};
7
8use mln_style::hash::{HashMap, RandomState};
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    /// Glyphs come from the network: a seed of the cache's own (fixed only
27    /// in the benchmarks' builds) keeps their hashes from being chosen to
28    /// collide.
29    hasher: RandomState,
30}
31
32#[derive(Default)]
33struct Inner {
34    glyphs: Table<Glyph>,
35    ranges: Table<GlyphCacheRange>,
36}
37
38struct Table<T> {
39    buckets: HashMap<u64, Vec<Weak<T>>>,
40    /// Entries in `buckets`, expired or not.
41    len: usize,
42    next_sweep: usize,
43}
44
45impl<T> Default for Table<T> {
46    fn default() -> Self {
47        Table { buckets: HashMap::default(), len: 0, next_sweep: MIN_SWEEP }
48    }
49}
50
51impl<T> Table<T> {
52    /// The live entry equal to `value` by `eq`, or `value` added.
53    fn intern(&mut self, hash: u64, value: T, eq: impl Fn(&T, &T) -> bool) -> Arc<T> {
54        let bucket = self.buckets.entry(hash).or_default();
55        for weak in bucket.iter() {
56            if let Some(alive) = weak.upgrade()
57                && eq(&alive, &value)
58            {
59                return alive;
60            }
61        }
62        let added = Arc::new(value);
63        bucket.push(Arc::downgrade(&added));
64        self.len += 1;
65        if self.len >= self.next_sweep {
66            self.sweep();
67        }
68        added
69    }
70
71    /// Drops the expired entries. The next sweep waits until the table has
72    /// doubled, so sweeping costs constant time per insertion.
73    fn sweep(&mut self) {
74        self.buckets.retain(|_, bucket| {
75            bucket.retain(|weak| weak.strong_count() > 0);
76            !bucket.is_empty()
77        });
78        self.len = self.buckets.values().map(Vec::len).sum();
79        self.next_sweep = MIN_SWEEP.max(2 * self.len);
80    }
81}
82
83/// Ranges are the same when they point to the same glyphs.
84fn same_range(a: &GlyphCacheRange, b: &GlyphCacheRange) -> bool {
85    a.len() == b.len() && a.iter().zip(b).all(|((a_id, a), (b_id, b))| a_id == b_id && Arc::ptr_eq(a, b))
86}
87
88impl GlyphCache {
89    #[must_use]
90    #[cfg(test)]
91    pub(crate) fn new() -> Self {
92        Self::default()
93    }
94
95    /// The cached range of the cached glyphs equal to `glyphs`, each glyph
96    /// cached if it wasn't. A glyph is shared by every range that has it.
97    pub(crate) fn intern_range(&self, glyphs: Vec<Glyph>) -> Arc<GlyphCacheRange> {
98        let hashes: Vec<u64> = glyphs.iter().map(|glyph| self.hash_glyph(glyph)).collect();
99        let mut inner = self.inner.lock();
100        let range: GlyphCacheRange = glyphs
101            .into_iter()
102            .zip(hashes)
103            .map(|(glyph, hash)| (glyph.id, inner.glyphs.intern(hash, glyph, |a, b| a == b)))
104            .collect();
105        let mut hasher = self.hasher.build_hasher();
106        for (id, glyph) in &range {
107            GlyphID::hash(*id).hash(&mut hasher);
108            Arc::as_ptr(glyph).hash(&mut hasher);
109        }
110        inner.ranges.intern(hasher.finish(), range, same_range)
111    }
112
113    fn hash_glyph(&self, glyph: &Glyph) -> u64 {
114        let mut hasher = self.hasher.build_hasher();
115        let metrics = &glyph.metrics;
116        glyph.id.hash().hash(&mut hasher);
117        metrics.width.hash(&mut hasher);
118        metrics.height.hash(&mut hasher);
119        metrics.left.to_bits().hash(&mut hasher);
120        metrics.top.to_bits().hash(&mut hasher);
121        metrics.advance.hash(&mut hasher);
122        metrics.is_double_resolution.hash(&mut hasher);
123        glyph.bitmap.size.width.hash(&mut hasher);
124        glyph.bitmap.size.height.hash(&mut hasher);
125        glyph.bitmap.data.hash(&mut hasher);
126        hasher.finish()
127    }
128
129    /// The number of glyphs alive, not counting ranges. Walks the whole
130    /// table.
131    #[cfg(test)]
132    pub(crate) fn live_glyphs(&self) -> usize {
133        let inner = self.inner.lock();
134        inner.glyphs.buckets.values().flatten().filter(|weak| weak.strong_count() > 0).count()
135    }
136}
137
138#[cfg(test)]
139#[path = "glyph_cache_test.rs"]
140mod tests;