Skip to content

Commit

Permalink
tiny_skia: Add a capacity limit to GlyphCache
Browse files Browse the repository at this point in the history
 * Trim the cache if `recently_used` size reaches the limit, even if a
   trim interval hasn't passed.
 * Shrink `entries` and `recently_used` to the limit when trimming.

Signed-off-by: Mohammad AlSaleh <CE.Mohammad.AlSaleh@gmail.com>
  • Loading branch information
MoSal committed Jan 31, 2024
1 parent 1c1667c commit e970123
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion tiny_skia/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ struct GlyphCache {

impl GlyphCache {
const TRIM_INTERVAL: usize = 300;
const CAPACITY_LIMIT: usize = 16 * 1024;

fn new() -> Self {
GlyphCache::default()
Expand Down Expand Up @@ -344,12 +345,17 @@ impl GlyphCache {
}

pub fn trim(&mut self) {
if self.trim_count > Self::TRIM_INTERVAL {
if self.trim_count > Self::TRIM_INTERVAL
|| self.recently_used.len() >= Self::CAPACITY_LIMIT
{
self.entries
.retain(|key, _| self.recently_used.contains(key));

self.recently_used.clear();

self.entries.shrink_to(Self::CAPACITY_LIMIT);
self.recently_used.shrink_to(Self::CAPACITY_LIMIT);

self.trim_count = 0;
} else {
self.trim_count += 1;
Expand Down

0 comments on commit e970123

Please sign in to comment.