Skip to main content

mln_engine/text/
glyph_cache.rs

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