Skip to main content

euv_core/font/shaping/
impl.rs

1use super::*;
2
3/// Construction helpers for `TextShapingKey`.
4impl TextShapingKey {
5    /// Computes dual 64-bit FNV-1a hashes over `bytes` to form a 128-bit collision-resistant digest.
6    ///
7    /// # Arguments
8    ///
9    /// - `&[u8]` - Input UTF-8 byte slice.
10    ///
11    /// # Returns
12    ///
13    /// - `(u64, u64)` - Dual 64-bit hash pair `(hash_a, hash_b)`.
14    #[must_use]
15    pub fn hash_bytes_128(bytes: &[u8]) -> (u64, u64) {
16        let mut ha: u64 = SHAPING_FNV_OFFSET_A;
17        let mut hb: u64 = SHAPING_FNV_OFFSET_B;
18        for (idx, &b) in bytes.iter().enumerate() {
19            ha ^= b as u64;
20            ha = ha.wrapping_mul(SHAPING_FNV_PRIME);
21            hb ^= (b as u64).wrapping_add((idx as u64).wrapping_mul(31));
22            hb = hb.wrapping_mul(SHAPING_FNV_PRIME);
23        }
24        (ha, hb)
25    }
26
27    /// Builds a DPI- and wrap-width-independent `TextShapingKey` from `text`, `style`, locale, direction, and font-chain revision.
28    ///
29    /// # Arguments
30    ///
31    /// - `&str` - Source UTF-8 text content.
32    /// - `TextStyle` - Typography style (color, alignment, and overflow are intentionally excluded).
33    /// - `&str` - Active BCP-47 locale identifier.
34    /// - `bool` - Whether right-to-left base direction is enabled.
35    /// - `u64` - Active font fallback chain revision.
36    ///
37    /// # Returns
38    ///
39    /// - `Self` - Constructed shaping cache key.
40    #[must_use]
41    pub fn from_text(
42        text: &str,
43        style: TextStyle,
44        locale: &str,
45        rtl: bool,
46        font_chain_revision: u64,
47    ) -> Self {
48        let (text_hash_a, text_hash_b): (u64, u64) = Self::hash_bytes_128(text.as_bytes());
49        let (locale_hash, _): (u64, u64) = Self::hash_bytes_128(locale.as_bytes());
50        Self {
51            text_hash_a,
52            text_hash_b,
53            text_len: text.len() as u32,
54            font_size_bits: style.get_font_size().to_bits(),
55            family: style.get_family(),
56            weight: style.get_weight(),
57            italic: style.get_italic(),
58            letter_spacing_bits: style.get_letter_spacing().to_bits(),
59            locale_hash,
60            rtl,
61            font_chain_revision,
62        }
63    }
64
65    /// Builds a paired `LineBreakKey` binding this shaping key to `max_width`, `line_height`, and `overflow`.
66    ///
67    /// # Arguments
68    ///
69    /// - `&Self` - Base shaping key.
70    /// - `Option<f32>` - Optional logical wrap width limit.
71    /// - `TextStyle` - Typography style providing `line_height` and `overflow`.
72    ///
73    /// # Returns
74    ///
75    /// - `LineBreakKey` - Line-break cache key independent of DPI scale and text color.
76    #[must_use]
77    pub fn line_break_key(&self, max_width: Option<f32>, style: TextStyle) -> LineBreakKey {
78        let width_bits: u32 = match max_width {
79            Some(w) if w.is_finite() => ((w.max(0.0) * 10.0).round() as u32).min(u32::MAX - 1),
80            _ => u32::MAX,
81        };
82        let mut ha: u64 = self.get_text_hash_a();
83        let mut hb: u64 = self.get_text_hash_b();
84        let meta: u64 =
85            ((self.get_font_size_bits() as u64) << 32) | (self.get_letter_spacing_bits() as u64);
86        ha = (ha ^ meta).wrapping_mul(SHAPING_FNV_PRIME);
87        hb = (hb ^ self.get_locale_hash() ^ ((self.get_family() as u64) << 8))
88            .wrapping_mul(SHAPING_FNV_PRIME);
89        LineBreakKey {
90            shaping_hash_a: ha,
91            shaping_hash_b: hb,
92            max_width_bits: width_bits,
93            line_height_bits: style.get_line_height().to_bits(),
94            overflow: style.get_overflow(),
95            font_chain_revision: self.get_font_chain_revision(),
96        }
97    }
98}
99
100/// Default bounded text shaping cache initialized with `TEXT_SHAPING_DEFAULT_BUDGET_BYTES`.
101impl Default for TextShapingCache {
102    /// Creates an empty bounded `TextShapingCache` with the default 4 MiB budget.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Empty text shaping cache.
107    fn default() -> Self {
108        Self::with_budget(TEXT_SHAPING_DEFAULT_BUDGET_BYTES)
109    }
110}
111
112/// Split shaping & line-break caching, independent font-chain invalidation, and bounded LRU eviction for `TextShapingCache`.
113impl TextShapingCache {
114    /// Creates a `TextShapingCache` enforcing `budget_bytes` across shaping runs and wrapped line layouts.
115    ///
116    /// # Arguments
117    ///
118    /// - `usize` - Resident byte ceiling (clamped to `>= TEXT_SHAPING_MIN_BUDGET_BYTES`).
119    ///
120    /// # Returns
121    ///
122    /// - `Self` - Configured empty shaping cache.
123    #[must_use]
124    pub fn with_budget(budget_bytes: usize) -> Self {
125        Self {
126            budget_bytes: budget_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES),
127            resident_bytes: 0,
128            font_chain_revision: 1,
129            lru_clock: 0,
130            shaped_runs: HashMap::new(),
131            line_breaks: HashMap::new(),
132            shaping_hits: 0,
133            shaping_misses: 0,
134            line_break_hits: 0,
135            line_break_misses: 0,
136            evictions: 0,
137        }
138    }
139
140    /// Updates the resident byte budget and immediately evicts cold entries if currently over budget.
141    ///
142    /// # Arguments
143    ///
144    /// - `&Self` - Mutable shaping cache.
145    /// - `usize` - New maximum resident bytes.
146    pub fn set_memory_budget(&mut self, max_bytes: usize) {
147        self.set_budget_bytes(max_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES));
148        self.evict_if_over_budget();
149    }
150
151    /// Advances the font fallback chain revision and invalidates all cached shaping and line-break entries.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Mutable shaping cache.
156    /// - `u64` - New monotonic font fallback chain revision.
157    ///
158    /// # Returns
159    ///
160    /// - `bool` - `true` if the revision changed and entries were invalidated.
161    pub fn invalidate_font_chain(&mut self, new_revision: u64) -> bool {
162        if self.get_font_chain_revision() == new_revision {
163            return false;
164        }
165        let Self {
166            font_chain_revision,
167            shaped_runs,
168            line_breaks,
169            resident_bytes,
170            ..
171        } = self;
172        *font_chain_revision = new_revision;
173        shaped_runs.clear();
174        line_breaks.clear();
175        *resident_bytes = 0;
176        true
177    }
178
179    /// Looks up or computes a DPI- and wrap-width-independent `ShapedGlyphRun` for `key`.
180    ///
181    /// # Arguments
182    ///
183    /// - `&Self` - Mutable shaping cache.
184    /// - `TextShapingKey` - Shaping lookup key.
185    /// - `F` - Lazy shaping function returning `(cluster_advances, total_width)` on a miss.
186    ///
187    /// # Returns
188    ///
189    /// - `&ShapedGlyphRun` - Cached shaping run reference.
190    pub fn get_or_shape<F>(&mut self, key: TextShapingKey, shape_fn: F) -> &ShapedGlyphRun
191    where
192        F: FnOnce() -> (Vec<f32>, f32),
193    {
194        let hit: bool = self.get_shaped_runs().contains_key(&key);
195        if hit {
196            let Self {
197                shaped_runs,
198                lru_clock,
199                shaping_hits,
200                ..
201            } = self;
202            *lru_clock = lru_clock.wrapping_add(1);
203            *shaping_hits = shaping_hits.saturating_add(1);
204            let tick: u64 = *lru_clock;
205            if let Some(entry) = shaped_runs.get_mut(&key) {
206                entry.set_last_used_tick(tick);
207            }
208            return &shaped_runs[&key];
209        }
210        let (advances, total_width): (Vec<f32>, f32) = shape_fn();
211        let cluster_count: usize = advances.len();
212        let entry_bytes: usize =
213            TEXT_SHAPING_ENTRY_OVERHEAD_BYTES.saturating_add(cluster_count.saturating_mul(4));
214        self.evict_to_make_room(entry_bytes);
215        let Self {
216            shaped_runs,
217            resident_bytes,
218            lru_clock,
219            shaping_misses,
220            ..
221        } = self;
222        *lru_clock = lru_clock.wrapping_add(1);
223        *shaping_misses = shaping_misses.saturating_add(1);
224        let run: ShapedGlyphRun = ShapedGlyphRun {
225            cluster_advances: advances,
226            total_width,
227            cluster_count,
228            byte_size: entry_bytes,
229            last_used_tick: *lru_clock,
230        };
231        let _: Option<ShapedGlyphRun> = shaped_runs.insert(key, run);
232        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
233        &shaped_runs[&key]
234    }
235
236    /// Looks up or computes a DPI- and color-independent wrapped `TextLayoutResult` for `key`.
237    ///
238    /// # Arguments
239    ///
240    /// - `&Self` - Mutable shaping cache.
241    /// - `LineBreakKey` - Line-break lookup key.
242    /// - `F` - Lazy line-break computation invoked only on cache miss.
243    ///
244    /// # Returns
245    ///
246    /// - `&TextLayoutResult` - Cached wrapped layout result.
247    pub fn get_or_break_lines<F>(&mut self, key: LineBreakKey, break_fn: F) -> &TextLayoutResult
248    where
249        F: FnOnce() -> TextLayoutResult,
250    {
251        let hit: bool = self.get_line_breaks().contains_key(&key);
252        if hit {
253            let Self {
254                line_breaks,
255                lru_clock,
256                line_break_hits,
257                ..
258            } = self;
259            *lru_clock = lru_clock.wrapping_add(1);
260            *line_break_hits = line_break_hits.saturating_add(1);
261            let tick: u64 = *lru_clock;
262            if let Some(entry) = line_breaks.get_mut(&key) {
263                entry.set_last_used_tick(tick);
264            }
265            return line_breaks[&key].get_layout();
266        }
267        let layout: TextLayoutResult = break_fn();
268        let mut entry_bytes: usize = TEXT_SHAPING_ENTRY_OVERHEAD_BYTES;
269        for line in layout.get_lines().iter() {
270            entry_bytes = entry_bytes
271                .saturating_add(32)
272                .saturating_add(line.get_text().len());
273        }
274        self.evict_to_make_room(entry_bytes);
275        let Self {
276            line_breaks,
277            resident_bytes,
278            lru_clock,
279            line_break_misses,
280            ..
281        } = self;
282        *lru_clock = lru_clock.wrapping_add(1);
283        *line_break_misses = line_break_misses.saturating_add(1);
284        let entry: CachedLineBreakEntry = CachedLineBreakEntry {
285            layout,
286            byte_size: entry_bytes,
287            last_used_tick: *lru_clock,
288        };
289        let _: Option<CachedLineBreakEntry> = line_breaks.insert(key, entry);
290        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
291        line_breaks[&key].get_layout()
292    }
293
294    /// Evicts coldest entries across shaping and line-break tables when `resident_bytes + incoming_bytes > budget_bytes`.
295    ///
296    /// # Arguments
297    ///
298    /// - `&Self` - Mutable shaping cache.
299    /// - `usize` - Size in bytes of the incoming entry.
300    fn evict_to_make_room(&mut self, incoming_bytes: usize) {
301        let budget: usize = self.get_budget_bytes();
302        if self.get_resident_bytes().saturating_add(incoming_bytes) <= budget {
303            return;
304        }
305        let target: usize = budget
306            .saturating_mul(3)
307            .saturating_div(4)
308            .saturating_sub(incoming_bytes);
309        self.evict_lru_to_target(target);
310    }
311
312    /// Evicts coldest entries whenever current resident bytes exceed the configured budget.
313    ///
314    /// # Arguments
315    ///
316    /// - `&Self` - Mutable shaping cache.
317    pub fn evict_if_over_budget(&mut self) {
318        let budget: usize = self.get_budget_bytes();
319        if self.get_resident_bytes() <= budget {
320            return;
321        }
322        let target: usize = (budget.saturating_mul(3) / 4).max(TEXT_SHAPING_ENTRY_OVERHEAD_BYTES);
323        self.evict_lru_to_target(target);
324    }
325
326    /// Evicts least-recently-used shaping and line-break entries until `resident_bytes <= target_bytes`.
327    ///
328    /// # Arguments
329    ///
330    /// - `&Self` - Mutable shaping cache.
331    /// - `usize` - Target post-eviction resident byte ceiling.
332    fn evict_lru_to_target(&mut self, target_bytes: usize) {
333        let Self {
334            shaped_runs,
335            line_breaks,
336            resident_bytes,
337            evictions,
338            ..
339        } = self;
340        let mut victims: Vec<ShapingEvictVictim> =
341            Vec::with_capacity(shaped_runs.len() + line_breaks.len());
342        for (k, v) in shaped_runs.iter() {
343            victims.push(ShapingEvictVictim {
344                last_used_tick: v.get_last_used_tick(),
345                is_shape: true,
346                shape_key: *k,
347                line_break_key: LineBreakKey::default(),
348                byte_size: v.get_byte_size(),
349            });
350        }
351        for (k, v) in line_breaks.iter() {
352            victims.push(ShapingEvictVictim {
353                last_used_tick: v.get_last_used_tick(),
354                is_shape: false,
355                shape_key: TextShapingKey::default(),
356                line_break_key: *k,
357                byte_size: v.get_byte_size(),
358            });
359        }
360        victims.sort_unstable_by_key(|item: &ShapingEvictVictim| item.last_used_tick);
361        for victim in victims.into_iter() {
362            if *resident_bytes <= target_bytes {
363                break;
364            }
365            if victim.is_shape {
366                if shaped_runs.remove(&victim.shape_key).is_some() {
367                    *resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
368                    *evictions = evictions.saturating_add(1);
369                }
370            } else if line_breaks.remove(&victim.line_break_key).is_some() {
371                *resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
372                *evictions = evictions.saturating_add(1);
373            }
374        }
375    }
376
377    /// Returns total cached entry count combining shaping runs and wrapped line-break entries.
378    ///
379    /// # Arguments
380    ///
381    /// - `&Self` - Shaping cache reference.
382    ///
383    /// # Returns
384    ///
385    /// - `usize` - Total cached entries.
386    #[must_use]
387    pub fn total_entries(&self) -> usize {
388        self.get_shaped_runs()
389            .len()
390            .saturating_add(self.get_line_breaks().len())
391    }
392}