cosmic_text/
shape_run_cache.rs

1#[cfg(not(feature = "std"))]
2use alloc::{string::String, vec::Vec};
3use core::ops::Range;
4
5use crate::{AttrsOwned, HashMap, ShapeGlyph};
6
7/// Key for caching shape runs.
8#[derive(Clone, Debug, Hash, PartialEq, Eq)]
9pub struct ShapeRunKey {
10    pub text: String,
11    pub default_attrs: AttrsOwned,
12    pub attrs_spans: Vec<(Range<usize>, AttrsOwned)>,
13}
14
15/// A helper structure for caching shape runs.
16#[derive(Clone, Default)]
17pub struct ShapeRunCache {
18    age: u64,
19    cache: HashMap<ShapeRunKey, (u64, Vec<ShapeGlyph>)>,
20}
21
22impl ShapeRunCache {
23    /// Get cache item, updating age if found
24    pub fn get(&mut self, key: &ShapeRunKey) -> Option<&Vec<ShapeGlyph>> {
25        self.cache.get_mut(key).map(|(age, glyphs)| {
26            *age = self.age;
27            &*glyphs
28        })
29    }
30
31    /// Insert cache item with current age
32    pub fn insert(&mut self, key: ShapeRunKey, glyphs: Vec<ShapeGlyph>) {
33        self.cache.insert(key, (self.age, glyphs));
34    }
35
36    /// Remove anything in the cache with an age older than `keep_ages`
37    pub fn trim(&mut self, keep_ages: u64) {
38        self.cache
39            .retain(|_key, (age, _glyphs)| *age + keep_ages >= self.age);
40        // Increase age
41        self.age += 1;
42    }
43}
44
45impl core::fmt::Debug for ShapeRunCache {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        f.debug_tuple("ShapeRunCache").finish()
48    }
49}