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