web engine - experimental web browser
at main 58 lines 1.6 kB view raw
1//! Glyph bitmap cache: avoids re-rasterizing the same glyphs at the same size. 2 3use std::collections::HashMap; 4 5use crate::font::rasterizer::GlyphBitmap; 6 7/// Cache key: (glyph_id, size_px quantized to integer pixels). 8type CacheKey = (u16, u16); 9 10/// A per-font cache of rasterized glyph bitmaps. 11/// 12/// Keys are `(glyph_id, size_px)` where size_px is rounded to the nearest 13/// integer pixel to bound cache size. No eviction policy — Phase 12 will 14/// add a texture atlas with LRU. 15#[derive(Debug)] 16pub struct GlyphCache { 17 entries: HashMap<CacheKey, GlyphBitmap>, 18} 19 20impl GlyphCache { 21 /// Create an empty glyph cache. 22 pub fn new() -> Self { 23 Self { 24 entries: HashMap::new(), 25 } 26 } 27 28 /// Quantize a floating-point pixel size to an integer key. 29 pub fn quantize_size(size_px: f32) -> u16 { 30 size_px.round().max(1.0) as u16 31 } 32 33 /// Look up a cached bitmap. Returns `None` on cache miss. 34 pub fn get(&self, glyph_id: u16, size_key: u16) -> Option<&GlyphBitmap> { 35 self.entries.get(&(glyph_id, size_key)) 36 } 37 38 /// Insert a rasterized bitmap into the cache. 39 pub fn insert(&mut self, glyph_id: u16, size_key: u16, bitmap: GlyphBitmap) { 40 self.entries.insert((glyph_id, size_key), bitmap); 41 } 42 43 /// Number of cached entries. 44 pub fn len(&self) -> usize { 45 self.entries.len() 46 } 47 48 /// Returns true if the cache is empty. 49 pub fn is_empty(&self) -> bool { 50 self.entries.is_empty() 51 } 52} 53 54impl Default for GlyphCache { 55 fn default() -> Self { 56 Self::new() 57 } 58}