Skip to main content

euv_core/font/shaping/
impl.rs

1use super::*;
2
3/// Construction and fast-hashing 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::from_prehashed(
51            text_hash_a,
52            text_hash_b,
53            text.len() as u32,
54            style,
55            locale_hash,
56            rtl,
57            font_chain_revision,
58        )
59    }
60
61    /// Builds a `TextShapingKey` from a single precomputed 64-bit `text_hash` without re-hashing text bytes.
62    ///
63    /// # Arguments
64    ///
65    /// - `u64` - Precomputed 64-bit text content hash (for example stored on a scene node).
66    /// - `u32` - UTF-8 byte length of the source text.
67    /// - `TextStyle` - Typography style parameters.
68    /// - `u64` - Precomputed locale hash.
69    /// - `bool` - Whether right-to-left base direction is enabled.
70    /// - `u64` - Active font fallback chain revision.
71    ///
72    /// # Returns
73    ///
74    /// - `Self` - Zero-rehash shaping cache key.
75    #[inline(always)]
76    #[must_use]
77    pub fn from_text_hash(
78        text_hash: u64,
79        text_len: u32,
80        style: TextStyle,
81        locale_hash: u64,
82        rtl: bool,
83        font_chain_revision: u64,
84    ) -> Self {
85        let text_hash_b: u64 =
86            text_hash.rotate_left(29).wrapping_mul(SHAPING_FX_MULT) ^ (text_len as u64);
87        Self::from_prehashed(
88            text_hash,
89            text_hash_b,
90            text_len,
91            style,
92            locale_hash,
93            rtl,
94            font_chain_revision,
95        )
96    }
97
98    /// Builds a `TextShapingKey` from precomputed 128-bit text hashes and precomputed locale hash.
99    ///
100    /// # Arguments
101    ///
102    /// - `u64` - Primary 64-bit text hash.
103    /// - `u64` - Secondary 64-bit text hash.
104    /// - `u32` - UTF-8 byte length of the source text.
105    /// - `TextStyle` - Typography style parameters.
106    /// - `u64` - Precomputed locale hash.
107    /// - `bool` - Whether right-to-left base direction is enabled.
108    /// - `u64` - Active font fallback chain revision.
109    ///
110    /// # Returns
111    ///
112    /// - `Self` - Constructed shaping cache key.
113    #[inline(always)]
114    #[must_use]
115    pub fn from_prehashed(
116        text_hash_a: u64,
117        text_hash_b: u64,
118        text_len: u32,
119        style: TextStyle,
120        locale_hash: u64,
121        rtl: bool,
122        font_chain_revision: u64,
123    ) -> Self {
124        Self {
125            text_hash_a,
126            text_hash_b,
127            text_len,
128            font_size_bits: style.get_font_size().to_bits(),
129            family: style.get_family(),
130            weight: style.get_weight(),
131            italic: style.get_italic(),
132            letter_spacing_bits: style.get_letter_spacing().to_bits(),
133            locale_hash,
134            rtl,
135            font_chain_revision,
136        }
137    }
138
139    /// Computes a single-pass FxHash digest of all fields for single-probe flat table lookup.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Shaping key reference.
144    ///
145    /// # Returns
146    ///
147    /// - `u64` - Mixed 64-bit avalanche hash.
148    #[inline(always)]
149    #[must_use]
150    pub fn fast_hash(&self) -> u64 {
151        let mut h: u64 = self.get_text_hash_a().wrapping_mul(SHAPING_FX_MULT);
152        h ^= self.get_text_hash_b();
153        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
154        let packed_size: u64 =
155            ((self.get_text_len() as u64) << 32) | (self.get_font_size_bits() as u64);
156        h ^= packed_size;
157        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
158        let packed_flags: u64 = ((self.get_letter_spacing_bits() as u64) << 32)
159            | ((self.get_family() as u64) << 16)
160            | ((self.get_weight() as u64) << 8)
161            | (u64::from(self.get_italic()) << 1)
162            | u64::from(self.get_rtl());
163        h ^= packed_flags;
164        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
165        h ^= self.get_locale_hash();
166        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
167        h ^= self.get_font_chain_revision();
168        let mixed: u64 = h.wrapping_mul(SHAPING_FX_MULT);
169        mixed ^ (mixed >> 32)
170    }
171
172    /// Builds a paired `LineBreakKey` binding this shaping key to `max_width`, `line_height`, and `overflow`.
173    ///
174    /// # Arguments
175    ///
176    /// - `&Self` - Base shaping key.
177    /// - `Option<f32>` - Optional logical wrap width limit.
178    /// - `TextStyle` - Typography style providing `line_height` and `overflow`.
179    ///
180    /// # Returns
181    ///
182    /// - `LineBreakKey` - Line-break cache key independent of DPI scale and text color.
183    #[must_use]
184    pub fn line_break_key(&self, max_width: Option<f32>, style: TextStyle) -> LineBreakKey {
185        let width_bits: u32 = match max_width {
186            Some(w) if w.is_finite() => ((w.max(0.0) * 10.0).round() as u32).min(u32::MAX - 1),
187            _ => u32::MAX,
188        };
189        let meta: u64 =
190            ((self.get_font_size_bits() as u64) << 32) | (self.get_letter_spacing_bits() as u64);
191        let flags: u64 = ((self.get_text_len() as u64) << 32)
192            | ((self.get_family() as u64) << 16)
193            | ((self.get_weight() as u64) << 8)
194            | (u64::from(self.get_italic()) << 1)
195            | u64::from(self.get_rtl());
196        let ha: u64 = (self.get_text_hash_a() ^ meta ^ flags).wrapping_mul(SHAPING_FNV_PRIME);
197        let hb: u64 = (self.get_text_hash_b() ^ self.get_locale_hash() ^ flags.rotate_left(17))
198            .wrapping_mul(SHAPING_FNV_PRIME);
199        LineBreakKey {
200            shaping_hash_a: ha,
201            shaping_hash_b: hb,
202            max_width_bits: width_bits,
203            line_height_bits: style.get_line_height().to_bits(),
204            overflow: style.get_overflow(),
205            font_chain_revision: self.get_font_chain_revision(),
206        }
207    }
208}
209
210/// Fast-hashing helpers for `LineBreakKey`.
211impl LineBreakKey {
212    /// Computes a single-pass FxHash digest of all fields for single-probe flat table lookup.
213    ///
214    /// # Arguments
215    ///
216    /// - `&Self` - Line-break key reference.
217    ///
218    /// # Returns
219    ///
220    /// - `u64` - Mixed 64-bit avalanche hash.
221    #[inline(always)]
222    #[must_use]
223    pub fn fast_hash(&self) -> u64 {
224        let mut h: u64 = self.get_shaping_hash_a().wrapping_mul(SHAPING_FX_MULT);
225        h ^= self.get_shaping_hash_b();
226        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
227        let packed_dims: u64 =
228            ((self.get_max_width_bits() as u64) << 32) | (self.get_line_height_bits() as u64);
229        h ^= packed_dims;
230        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
231        h ^= ((self.get_overflow() as u64) << 56) ^ self.get_font_chain_revision();
232        let mixed: u64 = h.wrapping_mul(SHAPING_FX_MULT);
233        mixed ^ (mixed >> 32)
234    }
235}
236
237/// Default bounded text shaping cache initialized with `TEXT_SHAPING_DEFAULT_BUDGET_BYTES`.
238impl Default for TextShapingCache {
239    /// Creates an empty bounded `TextShapingCache` with the default 4 MiB budget.
240    ///
241    /// # Returns
242    ///
243    /// - `Self` - Empty text shaping cache.
244    fn default() -> Self {
245        Self::with_budget(TEXT_SHAPING_DEFAULT_BUDGET_BYTES)
246    }
247}
248
249/// Single-probe FxHash shaping & line-break caching, independent font-chain invalidation, and O(1) intrusive LRU eviction for `TextShapingCache`.
250impl TextShapingCache {
251    /// Creates a zero-allocation empty `TextShapingCache` enforcing `budget_bytes` across shaping runs and wrapped line layouts.
252    ///
253    /// # Arguments
254    ///
255    /// - `usize` - Resident byte ceiling (clamped to `>= TEXT_SHAPING_MIN_BUDGET_BYTES`).
256    ///
257    /// # Returns
258    ///
259    /// - `Self` - Configured empty shaping cache.
260    #[must_use]
261    pub fn with_budget(budget_bytes: usize) -> Self {
262        Self {
263            budget_bytes: budget_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES),
264            resident_bytes: 0,
265            font_chain_revision: 1,
266            lru_clock: 0,
267            shape_index: Vec::new(),
268            line_break_index: Vec::new(),
269            shape_slots: Vec::new(),
270            line_break_slots: Vec::new(),
271            shape_free_slots: Vec::new(),
272            line_break_free_slots: Vec::new(),
273            lru_head: SHAPING_NODE_NONE,
274            lru_tail: SHAPING_NODE_NONE,
275            shape_count: 0,
276            line_break_count: 0,
277            shape_occupied: 0,
278            line_break_occupied: 0,
279            shaping_hits: 0,
280            shaping_misses: 0,
281            line_break_hits: 0,
282            line_break_misses: 0,
283            evictions: 0,
284        }
285    }
286
287    /// Packs a 31-bit hash fingerprint (bit 63 guaranteed 0) with a 32-bit arena slot index.
288    ///
289    /// # Arguments
290    ///
291    /// - `u64` - Full 64-bit FxHash of the entry key.
292    /// - `u32` - Slot index inside `shape_slots` or `line_break_slots`.
293    ///
294    /// # Returns
295    ///
296    /// - `u64` - Packed index entry never colliding with empty or tombstone sentinels.
297    #[inline(always)]
298    #[must_use]
299    fn pack_index_slot(hash: u64, slot_idx: u32) -> u64 {
300        ((hash >> 33) << 32) | (slot_idx as u64)
301    }
302
303    /// Extracts the 31-bit shifted tag stored in the upper half of a packed index entry.
304    ///
305    /// # Arguments
306    ///
307    /// - `u64` - Full 64-bit FxHash of the entry key.
308    ///
309    /// # Returns
310    ///
311    /// - `u64` - Shifted 31-bit tag ready for bitmask comparison.
312    #[inline(always)]
313    #[must_use]
314    fn hash_tag_shifted(hash: u64) -> u64 {
315        (hash >> 33) << 32
316    }
317
318    /// Probes the open-addressed `shape_index` table once for `key`, returning its `shape_slots` index on a hit.
319    ///
320    /// # Arguments
321    ///
322    /// - `&[u64]` - Open-addressed shaping index table.
323    /// - `&[ShapingRunSlot]` - Contiguous shaping slot arena.
324    /// - `&TextShapingKey` - Target shaping lookup key.
325    /// - `u64` - Precomputed `key.fast_hash()`.
326    ///
327    /// # Returns
328    ///
329    /// - `Option<u32>` - Matching slot index when resident.
330    #[inline(always)]
331    #[must_use]
332    fn probe_shape_slot(
333        index: &[u64],
334        slots: &[ShapingRunSlot],
335        key: &TextShapingKey,
336        hash: u64,
337    ) -> Option<u32> {
338        let cap: usize = index.len();
339        if cap == 0 {
340            return None;
341        }
342        let mask: usize = cap - 1;
343        let tag_shifted: u64 = Self::hash_tag_shifted(hash);
344        let mut idx: usize = (hash as usize) & mask;
345        loop {
346            let slot_val: u64 = index[idx];
347            if slot_val == SHAPING_INDEX_EMPTY {
348                return None;
349            }
350            if slot_val != SHAPING_INDEX_TOMBSTONE
351                && (slot_val & 0xFFFF_FFFF_0000_0000) == tag_shifted
352            {
353                let slot_idx: u32 = slot_val as u32;
354                let entry: &ShapingRunSlot = &slots[slot_idx as usize];
355                if entry.occupied && entry.key == *key {
356                    return Some(slot_idx);
357                }
358            }
359            idx = (idx + 1) & mask;
360        }
361    }
362
363    /// Probes the open-addressed `line_break_index` table once for `key`, returning its `line_break_slots` index on a hit.
364    ///
365    /// # Arguments
366    ///
367    /// - `&[u64]` - Open-addressed line-break index table.
368    /// - `&[LineBreakSlot]` - Contiguous line-break slot arena.
369    /// - `&LineBreakKey` - Target line-break lookup key.
370    /// - `u64` - Precomputed `key.fast_hash()`.
371    ///
372    /// # Returns
373    ///
374    /// - `Option<u32>` - Matching slot index when resident.
375    #[inline(always)]
376    #[must_use]
377    fn probe_line_break_slot(
378        index: &[u64],
379        slots: &[LineBreakSlot],
380        key: &LineBreakKey,
381        hash: u64,
382    ) -> Option<u32> {
383        let cap: usize = index.len();
384        if cap == 0 {
385            return None;
386        }
387        let mask: usize = cap - 1;
388        let tag_shifted: u64 = Self::hash_tag_shifted(hash);
389        let mut idx: usize = (hash as usize) & mask;
390        loop {
391            let slot_val: u64 = index[idx];
392            if slot_val == SHAPING_INDEX_EMPTY {
393                return None;
394            }
395            if slot_val != SHAPING_INDEX_TOMBSTONE
396                && (slot_val & 0xFFFF_FFFF_0000_0000) == tag_shifted
397            {
398                let slot_idx: u32 = slot_val as u32;
399                let entry: &LineBreakSlot = &slots[slot_idx as usize];
400                if entry.occupied && entry.key == *key {
401                    return Some(slot_idx);
402                }
403            }
404            idx = (idx + 1) & mask;
405        }
406    }
407
408    /// Inserts `(hash, slot_idx)` into `shape_index`, rehashing at 75% load (in-place when tombstones dominate).
409    ///
410    /// # Arguments
411    ///
412    /// - `&mut Vec<u64>` - Open-addressed shaping index table.
413    /// - `&mut usize` - Live plus tombstone slot counter.
414    /// - `usize` - Live shaping entry count.
415    /// - `&[ShapingRunSlot]` - Contiguous shaping slot arena used during rehash.
416    /// - `u64` - Precomputed key hash.
417    /// - `u32` - Arena slot index to insert.
418    fn insert_shape_index(
419        index: &mut Vec<u64>,
420        occupied: &mut usize,
421        live_count: usize,
422        slots: &[ShapingRunSlot],
423        hash: u64,
424        slot_idx: u32,
425    ) {
426        let cap: usize = index.len();
427        if cap == 0 {
428            index.resize(SHAPING_INDEX_INIT_CAP, SHAPING_INDEX_EMPTY);
429            *occupied = 0;
430        } else if (*occupied + 1) * 4 >= cap * 3 {
431            let next_cap: usize = if live_count * 2 < cap { cap } else { cap * 2 };
432            let next_mask: usize = next_cap - 1;
433            let mut rebuilt: Vec<u64> = vec![SHAPING_INDEX_EMPTY; next_cap];
434            let mut rebuilt_count: usize = 0;
435            for (i, slot) in slots.iter().enumerate() {
436                if !slot.occupied {
437                    continue;
438                }
439                let mut dst: usize = (slot.hash as usize) & next_mask;
440                while rebuilt[dst] != SHAPING_INDEX_EMPTY {
441                    dst = (dst + 1) & next_mask;
442                }
443                rebuilt[dst] = Self::pack_index_slot(slot.hash, i as u32);
444                rebuilt_count += 1;
445            }
446            *index = rebuilt;
447            *occupied = rebuilt_count;
448            return;
449        }
450        let mask: usize = index.len() - 1;
451        let mut idx: usize = (hash as usize) & mask;
452        loop {
453            let existing: u64 = index[idx];
454            if existing == SHAPING_INDEX_EMPTY {
455                index[idx] = Self::pack_index_slot(hash, slot_idx);
456                *occupied = occupied.saturating_add(1);
457                return;
458            }
459            if existing == SHAPING_INDEX_TOMBSTONE {
460                index[idx] = Self::pack_index_slot(hash, slot_idx);
461                return;
462            }
463            idx = (idx + 1) & mask;
464        }
465    }
466
467    /// Inserts `(hash, slot_idx)` into `line_break_index`, rehashing at 75% load (in-place when tombstones dominate).
468    ///
469    /// # Arguments
470    ///
471    /// - `&mut Vec<u64>` - Open-addressed line-break index table.
472    /// - `&mut usize` - Live plus tombstone slot counter.
473    /// - `usize` - Live line-break entry count.
474    /// - `&[LineBreakSlot]` - Contiguous line-break slot arena used during rehash.
475    /// - `u64` - Precomputed key hash.
476    /// - `u32` - Arena slot index to insert.
477    fn insert_line_break_index(
478        index: &mut Vec<u64>,
479        occupied: &mut usize,
480        live_count: usize,
481        slots: &[LineBreakSlot],
482        hash: u64,
483        slot_idx: u32,
484    ) {
485        let cap: usize = index.len();
486        if cap == 0 {
487            index.resize(SHAPING_INDEX_INIT_CAP, SHAPING_INDEX_EMPTY);
488            *occupied = 0;
489        } else if (*occupied + 1) * 4 >= cap * 3 {
490            let next_cap: usize = if live_count * 2 < cap { cap } else { cap * 2 };
491            let next_mask: usize = next_cap - 1;
492            let mut rebuilt: Vec<u64> = vec![SHAPING_INDEX_EMPTY; next_cap];
493            let mut rebuilt_count: usize = 0;
494            for (i, slot) in slots.iter().enumerate() {
495                if !slot.occupied {
496                    continue;
497                }
498                let mut dst: usize = (slot.hash as usize) & next_mask;
499                while rebuilt[dst] != SHAPING_INDEX_EMPTY {
500                    dst = (dst + 1) & next_mask;
501                }
502                rebuilt[dst] = Self::pack_index_slot(slot.hash, i as u32);
503                rebuilt_count += 1;
504            }
505            *index = rebuilt;
506            *occupied = rebuilt_count;
507            return;
508        }
509        let mask: usize = index.len() - 1;
510        let mut idx: usize = (hash as usize) & mask;
511        loop {
512            let existing: u64 = index[idx];
513            if existing == SHAPING_INDEX_EMPTY {
514                index[idx] = Self::pack_index_slot(hash, slot_idx);
515                *occupied = occupied.saturating_add(1);
516                return;
517            }
518            if existing == SHAPING_INDEX_TOMBSTONE {
519                index[idx] = Self::pack_index_slot(hash, slot_idx);
520                return;
521            }
522            idx = (idx + 1) & mask;
523        }
524    }
525
526    /// Marks the open-addressed slot pointing to `slot_idx` as a tombstone in O(1) expected time.
527    ///
528    /// # Arguments
529    ///
530    /// - `&mut [u64]` - Open-addressed index table containing `slot_idx`.
531    /// - `u64` - Stored FxHash of the evicted entry.
532    /// - `u32` - Arena slot index to tomb-mark.
533    #[inline]
534    fn remove_index_entry(index: &mut [u64], hash: u64, slot_idx: u32) {
535        let cap: usize = index.len();
536        if cap == 0 {
537            return;
538        }
539        let mask: usize = cap - 1;
540        let expected: u64 = Self::pack_index_slot(hash, slot_idx);
541        let mut idx: usize = (hash as usize) & mask;
542        loop {
543            let existing: u64 = index[idx];
544            if existing == SHAPING_INDEX_EMPTY {
545                return;
546            }
547            if existing == expected {
548                index[idx] = SHAPING_INDEX_TOMBSTONE;
549                return;
550            }
551            idx = (idx + 1) & mask;
552        }
553    }
554
555    /// Reads the `(prev, next)` intrusive LRU links of a tagged node handle.
556    ///
557    /// # Arguments
558    ///
559    /// - `&[ShapingRunSlot]` - Shaping slot arena.
560    /// - `&[LineBreakSlot]` - Line-break slot arena.
561    /// - `u32` - Tagged LRU node handle.
562    ///
563    /// # Returns
564    ///
565    /// - `(u32, u32)` - Pair `(prev_handle, next_handle)`.
566    #[inline(always)]
567    #[must_use]
568    fn lru_links(
569        shape_slots: &[ShapingRunSlot],
570        line_break_slots: &[LineBreakSlot],
571        handle: u32,
572    ) -> (u32, u32) {
573        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
574        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
575            (line_break_slots[idx].prev, line_break_slots[idx].next)
576        } else {
577            (shape_slots[idx].prev, shape_slots[idx].next)
578        }
579    }
580
581    /// Updates the `prev` link of a tagged node handle in O(1).
582    ///
583    /// # Arguments
584    ///
585    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
586    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
587    /// - `u32` - Tagged LRU node handle.
588    /// - `u32` - New previous neighbor handle.
589    #[inline(always)]
590    fn set_lru_prev(
591        shape_slots: &mut [ShapingRunSlot],
592        line_break_slots: &mut [LineBreakSlot],
593        handle: u32,
594        prev: u32,
595    ) {
596        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
597        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
598            line_break_slots[idx].prev = prev;
599        } else {
600            shape_slots[idx].prev = prev;
601        }
602    }
603
604    /// Updates the `next` link of a tagged node handle in O(1).
605    ///
606    /// # Arguments
607    ///
608    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
609    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
610    /// - `u32` - Tagged LRU node handle.
611    /// - `u32` - New next neighbor handle.
612    #[inline(always)]
613    fn set_lru_next(
614        shape_slots: &mut [ShapingRunSlot],
615        line_break_slots: &mut [LineBreakSlot],
616        handle: u32,
617        next: u32,
618    ) {
619        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
620        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
621            line_break_slots[idx].next = next;
622        } else {
623            shape_slots[idx].next = next;
624        }
625    }
626
627    /// Promotes an already-linked tagged node handle to the MRU head in O(1).
628    ///
629    /// # Arguments
630    ///
631    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
632    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
633    /// - `&mut u32` - Head handle pointer.
634    /// - `&mut u32` - Tail handle pointer.
635    /// - `u32` - Tagged node handle to move to front.
636    #[inline(always)]
637    fn lru_move_to_front(
638        shape_slots: &mut [ShapingRunSlot],
639        line_break_slots: &mut [LineBreakSlot],
640        lru_head: &mut u32,
641        lru_tail: &mut u32,
642        handle: u32,
643    ) {
644        if *lru_head == handle {
645            return;
646        }
647        let (prev, next): (u32, u32) = Self::lru_links(shape_slots, line_break_slots, handle);
648        if prev != SHAPING_NODE_NONE {
649            Self::set_lru_next(shape_slots, line_break_slots, prev, next);
650        }
651        if next != SHAPING_NODE_NONE {
652            Self::set_lru_prev(shape_slots, line_break_slots, next, prev);
653        } else {
654            *lru_tail = prev;
655        }
656        let old_head: u32 = *lru_head;
657        Self::set_lru_prev(shape_slots, line_break_slots, handle, SHAPING_NODE_NONE);
658        Self::set_lru_next(shape_slots, line_break_slots, handle, old_head);
659        if old_head != SHAPING_NODE_NONE {
660            Self::set_lru_prev(shape_slots, line_break_slots, old_head, handle);
661        } else {
662            *lru_tail = handle;
663        }
664        *lru_head = handle;
665    }
666
667    /// Links a newly inserted tagged node handle at the MRU head in O(1).
668    ///
669    /// # Arguments
670    ///
671    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
672    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
673    /// - `&mut u32` - Head handle pointer.
674    /// - `&mut u32` - Tail handle pointer.
675    /// - `u32` - Newly inserted tagged node handle.
676    #[inline(always)]
677    fn lru_push_front(
678        shape_slots: &mut [ShapingRunSlot],
679        line_break_slots: &mut [LineBreakSlot],
680        lru_head: &mut u32,
681        lru_tail: &mut u32,
682        handle: u32,
683    ) {
684        let old_head: u32 = *lru_head;
685        Self::set_lru_prev(shape_slots, line_break_slots, handle, SHAPING_NODE_NONE);
686        Self::set_lru_next(shape_slots, line_break_slots, handle, old_head);
687        if old_head != SHAPING_NODE_NONE {
688            Self::set_lru_prev(shape_slots, line_break_slots, old_head, handle);
689        } else {
690            *lru_tail = handle;
691        }
692        *lru_head = handle;
693    }
694
695    /// Updates the resident byte budget and immediately evicts cold entries if currently over budget.
696    ///
697    /// # Arguments
698    ///
699    /// - `&Self` - Mutable shaping cache.
700    /// - `usize` - New maximum resident bytes.
701    pub fn set_memory_budget(&mut self, max_bytes: usize) {
702        self.set_budget_bytes(max_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES));
703        self.evict_if_over_budget();
704    }
705
706    /// Advances the font fallback chain revision and invalidates all cached shaping and line-break entries.
707    ///
708    /// # Arguments
709    ///
710    /// - `&Self` - Mutable shaping cache.
711    /// - `u64` - New monotonic font fallback chain revision.
712    ///
713    /// # Returns
714    ///
715    /// - `bool` - `true` if the revision changed and entries were invalidated.
716    pub fn invalidate_font_chain(&mut self, new_revision: u64) -> bool {
717        if self.get_font_chain_revision() == new_revision {
718            return false;
719        }
720        let Self {
721            font_chain_revision,
722            shape_index,
723            line_break_index,
724            shape_slots,
725            line_break_slots,
726            shape_free_slots,
727            line_break_free_slots,
728            lru_head,
729            lru_tail,
730            shape_count,
731            line_break_count,
732            shape_occupied,
733            line_break_occupied,
734            resident_bytes,
735            ..
736        } = self;
737        *font_chain_revision = new_revision;
738        shape_index.fill(SHAPING_INDEX_EMPTY);
739        line_break_index.fill(SHAPING_INDEX_EMPTY);
740        shape_slots.clear();
741        line_break_slots.clear();
742        shape_free_slots.clear();
743        line_break_free_slots.clear();
744        *lru_head = SHAPING_NODE_NONE;
745        *lru_tail = SHAPING_NODE_NONE;
746        *shape_count = 0;
747        *line_break_count = 0;
748        *shape_occupied = 0;
749        *line_break_occupied = 0;
750        *resident_bytes = 0;
751        true
752    }
753
754    /// Performs a read-only single-probe zero-mutation lookup of a cached `ShapedGlyphRun`.
755    ///
756    /// # Arguments
757    ///
758    /// - `&Self` - Shaping cache reference.
759    /// - `&TextShapingKey` - Shaping lookup key.
760    ///
761    /// # Returns
762    ///
763    /// - `Option<&ShapedGlyphRun>` - Cached shaping run when resident.
764    #[inline]
765    #[must_use]
766    pub fn peek_shaped(&self, key: &TextShapingKey) -> Option<&ShapedGlyphRun> {
767        let Self {
768            shape_index,
769            shape_slots,
770            ..
771        } = self;
772        let hash: u64 = key.fast_hash();
773        let slot: u32 = Self::probe_shape_slot(shape_index, shape_slots, key, hash)?;
774        Some(&shape_slots[slot as usize].run)
775    }
776
777    /// Performs a read-only single-probe zero-mutation lookup of a cached wrapped `TextLayoutResult`.
778    ///
779    /// # Arguments
780    ///
781    /// - `&Self` - Shaping cache reference.
782    /// - `&LineBreakKey` - Line-break lookup key.
783    ///
784    /// # Returns
785    ///
786    /// - `Option<&TextLayoutResult>` - Cached wrapped layout result when resident.
787    #[inline]
788    #[must_use]
789    pub fn peek_line_break(&self, key: &LineBreakKey) -> Option<&TextLayoutResult> {
790        let Self {
791            line_break_index,
792            line_break_slots,
793            ..
794        } = self;
795        let hash: u64 = key.fast_hash();
796        let slot: u32 = Self::probe_line_break_slot(line_break_index, line_break_slots, key, hash)?;
797        Some(&line_break_slots[slot as usize].layout)
798    }
799
800    /// Looks up or computes a DPI- and wrap-width-independent `ShapedGlyphRun` for `key` with a single FxHash probe.
801    ///
802    /// # Arguments
803    ///
804    /// - `&Self` - Mutable shaping cache.
805    /// - `TextShapingKey` - Shaping lookup key.
806    /// - `F` - Lazy shaping function returning `(cluster_advances, total_width)` on a miss.
807    ///
808    /// # Returns
809    ///
810    /// - `&ShapedGlyphRun` - Cached shaping run reference.
811    pub fn get_or_shape<F>(&mut self, key: TextShapingKey, shape_fn: F) -> &ShapedGlyphRun
812    where
813        F: FnOnce() -> (Vec<f32>, f32),
814    {
815        let hash: u64 = key.fast_hash();
816        let hit_slot: Option<u32> = {
817            let Self {
818                shape_index,
819                shape_slots,
820                ..
821            } = self;
822            Self::probe_shape_slot(shape_index, shape_slots, &key, hash)
823        };
824        if let Some(slot) = hit_slot {
825            let Self {
826                shape_slots,
827                line_break_slots,
828                lru_head,
829                lru_tail,
830                lru_clock,
831                shaping_hits,
832                ..
833            } = self;
834            *lru_clock = lru_clock.wrapping_add(1);
835            *shaping_hits = shaping_hits.saturating_add(1);
836            let tick: u64 = *lru_clock;
837            Self::lru_move_to_front(shape_slots, line_break_slots, lru_head, lru_tail, slot);
838            let entry: &mut ShapingRunSlot = &mut shape_slots[slot as usize];
839            entry.run.set_last_used_tick(tick);
840            return &entry.run;
841        }
842        let (advances, total_width): (Vec<f32>, f32) = shape_fn();
843        let cluster_count: usize = advances.len();
844        let entry_bytes: usize =
845            TEXT_SHAPING_ENTRY_OVERHEAD_BYTES.saturating_add(cluster_count.saturating_mul(4));
846        self.evict_to_make_room(entry_bytes);
847        let Self {
848            shape_index,
849            shape_slots,
850            line_break_slots,
851            shape_free_slots,
852            lru_head,
853            lru_tail,
854            shape_count,
855            shape_occupied,
856            resident_bytes,
857            lru_clock,
858            shaping_misses,
859            ..
860        } = self;
861        *lru_clock = lru_clock.wrapping_add(1);
862        *shaping_misses = shaping_misses.saturating_add(1);
863        let run: ShapedGlyphRun = ShapedGlyphRun {
864            cluster_advances: advances,
865            total_width,
866            cluster_count,
867            byte_size: entry_bytes,
868            last_used_tick: *lru_clock,
869        };
870        let slot_val: ShapingRunSlot = ShapingRunSlot {
871            occupied: true,
872            hash,
873            key,
874            run,
875            prev: SHAPING_NODE_NONE,
876            next: SHAPING_NODE_NONE,
877        };
878        let slot: u32 = if let Some(reused) = shape_free_slots.pop() {
879            shape_slots[reused as usize] = slot_val;
880            reused
881        } else {
882            let next_idx: u32 = shape_slots.len() as u32;
883            shape_slots.push(slot_val);
884            next_idx
885        };
886        Self::lru_push_front(shape_slots, line_break_slots, lru_head, lru_tail, slot);
887        *shape_count = shape_count.saturating_add(1);
888        Self::insert_shape_index(
889            shape_index,
890            shape_occupied,
891            *shape_count,
892            shape_slots,
893            hash,
894            slot,
895        );
896        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
897        &shape_slots[slot as usize].run
898    }
899
900    /// Looks up or computes a DPI- and color-independent wrapped `TextLayoutResult` for `key` with a single FxHash probe.
901    ///
902    /// # Arguments
903    ///
904    /// - `&Self` - Mutable shaping cache.
905    /// - `LineBreakKey` - Line-break lookup key.
906    /// - `F` - Lazy line-break computation invoked only on cache miss.
907    ///
908    /// # Returns
909    ///
910    /// - `&TextLayoutResult` - Cached wrapped layout result.
911    pub fn get_or_break_lines<F>(&mut self, key: LineBreakKey, break_fn: F) -> &TextLayoutResult
912    where
913        F: FnOnce() -> TextLayoutResult,
914    {
915        let hash: u64 = key.fast_hash();
916        let hit_slot: Option<u32> = {
917            let Self {
918                line_break_index,
919                line_break_slots,
920                ..
921            } = self;
922            Self::probe_line_break_slot(line_break_index, line_break_slots, &key, hash)
923        };
924        if let Some(slot) = hit_slot {
925            let Self {
926                shape_slots,
927                line_break_slots,
928                lru_head,
929                lru_tail,
930                lru_clock,
931                line_break_hits,
932                ..
933            } = self;
934            *lru_clock = lru_clock.wrapping_add(1);
935            *line_break_hits = line_break_hits.saturating_add(1);
936            let handle: u32 = slot | SHAPING_LRU_LINE_BREAK_BIT;
937            Self::lru_move_to_front(shape_slots, line_break_slots, lru_head, lru_tail, handle);
938            return &line_break_slots[slot as usize].layout;
939        }
940        let layout: TextLayoutResult = break_fn();
941        let mut entry_bytes: usize = TEXT_SHAPING_ENTRY_OVERHEAD_BYTES;
942        for line in layout.get_lines().iter() {
943            entry_bytes = entry_bytes
944                .saturating_add(32)
945                .saturating_add(line.get_text().len());
946        }
947        self.evict_to_make_room(entry_bytes);
948        let Self {
949            line_break_index,
950            shape_slots,
951            line_break_slots,
952            line_break_free_slots,
953            lru_head,
954            lru_tail,
955            line_break_count,
956            line_break_occupied,
957            resident_bytes,
958            lru_clock,
959            line_break_misses,
960            ..
961        } = self;
962        *lru_clock = lru_clock.wrapping_add(1);
963        *line_break_misses = line_break_misses.saturating_add(1);
964        let slot_val: LineBreakSlot = LineBreakSlot {
965            occupied: true,
966            hash,
967            byte_size: entry_bytes,
968            key,
969            layout,
970            prev: SHAPING_NODE_NONE,
971            next: SHAPING_NODE_NONE,
972        };
973        let slot: u32 = if let Some(reused) = line_break_free_slots.pop() {
974            line_break_slots[reused as usize] = slot_val;
975            reused
976        } else {
977            let next_idx: u32 = line_break_slots.len() as u32;
978            line_break_slots.push(slot_val);
979            next_idx
980        };
981        let handle: u32 = slot | SHAPING_LRU_LINE_BREAK_BIT;
982        Self::lru_push_front(shape_slots, line_break_slots, lru_head, lru_tail, handle);
983        *line_break_count = line_break_count.saturating_add(1);
984        Self::insert_line_break_index(
985            line_break_index,
986            line_break_occupied,
987            *line_break_count,
988            line_break_slots,
989            hash,
990            slot,
991        );
992        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
993        &line_break_slots[slot as usize].layout
994    }
995
996    /// Evicts coldest entries across shaping and line-break tables when `resident_bytes + incoming_bytes > budget_bytes`.
997    ///
998    /// # Arguments
999    ///
1000    /// - `&Self` - Mutable shaping cache.
1001    /// - `usize` - Size in bytes of the incoming entry.
1002    fn evict_to_make_room(&mut self, incoming_bytes: usize) {
1003        let budget: usize = self.get_budget_bytes();
1004        if self.get_resident_bytes().saturating_add(incoming_bytes) <= budget {
1005            return;
1006        }
1007        let target: usize = budget
1008            .saturating_mul(3)
1009            .saturating_div(4)
1010            .saturating_sub(incoming_bytes);
1011        self.evict_lru_to_target(target);
1012    }
1013
1014    /// Evicts coldest entries whenever current resident bytes exceed the configured budget.
1015    ///
1016    /// # Arguments
1017    ///
1018    /// - `&Self` - Mutable shaping cache.
1019    pub fn evict_if_over_budget(&mut self) {
1020        let budget: usize = self.get_budget_bytes();
1021        if self.get_resident_bytes() <= budget {
1022            return;
1023        }
1024        let target: usize = (budget.saturating_mul(3) / 4).max(TEXT_SHAPING_ENTRY_OVERHEAD_BYTES);
1025        self.evict_lru_to_target(target);
1026    }
1027
1028    /// Evicts least-recently-used entries from `lru_tail` in strict O(1) per victim with zero heap allocations.
1029    ///
1030    /// # Arguments
1031    ///
1032    /// - `&Self` - Mutable shaping cache.
1033    /// - `usize` - Target post-eviction resident byte ceiling.
1034    fn evict_lru_to_target(&mut self, target_bytes: usize) {
1035        let Self {
1036            shape_index,
1037            line_break_index,
1038            shape_slots,
1039            line_break_slots,
1040            shape_free_slots,
1041            line_break_free_slots,
1042            lru_head,
1043            lru_tail,
1044            shape_count,
1045            line_break_count,
1046            resident_bytes,
1047            evictions,
1048            ..
1049        } = self;
1050        while *resident_bytes > target_bytes && *lru_tail != SHAPING_NODE_NONE {
1051            let victim: u32 = *lru_tail;
1052            let (prev, _): (u32, u32) = Self::lru_links(shape_slots, line_break_slots, victim);
1053            *lru_tail = prev;
1054            if prev != SHAPING_NODE_NONE {
1055                Self::set_lru_next(shape_slots, line_break_slots, prev, SHAPING_NODE_NONE);
1056            } else {
1057                *lru_head = SHAPING_NODE_NONE;
1058            }
1059            let slot_idx: u32 = victim & SHAPING_LRU_INDEX_MASK;
1060            if (victim & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
1061                let slot: &mut LineBreakSlot = &mut line_break_slots[slot_idx as usize];
1062                if slot.occupied {
1063                    let victim_hash: u64 = slot.hash;
1064                    let victim_bytes: usize = slot.byte_size;
1065                    slot.occupied = false;
1066                    slot.byte_size = 0;
1067                    slot.prev = SHAPING_NODE_NONE;
1068                    slot.next = SHAPING_NODE_NONE;
1069                    slot.layout = TextLayoutResult::default();
1070                    Self::remove_index_entry(line_break_index, victim_hash, slot_idx);
1071                    *line_break_count = line_break_count.saturating_sub(1);
1072                    *resident_bytes = resident_bytes.saturating_sub(victim_bytes);
1073                    *evictions = evictions.saturating_add(1);
1074                    line_break_free_slots.push(slot_idx);
1075                }
1076            } else {
1077                let slot: &mut ShapingRunSlot = &mut shape_slots[slot_idx as usize];
1078                if slot.occupied {
1079                    let victim_hash: u64 = slot.hash;
1080                    let victim_bytes: usize = slot.run.get_byte_size();
1081                    slot.occupied = false;
1082                    slot.prev = SHAPING_NODE_NONE;
1083                    slot.next = SHAPING_NODE_NONE;
1084                    slot.run = ShapedGlyphRun::default();
1085                    Self::remove_index_entry(shape_index, victim_hash, slot_idx);
1086                    *shape_count = shape_count.saturating_sub(1);
1087                    *resident_bytes = resident_bytes.saturating_sub(victim_bytes);
1088                    *evictions = evictions.saturating_add(1);
1089                    shape_free_slots.push(slot_idx);
1090                }
1091            }
1092        }
1093    }
1094
1095    /// Returns total cached entry count combining shaping runs and wrapped line-break entries.
1096    ///
1097    /// # Arguments
1098    ///
1099    /// - `&Self` - Shaping cache reference.
1100    ///
1101    /// # Returns
1102    ///
1103    /// - `usize` - Total cached entries.
1104    #[must_use]
1105    pub fn total_entries(&self) -> usize {
1106        let Self {
1107            shape_count,
1108            line_break_count,
1109            ..
1110        } = self;
1111        shape_count.saturating_add(*line_break_count)
1112    }
1113}