mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// Cached glyphs are held through `std::sync::Weak`, in a map from hash to a
// bucket of weak references.

use std::collections::BTreeMap;
use std::hash::{BuildHasher, Hash, Hasher};
use std::sync::{Arc, Weak};

use mln_style::hash::{HashMap, RandomState};
use parking_lot::Mutex;

use crate::text::glyph::{Glyph, GlyphID};

/// The glyphs parsed from one glyph range.
pub(crate) type GlyphCacheRange = BTreeMap<GlyphID, Arc<Glyph>>;

/// The table sizes below which expired entries are left in place.
const MIN_SWEEP: usize = 4096;

/// Keeps one copy of equal glyphs and glyph ranges. It only holds weak
/// references, so it never keeps a glyph alive. Renderers given the same
/// cache share the glyphs they parse from glyph PBFs, across maps and font
/// stacks. Thread-safe.
#[derive(Default)]
pub struct GlyphCache {
    inner: Mutex<Inner>,
    /// Glyphs come from the network: a seed of the cache's own (fixed only
    /// in the benchmarks' builds) keeps their hashes from being chosen to
    /// collide.
    hasher: RandomState,
}

#[derive(Default)]
struct Inner {
    glyphs: Table<Glyph>,
    ranges: Table<GlyphCacheRange>,
}

struct Table<T> {
    buckets: HashMap<u64, Vec<Weak<T>>>,
    /// Entries in `buckets`, expired or not.
    len: usize,
    next_sweep: usize,
}

impl<T> Default for Table<T> {
    fn default() -> Self {
        Table { buckets: HashMap::default(), len: 0, next_sweep: MIN_SWEEP }
    }
}

impl<T> Table<T> {
    /// The live entry equal to `value` by `eq`, or `value` added.
    fn intern(&mut self, hash: u64, value: T, eq: impl Fn(&T, &T) -> bool) -> Arc<T> {
        let bucket = self.buckets.entry(hash).or_default();
        for weak in bucket.iter() {
            if let Some(alive) = weak.upgrade()
                && eq(&alive, &value)
            {
                return alive;
            }
        }
        let added = Arc::new(value);
        bucket.push(Arc::downgrade(&added));
        self.len += 1;
        if self.len >= self.next_sweep {
            self.sweep();
        }
        added
    }

    /// Drops the expired entries. The next sweep waits until the table has
    /// doubled, so sweeping costs constant time per insertion.
    fn sweep(&mut self) {
        self.buckets.retain(|_, bucket| {
            bucket.retain(|weak| weak.strong_count() > 0);
            !bucket.is_empty()
        });
        self.len = self.buckets.values().map(Vec::len).sum();
        self.next_sweep = MIN_SWEEP.max(2 * self.len);
    }
}

/// Ranges are the same when they point to the same glyphs.
fn same_range(a: &GlyphCacheRange, b: &GlyphCacheRange) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|((a_id, a), (b_id, b))| a_id == b_id && Arc::ptr_eq(a, b))
}

impl GlyphCache {
    #[must_use]
    #[cfg(test)]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// The cached range of the cached glyphs equal to `glyphs`, each glyph
    /// cached if it wasn't. A glyph is shared by every range that has it.
    pub(crate) fn intern_range(&self, glyphs: Vec<Glyph>) -> Arc<GlyphCacheRange> {
        let hashes: Vec<u64> = glyphs.iter().map(|glyph| self.hash_glyph(glyph)).collect();
        let mut inner = self.inner.lock();
        let range: GlyphCacheRange = glyphs
            .into_iter()
            .zip(hashes)
            .map(|(glyph, hash)| (glyph.id, inner.glyphs.intern(hash, glyph, |a, b| a == b)))
            .collect();
        let mut hasher = self.hasher.build_hasher();
        for (id, glyph) in &range {
            GlyphID::hash(*id).hash(&mut hasher);
            Arc::as_ptr(glyph).hash(&mut hasher);
        }
        inner.ranges.intern(hasher.finish(), range, same_range)
    }

    fn hash_glyph(&self, glyph: &Glyph) -> u64 {
        let mut hasher = self.hasher.build_hasher();
        let metrics = &glyph.metrics;
        glyph.id.hash().hash(&mut hasher);
        metrics.width.hash(&mut hasher);
        metrics.height.hash(&mut hasher);
        metrics.left.to_bits().hash(&mut hasher);
        metrics.top.to_bits().hash(&mut hasher);
        metrics.advance.hash(&mut hasher);
        metrics.is_double_resolution.hash(&mut hasher);
        glyph.bitmap.size.width.hash(&mut hasher);
        glyph.bitmap.size.height.hash(&mut hasher);
        glyph.bitmap.data.hash(&mut hasher);
        hasher.finish()
    }

    /// The number of glyphs alive, not counting ranges. Walks the whole
    /// table.
    #[cfg(test)]
    pub(crate) fn live_glyphs(&self) -> usize {
        let inner = self.inner.lock();
        inner.glyphs.buckets.values().flatten().filter(|weak| weak.strong_count() > 0).count()
    }
}

#[cfg(test)]
#[path = "glyph_cache_test.rs"]
mod tests;