euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
use super::*;

/// Construction and fast-hashing helpers for `TextShapingKey`.
impl TextShapingKey {
    /// Computes dual 64-bit FNV-1a hashes over `bytes` to form a 128-bit collision-resistant digest.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input UTF-8 byte slice.
    ///
    /// # Returns
    ///
    /// - `(u64, u64)` - Dual 64-bit hash pair `(hash_a, hash_b)`.
    #[must_use]
    pub fn hash_bytes_128(bytes: &[u8]) -> (u64, u64) {
        let mut ha: u64 = SHAPING_FNV_OFFSET_A;
        let mut hb: u64 = SHAPING_FNV_OFFSET_B;
        for (idx, &b) in bytes.iter().enumerate() {
            ha ^= b as u64;
            ha = ha.wrapping_mul(SHAPING_FNV_PRIME);
            hb ^= (b as u64).wrapping_add((idx as u64).wrapping_mul(31));
            hb = hb.wrapping_mul(SHAPING_FNV_PRIME);
        }
        (ha, hb)
    }

    /// Builds a DPI- and wrap-width-independent `TextShapingKey` from `text`, `style`, locale, direction, and font-chain revision.
    ///
    /// # Arguments
    ///
    /// - `&str` - Source UTF-8 text content.
    /// - `TextStyle` - Typography style (color, alignment, and overflow are intentionally excluded).
    /// - `&str` - Active BCP-47 locale identifier.
    /// - `bool` - Whether right-to-left base direction is enabled.
    /// - `u64` - Active font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed shaping cache key.
    #[must_use]
    pub fn from_text(
        text: &str,
        style: TextStyle,
        locale: &str,
        rtl: bool,
        font_chain_revision: u64,
    ) -> Self {
        let (text_hash_a, text_hash_b): (u64, u64) = Self::hash_bytes_128(text.as_bytes());
        let (locale_hash, _): (u64, u64) = Self::hash_bytes_128(locale.as_bytes());
        Self::from_prehashed(
            text_hash_a,
            text_hash_b,
            text.len() as u32,
            style,
            locale_hash,
            rtl,
            font_chain_revision,
        )
    }

    /// Builds a `TextShapingKey` from a single precomputed 64-bit `text_hash` without re-hashing text bytes.
    ///
    /// # Arguments
    ///
    /// - `u64` - Precomputed 64-bit text content hash (for example stored on a scene node).
    /// - `u32` - UTF-8 byte length of the source text.
    /// - `TextStyle` - Typography style parameters.
    /// - `u64` - Precomputed locale hash.
    /// - `bool` - Whether right-to-left base direction is enabled.
    /// - `u64` - Active font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `Self` - Zero-rehash shaping cache key.
    #[inline(always)]
    #[must_use]
    pub fn from_text_hash(
        text_hash: u64,
        text_len: u32,
        style: TextStyle,
        locale_hash: u64,
        rtl: bool,
        font_chain_revision: u64,
    ) -> Self {
        let text_hash_b: u64 =
            text_hash.rotate_left(29).wrapping_mul(SHAPING_FX_MULT) ^ (text_len as u64);
        Self::from_prehashed(
            text_hash,
            text_hash_b,
            text_len,
            style,
            locale_hash,
            rtl,
            font_chain_revision,
        )
    }

    /// Builds a `TextShapingKey` from precomputed 128-bit text hashes and precomputed locale hash.
    ///
    /// # Arguments
    ///
    /// - `u64` - Primary 64-bit text hash.
    /// - `u64` - Secondary 64-bit text hash.
    /// - `u32` - UTF-8 byte length of the source text.
    /// - `TextStyle` - Typography style parameters.
    /// - `u64` - Precomputed locale hash.
    /// - `bool` - Whether right-to-left base direction is enabled.
    /// - `u64` - Active font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed shaping cache key.
    #[inline(always)]
    #[must_use]
    pub fn from_prehashed(
        text_hash_a: u64,
        text_hash_b: u64,
        text_len: u32,
        style: TextStyle,
        locale_hash: u64,
        rtl: bool,
        font_chain_revision: u64,
    ) -> Self {
        Self {
            text_hash_a,
            text_hash_b,
            text_len,
            font_size_bits: style.get_font_size().to_bits(),
            family: style.get_family(),
            weight: style.get_weight(),
            italic: style.get_italic(),
            letter_spacing_bits: style.get_letter_spacing().to_bits(),
            locale_hash,
            rtl,
            font_chain_revision,
        }
    }

    /// Computes a single-pass FxHash digest of all fields for single-probe flat table lookup.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shaping key reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Mixed 64-bit avalanche hash.
    #[inline(always)]
    #[must_use]
    pub fn fast_hash(&self) -> u64 {
        let mut h: u64 = self.get_text_hash_a().wrapping_mul(SHAPING_FX_MULT);
        h ^= self.get_text_hash_b();
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        let packed_size: u64 =
            ((self.get_text_len() as u64) << 32) | (self.get_font_size_bits() as u64);
        h ^= packed_size;
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        let packed_flags: u64 = ((self.get_letter_spacing_bits() as u64) << 32)
            | ((self.get_family() as u64) << 16)
            | ((self.get_weight() as u64) << 8)
            | (u64::from(self.get_italic()) << 1)
            | u64::from(self.get_rtl());
        h ^= packed_flags;
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        h ^= self.get_locale_hash();
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        h ^= self.get_font_chain_revision();
        let mixed: u64 = h.wrapping_mul(SHAPING_FX_MULT);
        mixed ^ (mixed >> 32)
    }

    /// Builds a paired `LineBreakKey` binding this shaping key to `max_width`, `line_height`, and `overflow`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Base shaping key.
    /// - `Option<f32>` - Optional logical wrap width limit.
    /// - `TextStyle` - Typography style providing `line_height` and `overflow`.
    ///
    /// # Returns
    ///
    /// - `LineBreakKey` - Line-break cache key independent of DPI scale and text color.
    #[must_use]
    pub fn line_break_key(&self, max_width: Option<f32>, style: TextStyle) -> LineBreakKey {
        let width_bits: u32 = match max_width {
            Some(w) if w.is_finite() => ((w.max(0.0) * 10.0).round() as u32).min(u32::MAX - 1),
            _ => u32::MAX,
        };
        let meta: u64 =
            ((self.get_font_size_bits() as u64) << 32) | (self.get_letter_spacing_bits() as u64);
        let flags: u64 = ((self.get_text_len() as u64) << 32)
            | ((self.get_family() as u64) << 16)
            | ((self.get_weight() as u64) << 8)
            | (u64::from(self.get_italic()) << 1)
            | u64::from(self.get_rtl());
        let ha: u64 = (self.get_text_hash_a() ^ meta ^ flags).wrapping_mul(SHAPING_FNV_PRIME);
        let hb: u64 = (self.get_text_hash_b() ^ self.get_locale_hash() ^ flags.rotate_left(17))
            .wrapping_mul(SHAPING_FNV_PRIME);
        LineBreakKey {
            shaping_hash_a: ha,
            shaping_hash_b: hb,
            max_width_bits: width_bits,
            line_height_bits: style.get_line_height().to_bits(),
            overflow: style.get_overflow(),
            font_chain_revision: self.get_font_chain_revision(),
        }
    }
}

/// Fast-hashing helpers for `LineBreakKey`.
impl LineBreakKey {
    /// Computes a single-pass FxHash digest of all fields for single-probe flat table lookup.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Line-break key reference.
    ///
    /// # Returns
    ///
    /// - `u64` - Mixed 64-bit avalanche hash.
    #[inline(always)]
    #[must_use]
    pub fn fast_hash(&self) -> u64 {
        let mut h: u64 = self.get_shaping_hash_a().wrapping_mul(SHAPING_FX_MULT);
        h ^= self.get_shaping_hash_b();
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        let packed_dims: u64 =
            ((self.get_max_width_bits() as u64) << 32) | (self.get_line_height_bits() as u64);
        h ^= packed_dims;
        h = h.rotate_left(5).wrapping_mul(SHAPING_FX_MULT);
        h ^= ((self.get_overflow() as u64) << 56) ^ self.get_font_chain_revision();
        let mixed: u64 = h.wrapping_mul(SHAPING_FX_MULT);
        mixed ^ (mixed >> 32)
    }
}

/// Default bounded text shaping cache initialized with `TEXT_SHAPING_DEFAULT_BUDGET_BYTES`.
impl Default for TextShapingCache {
    /// Creates an empty bounded `TextShapingCache` with the default 4 MiB budget.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty text shaping cache.
    fn default() -> Self {
        Self::with_budget(TEXT_SHAPING_DEFAULT_BUDGET_BYTES)
    }
}

/// Single-probe FxHash shaping & line-break caching, independent font-chain invalidation, and O(1) intrusive LRU eviction for `TextShapingCache`.
impl TextShapingCache {
    /// Creates a zero-allocation empty `TextShapingCache` enforcing `budget_bytes` across shaping runs and wrapped line layouts.
    ///
    /// # Arguments
    ///
    /// - `usize` - Resident byte ceiling (clamped to `>= TEXT_SHAPING_MIN_BUDGET_BYTES`).
    ///
    /// # Returns
    ///
    /// - `Self` - Configured empty shaping cache.
    #[must_use]
    pub fn with_budget(budget_bytes: usize) -> Self {
        Self {
            budget_bytes: budget_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES),
            resident_bytes: 0,
            font_chain_revision: 1,
            lru_clock: 0,
            shape_index: Vec::new(),
            line_break_index: Vec::new(),
            shape_slots: Vec::new(),
            line_break_slots: Vec::new(),
            shape_free_slots: Vec::new(),
            line_break_free_slots: Vec::new(),
            lru_head: SHAPING_NODE_NONE,
            lru_tail: SHAPING_NODE_NONE,
            shape_count: 0,
            line_break_count: 0,
            shape_occupied: 0,
            line_break_occupied: 0,
            shaping_hits: 0,
            shaping_misses: 0,
            line_break_hits: 0,
            line_break_misses: 0,
            evictions: 0,
        }
    }

    /// Packs a 31-bit hash fingerprint (bit 63 guaranteed 0) with a 32-bit arena slot index.
    ///
    /// # Arguments
    ///
    /// - `u64` - Full 64-bit FxHash of the entry key.
    /// - `u32` - Slot index inside `shape_slots` or `line_break_slots`.
    ///
    /// # Returns
    ///
    /// - `u64` - Packed index entry never colliding with empty or tombstone sentinels.
    #[inline(always)]
    #[must_use]
    fn pack_index_slot(hash: u64, slot_idx: u32) -> u64 {
        ((hash >> 33) << 32) | (slot_idx as u64)
    }

    /// Extracts the 31-bit shifted tag stored in the upper half of a packed index entry.
    ///
    /// # Arguments
    ///
    /// - `u64` - Full 64-bit FxHash of the entry key.
    ///
    /// # Returns
    ///
    /// - `u64` - Shifted 31-bit tag ready for bitmask comparison.
    #[inline(always)]
    #[must_use]
    fn hash_tag_shifted(hash: u64) -> u64 {
        (hash >> 33) << 32
    }

    /// Probes the open-addressed `shape_index` table once for `key`, returning its `shape_slots` index on a hit.
    ///
    /// # Arguments
    ///
    /// - `&[u64]` - Open-addressed shaping index table.
    /// - `&[ShapingRunSlot]` - Contiguous shaping slot arena.
    /// - `&TextShapingKey` - Target shaping lookup key.
    /// - `u64` - Precomputed `key.fast_hash()`.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Matching slot index when resident.
    #[inline(always)]
    #[must_use]
    fn probe_shape_slot(
        index: &[u64],
        slots: &[ShapingRunSlot],
        key: &TextShapingKey,
        hash: u64,
    ) -> Option<u32> {
        let cap: usize = index.len();
        if cap == 0 {
            return None;
        }
        let mask: usize = cap - 1;
        let tag_shifted: u64 = Self::hash_tag_shifted(hash);
        let mut idx: usize = (hash as usize) & mask;
        loop {
            let slot_val: u64 = index[idx];
            if slot_val == SHAPING_INDEX_EMPTY {
                return None;
            }
            if slot_val != SHAPING_INDEX_TOMBSTONE
                && (slot_val & 0xFFFF_FFFF_0000_0000) == tag_shifted
            {
                let slot_idx: u32 = slot_val as u32;
                let entry: &ShapingRunSlot = &slots[slot_idx as usize];
                if entry.occupied && entry.key == *key {
                    return Some(slot_idx);
                }
            }
            idx = (idx + 1) & mask;
        }
    }

    /// Probes the open-addressed `line_break_index` table once for `key`, returning its `line_break_slots` index on a hit.
    ///
    /// # Arguments
    ///
    /// - `&[u64]` - Open-addressed line-break index table.
    /// - `&[LineBreakSlot]` - Contiguous line-break slot arena.
    /// - `&LineBreakKey` - Target line-break lookup key.
    /// - `u64` - Precomputed `key.fast_hash()`.
    ///
    /// # Returns
    ///
    /// - `Option<u32>` - Matching slot index when resident.
    #[inline(always)]
    #[must_use]
    fn probe_line_break_slot(
        index: &[u64],
        slots: &[LineBreakSlot],
        key: &LineBreakKey,
        hash: u64,
    ) -> Option<u32> {
        let cap: usize = index.len();
        if cap == 0 {
            return None;
        }
        let mask: usize = cap - 1;
        let tag_shifted: u64 = Self::hash_tag_shifted(hash);
        let mut idx: usize = (hash as usize) & mask;
        loop {
            let slot_val: u64 = index[idx];
            if slot_val == SHAPING_INDEX_EMPTY {
                return None;
            }
            if slot_val != SHAPING_INDEX_TOMBSTONE
                && (slot_val & 0xFFFF_FFFF_0000_0000) == tag_shifted
            {
                let slot_idx: u32 = slot_val as u32;
                let entry: &LineBreakSlot = &slots[slot_idx as usize];
                if entry.occupied && entry.key == *key {
                    return Some(slot_idx);
                }
            }
            idx = (idx + 1) & mask;
        }
    }

    /// Inserts `(hash, slot_idx)` into `shape_index`, rehashing at 75% load (in-place when tombstones dominate).
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<u64>` - Open-addressed shaping index table.
    /// - `&mut usize` - Live plus tombstone slot counter.
    /// - `usize` - Live shaping entry count.
    /// - `&[ShapingRunSlot]` - Contiguous shaping slot arena used during rehash.
    /// - `u64` - Precomputed key hash.
    /// - `u32` - Arena slot index to insert.
    fn insert_shape_index(
        index: &mut Vec<u64>,
        occupied: &mut usize,
        live_count: usize,
        slots: &[ShapingRunSlot],
        hash: u64,
        slot_idx: u32,
    ) {
        let cap: usize = index.len();
        if cap == 0 {
            index.resize(SHAPING_INDEX_INIT_CAP, SHAPING_INDEX_EMPTY);
            *occupied = 0;
        } else if (*occupied + 1) * 4 >= cap * 3 {
            let next_cap: usize = if live_count * 2 < cap { cap } else { cap * 2 };
            let next_mask: usize = next_cap - 1;
            let mut rebuilt: Vec<u64> = vec![SHAPING_INDEX_EMPTY; next_cap];
            let mut rebuilt_count: usize = 0;
            for (i, slot) in slots.iter().enumerate() {
                if !slot.occupied {
                    continue;
                }
                let mut dst: usize = (slot.hash as usize) & next_mask;
                while rebuilt[dst] != SHAPING_INDEX_EMPTY {
                    dst = (dst + 1) & next_mask;
                }
                rebuilt[dst] = Self::pack_index_slot(slot.hash, i as u32);
                rebuilt_count += 1;
            }
            *index = rebuilt;
            *occupied = rebuilt_count;
            return;
        }
        let mask: usize = index.len() - 1;
        let mut idx: usize = (hash as usize) & mask;
        loop {
            let existing: u64 = index[idx];
            if existing == SHAPING_INDEX_EMPTY {
                index[idx] = Self::pack_index_slot(hash, slot_idx);
                *occupied = occupied.saturating_add(1);
                return;
            }
            if existing == SHAPING_INDEX_TOMBSTONE {
                index[idx] = Self::pack_index_slot(hash, slot_idx);
                return;
            }
            idx = (idx + 1) & mask;
        }
    }

    /// Inserts `(hash, slot_idx)` into `line_break_index`, rehashing at 75% load (in-place when tombstones dominate).
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<u64>` - Open-addressed line-break index table.
    /// - `&mut usize` - Live plus tombstone slot counter.
    /// - `usize` - Live line-break entry count.
    /// - `&[LineBreakSlot]` - Contiguous line-break slot arena used during rehash.
    /// - `u64` - Precomputed key hash.
    /// - `u32` - Arena slot index to insert.
    fn insert_line_break_index(
        index: &mut Vec<u64>,
        occupied: &mut usize,
        live_count: usize,
        slots: &[LineBreakSlot],
        hash: u64,
        slot_idx: u32,
    ) {
        let cap: usize = index.len();
        if cap == 0 {
            index.resize(SHAPING_INDEX_INIT_CAP, SHAPING_INDEX_EMPTY);
            *occupied = 0;
        } else if (*occupied + 1) * 4 >= cap * 3 {
            let next_cap: usize = if live_count * 2 < cap { cap } else { cap * 2 };
            let next_mask: usize = next_cap - 1;
            let mut rebuilt: Vec<u64> = vec![SHAPING_INDEX_EMPTY; next_cap];
            let mut rebuilt_count: usize = 0;
            for (i, slot) in slots.iter().enumerate() {
                if !slot.occupied {
                    continue;
                }
                let mut dst: usize = (slot.hash as usize) & next_mask;
                while rebuilt[dst] != SHAPING_INDEX_EMPTY {
                    dst = (dst + 1) & next_mask;
                }
                rebuilt[dst] = Self::pack_index_slot(slot.hash, i as u32);
                rebuilt_count += 1;
            }
            *index = rebuilt;
            *occupied = rebuilt_count;
            return;
        }
        let mask: usize = index.len() - 1;
        let mut idx: usize = (hash as usize) & mask;
        loop {
            let existing: u64 = index[idx];
            if existing == SHAPING_INDEX_EMPTY {
                index[idx] = Self::pack_index_slot(hash, slot_idx);
                *occupied = occupied.saturating_add(1);
                return;
            }
            if existing == SHAPING_INDEX_TOMBSTONE {
                index[idx] = Self::pack_index_slot(hash, slot_idx);
                return;
            }
            idx = (idx + 1) & mask;
        }
    }

    /// Marks the open-addressed slot pointing to `slot_idx` as a tombstone in O(1) expected time.
    ///
    /// # Arguments
    ///
    /// - `&mut [u64]` - Open-addressed index table containing `slot_idx`.
    /// - `u64` - Stored FxHash of the evicted entry.
    /// - `u32` - Arena slot index to tomb-mark.
    #[inline]
    fn remove_index_entry(index: &mut [u64], hash: u64, slot_idx: u32) {
        let cap: usize = index.len();
        if cap == 0 {
            return;
        }
        let mask: usize = cap - 1;
        let expected: u64 = Self::pack_index_slot(hash, slot_idx);
        let mut idx: usize = (hash as usize) & mask;
        loop {
            let existing: u64 = index[idx];
            if existing == SHAPING_INDEX_EMPTY {
                return;
            }
            if existing == expected {
                index[idx] = SHAPING_INDEX_TOMBSTONE;
                return;
            }
            idx = (idx + 1) & mask;
        }
    }

    /// Reads the `(prev, next)` intrusive LRU links of a tagged node handle.
    ///
    /// # Arguments
    ///
    /// - `&[ShapingRunSlot]` - Shaping slot arena.
    /// - `&[LineBreakSlot]` - Line-break slot arena.
    /// - `u32` - Tagged LRU node handle.
    ///
    /// # Returns
    ///
    /// - `(u32, u32)` - Pair `(prev_handle, next_handle)`.
    #[inline(always)]
    #[must_use]
    fn lru_links(
        shape_slots: &[ShapingRunSlot],
        line_break_slots: &[LineBreakSlot],
        handle: u32,
    ) -> (u32, u32) {
        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
            (line_break_slots[idx].prev, line_break_slots[idx].next)
        } else {
            (shape_slots[idx].prev, shape_slots[idx].next)
        }
    }

    /// Updates the `prev` link of a tagged node handle in O(1).
    ///
    /// # Arguments
    ///
    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
    /// - `u32` - Tagged LRU node handle.
    /// - `u32` - New previous neighbor handle.
    #[inline(always)]
    fn set_lru_prev(
        shape_slots: &mut [ShapingRunSlot],
        line_break_slots: &mut [LineBreakSlot],
        handle: u32,
        prev: u32,
    ) {
        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
            line_break_slots[idx].prev = prev;
        } else {
            shape_slots[idx].prev = prev;
        }
    }

    /// Updates the `next` link of a tagged node handle in O(1).
    ///
    /// # Arguments
    ///
    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
    /// - `u32` - Tagged LRU node handle.
    /// - `u32` - New next neighbor handle.
    #[inline(always)]
    fn set_lru_next(
        shape_slots: &mut [ShapingRunSlot],
        line_break_slots: &mut [LineBreakSlot],
        handle: u32,
        next: u32,
    ) {
        let idx: usize = (handle & SHAPING_LRU_INDEX_MASK) as usize;
        if (handle & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
            line_break_slots[idx].next = next;
        } else {
            shape_slots[idx].next = next;
        }
    }

    /// Promotes an already-linked tagged node handle to the MRU head in O(1).
    ///
    /// # Arguments
    ///
    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
    /// - `&mut u32` - Head handle pointer.
    /// - `&mut u32` - Tail handle pointer.
    /// - `u32` - Tagged node handle to move to front.
    #[inline(always)]
    fn lru_move_to_front(
        shape_slots: &mut [ShapingRunSlot],
        line_break_slots: &mut [LineBreakSlot],
        lru_head: &mut u32,
        lru_tail: &mut u32,
        handle: u32,
    ) {
        if *lru_head == handle {
            return;
        }
        let (prev, next): (u32, u32) = Self::lru_links(shape_slots, line_break_slots, handle);
        if prev != SHAPING_NODE_NONE {
            Self::set_lru_next(shape_slots, line_break_slots, prev, next);
        }
        if next != SHAPING_NODE_NONE {
            Self::set_lru_prev(shape_slots, line_break_slots, next, prev);
        } else {
            *lru_tail = prev;
        }
        let old_head: u32 = *lru_head;
        Self::set_lru_prev(shape_slots, line_break_slots, handle, SHAPING_NODE_NONE);
        Self::set_lru_next(shape_slots, line_break_slots, handle, old_head);
        if old_head != SHAPING_NODE_NONE {
            Self::set_lru_prev(shape_slots, line_break_slots, old_head, handle);
        } else {
            *lru_tail = handle;
        }
        *lru_head = handle;
    }

    /// Links a newly inserted tagged node handle at the MRU head in O(1).
    ///
    /// # Arguments
    ///
    /// - `&mut [ShapingRunSlot]` - Mutable shaping slot arena.
    /// - `&mut [LineBreakSlot]` - Mutable line-break slot arena.
    /// - `&mut u32` - Head handle pointer.
    /// - `&mut u32` - Tail handle pointer.
    /// - `u32` - Newly inserted tagged node handle.
    #[inline(always)]
    fn lru_push_front(
        shape_slots: &mut [ShapingRunSlot],
        line_break_slots: &mut [LineBreakSlot],
        lru_head: &mut u32,
        lru_tail: &mut u32,
        handle: u32,
    ) {
        let old_head: u32 = *lru_head;
        Self::set_lru_prev(shape_slots, line_break_slots, handle, SHAPING_NODE_NONE);
        Self::set_lru_next(shape_slots, line_break_slots, handle, old_head);
        if old_head != SHAPING_NODE_NONE {
            Self::set_lru_prev(shape_slots, line_break_slots, old_head, handle);
        } else {
            *lru_tail = handle;
        }
        *lru_head = handle;
    }

    /// Updates the resident byte budget and immediately evicts cold entries if currently over budget.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - New maximum resident bytes.
    pub fn set_memory_budget(&mut self, max_bytes: usize) {
        self.set_budget_bytes(max_bytes.max(TEXT_SHAPING_MIN_BUDGET_BYTES));
        self.evict_if_over_budget();
    }

    /// Advances the font fallback chain revision and invalidates all cached shaping and line-break entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `u64` - New monotonic font fallback chain revision.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the revision changed and entries were invalidated.
    pub fn invalidate_font_chain(&mut self, new_revision: u64) -> bool {
        if self.get_font_chain_revision() == new_revision {
            return false;
        }
        let Self {
            font_chain_revision,
            shape_index,
            line_break_index,
            shape_slots,
            line_break_slots,
            shape_free_slots,
            line_break_free_slots,
            lru_head,
            lru_tail,
            shape_count,
            line_break_count,
            shape_occupied,
            line_break_occupied,
            resident_bytes,
            ..
        } = self;
        *font_chain_revision = new_revision;
        shape_index.fill(SHAPING_INDEX_EMPTY);
        line_break_index.fill(SHAPING_INDEX_EMPTY);
        shape_slots.clear();
        line_break_slots.clear();
        shape_free_slots.clear();
        line_break_free_slots.clear();
        *lru_head = SHAPING_NODE_NONE;
        *lru_tail = SHAPING_NODE_NONE;
        *shape_count = 0;
        *line_break_count = 0;
        *shape_occupied = 0;
        *line_break_occupied = 0;
        *resident_bytes = 0;
        true
    }

    /// Performs a read-only single-probe zero-mutation lookup of a cached `ShapedGlyphRun`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shaping cache reference.
    /// - `&TextShapingKey` - Shaping lookup key.
    ///
    /// # Returns
    ///
    /// - `Option<&ShapedGlyphRun>` - Cached shaping run when resident.
    #[inline]
    #[must_use]
    pub fn peek_shaped(&self, key: &TextShapingKey) -> Option<&ShapedGlyphRun> {
        let Self {
            shape_index,
            shape_slots,
            ..
        } = self;
        let hash: u64 = key.fast_hash();
        let slot: u32 = Self::probe_shape_slot(shape_index, shape_slots, key, hash)?;
        Some(&shape_slots[slot as usize].run)
    }

    /// Performs a read-only single-probe zero-mutation lookup of a cached wrapped `TextLayoutResult`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shaping cache reference.
    /// - `&LineBreakKey` - Line-break lookup key.
    ///
    /// # Returns
    ///
    /// - `Option<&TextLayoutResult>` - Cached wrapped layout result when resident.
    #[inline]
    #[must_use]
    pub fn peek_line_break(&self, key: &LineBreakKey) -> Option<&TextLayoutResult> {
        let Self {
            line_break_index,
            line_break_slots,
            ..
        } = self;
        let hash: u64 = key.fast_hash();
        let slot: u32 = Self::probe_line_break_slot(line_break_index, line_break_slots, key, hash)?;
        Some(&line_break_slots[slot as usize].layout)
    }

    /// Looks up or computes a DPI- and wrap-width-independent `ShapedGlyphRun` for `key` with a single FxHash probe.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `TextShapingKey` - Shaping lookup key.
    /// - `F` - Lazy shaping function returning `(cluster_advances, total_width)` on a miss.
    ///
    /// # Returns
    ///
    /// - `&ShapedGlyphRun` - Cached shaping run reference.
    pub fn get_or_shape<F>(&mut self, key: TextShapingKey, shape_fn: F) -> &ShapedGlyphRun
    where
        F: FnOnce() -> (Vec<f32>, f32),
    {
        let hash: u64 = key.fast_hash();
        let hit_slot: Option<u32> = {
            let Self {
                shape_index,
                shape_slots,
                ..
            } = self;
            Self::probe_shape_slot(shape_index, shape_slots, &key, hash)
        };
        if let Some(slot) = hit_slot {
            let Self {
                shape_slots,
                line_break_slots,
                lru_head,
                lru_tail,
                lru_clock,
                shaping_hits,
                ..
            } = self;
            *lru_clock = lru_clock.wrapping_add(1);
            *shaping_hits = shaping_hits.saturating_add(1);
            let tick: u64 = *lru_clock;
            Self::lru_move_to_front(shape_slots, line_break_slots, lru_head, lru_tail, slot);
            let entry: &mut ShapingRunSlot = &mut shape_slots[slot as usize];
            entry.run.set_last_used_tick(tick);
            return &entry.run;
        }
        let (advances, total_width): (Vec<f32>, f32) = shape_fn();
        let cluster_count: usize = advances.len();
        let entry_bytes: usize =
            TEXT_SHAPING_ENTRY_OVERHEAD_BYTES.saturating_add(cluster_count.saturating_mul(4));
        self.evict_to_make_room(entry_bytes);
        let Self {
            shape_index,
            shape_slots,
            line_break_slots,
            shape_free_slots,
            lru_head,
            lru_tail,
            shape_count,
            shape_occupied,
            resident_bytes,
            lru_clock,
            shaping_misses,
            ..
        } = self;
        *lru_clock = lru_clock.wrapping_add(1);
        *shaping_misses = shaping_misses.saturating_add(1);
        let run: ShapedGlyphRun = ShapedGlyphRun {
            cluster_advances: advances,
            total_width,
            cluster_count,
            byte_size: entry_bytes,
            last_used_tick: *lru_clock,
        };
        let slot_val: ShapingRunSlot = ShapingRunSlot {
            occupied: true,
            hash,
            key,
            run,
            prev: SHAPING_NODE_NONE,
            next: SHAPING_NODE_NONE,
        };
        let slot: u32 = if let Some(reused) = shape_free_slots.pop() {
            shape_slots[reused as usize] = slot_val;
            reused
        } else {
            let next_idx: u32 = shape_slots.len() as u32;
            shape_slots.push(slot_val);
            next_idx
        };
        Self::lru_push_front(shape_slots, line_break_slots, lru_head, lru_tail, slot);
        *shape_count = shape_count.saturating_add(1);
        Self::insert_shape_index(
            shape_index,
            shape_occupied,
            *shape_count,
            shape_slots,
            hash,
            slot,
        );
        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
        &shape_slots[slot as usize].run
    }

    /// Looks up or computes a DPI- and color-independent wrapped `TextLayoutResult` for `key` with a single FxHash probe.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `LineBreakKey` - Line-break lookup key.
    /// - `F` - Lazy line-break computation invoked only on cache miss.
    ///
    /// # Returns
    ///
    /// - `&TextLayoutResult` - Cached wrapped layout result.
    pub fn get_or_break_lines<F>(&mut self, key: LineBreakKey, break_fn: F) -> &TextLayoutResult
    where
        F: FnOnce() -> TextLayoutResult,
    {
        let hash: u64 = key.fast_hash();
        let hit_slot: Option<u32> = {
            let Self {
                line_break_index,
                line_break_slots,
                ..
            } = self;
            Self::probe_line_break_slot(line_break_index, line_break_slots, &key, hash)
        };
        if let Some(slot) = hit_slot {
            let Self {
                shape_slots,
                line_break_slots,
                lru_head,
                lru_tail,
                lru_clock,
                line_break_hits,
                ..
            } = self;
            *lru_clock = lru_clock.wrapping_add(1);
            *line_break_hits = line_break_hits.saturating_add(1);
            let handle: u32 = slot | SHAPING_LRU_LINE_BREAK_BIT;
            Self::lru_move_to_front(shape_slots, line_break_slots, lru_head, lru_tail, handle);
            return &line_break_slots[slot as usize].layout;
        }
        let layout: TextLayoutResult = break_fn();
        let mut entry_bytes: usize = TEXT_SHAPING_ENTRY_OVERHEAD_BYTES;
        for line in layout.get_lines().iter() {
            entry_bytes = entry_bytes
                .saturating_add(32)
                .saturating_add(line.get_text().len());
        }
        self.evict_to_make_room(entry_bytes);
        let Self {
            line_break_index,
            shape_slots,
            line_break_slots,
            line_break_free_slots,
            lru_head,
            lru_tail,
            line_break_count,
            line_break_occupied,
            resident_bytes,
            lru_clock,
            line_break_misses,
            ..
        } = self;
        *lru_clock = lru_clock.wrapping_add(1);
        *line_break_misses = line_break_misses.saturating_add(1);
        let slot_val: LineBreakSlot = LineBreakSlot {
            occupied: true,
            hash,
            byte_size: entry_bytes,
            key,
            layout,
            prev: SHAPING_NODE_NONE,
            next: SHAPING_NODE_NONE,
        };
        let slot: u32 = if let Some(reused) = line_break_free_slots.pop() {
            line_break_slots[reused as usize] = slot_val;
            reused
        } else {
            let next_idx: u32 = line_break_slots.len() as u32;
            line_break_slots.push(slot_val);
            next_idx
        };
        let handle: u32 = slot | SHAPING_LRU_LINE_BREAK_BIT;
        Self::lru_push_front(shape_slots, line_break_slots, lru_head, lru_tail, handle);
        *line_break_count = line_break_count.saturating_add(1);
        Self::insert_line_break_index(
            line_break_index,
            line_break_occupied,
            *line_break_count,
            line_break_slots,
            hash,
            slot,
        );
        *resident_bytes = resident_bytes.saturating_add(entry_bytes);
        &line_break_slots[slot as usize].layout
    }

    /// Evicts coldest entries across shaping and line-break tables when `resident_bytes + incoming_bytes > budget_bytes`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - Size in bytes of the incoming entry.
    fn evict_to_make_room(&mut self, incoming_bytes: usize) {
        let budget: usize = self.get_budget_bytes();
        if self.get_resident_bytes().saturating_add(incoming_bytes) <= budget {
            return;
        }
        let target: usize = budget
            .saturating_mul(3)
            .saturating_div(4)
            .saturating_sub(incoming_bytes);
        self.evict_lru_to_target(target);
    }

    /// Evicts coldest entries whenever current resident bytes exceed the configured budget.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    pub fn evict_if_over_budget(&mut self) {
        let budget: usize = self.get_budget_bytes();
        if self.get_resident_bytes() <= budget {
            return;
        }
        let target: usize = (budget.saturating_mul(3) / 4).max(TEXT_SHAPING_ENTRY_OVERHEAD_BYTES);
        self.evict_lru_to_target(target);
    }

    /// Evicts least-recently-used entries from `lru_tail` in strict O(1) per victim with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable shaping cache.
    /// - `usize` - Target post-eviction resident byte ceiling.
    fn evict_lru_to_target(&mut self, target_bytes: usize) {
        let Self {
            shape_index,
            line_break_index,
            shape_slots,
            line_break_slots,
            shape_free_slots,
            line_break_free_slots,
            lru_head,
            lru_tail,
            shape_count,
            line_break_count,
            resident_bytes,
            evictions,
            ..
        } = self;
        while *resident_bytes > target_bytes && *lru_tail != SHAPING_NODE_NONE {
            let victim: u32 = *lru_tail;
            let (prev, _): (u32, u32) = Self::lru_links(shape_slots, line_break_slots, victim);
            *lru_tail = prev;
            if prev != SHAPING_NODE_NONE {
                Self::set_lru_next(shape_slots, line_break_slots, prev, SHAPING_NODE_NONE);
            } else {
                *lru_head = SHAPING_NODE_NONE;
            }
            let slot_idx: u32 = victim & SHAPING_LRU_INDEX_MASK;
            if (victim & SHAPING_LRU_LINE_BREAK_BIT) != 0 {
                let slot: &mut LineBreakSlot = &mut line_break_slots[slot_idx as usize];
                if slot.occupied {
                    let victim_hash: u64 = slot.hash;
                    let victim_bytes: usize = slot.byte_size;
                    slot.occupied = false;
                    slot.byte_size = 0;
                    slot.prev = SHAPING_NODE_NONE;
                    slot.next = SHAPING_NODE_NONE;
                    slot.layout = TextLayoutResult::default();
                    Self::remove_index_entry(line_break_index, victim_hash, slot_idx);
                    *line_break_count = line_break_count.saturating_sub(1);
                    *resident_bytes = resident_bytes.saturating_sub(victim_bytes);
                    *evictions = evictions.saturating_add(1);
                    line_break_free_slots.push(slot_idx);
                }
            } else {
                let slot: &mut ShapingRunSlot = &mut shape_slots[slot_idx as usize];
                if slot.occupied {
                    let victim_hash: u64 = slot.hash;
                    let victim_bytes: usize = slot.run.get_byte_size();
                    slot.occupied = false;
                    slot.prev = SHAPING_NODE_NONE;
                    slot.next = SHAPING_NODE_NONE;
                    slot.run = ShapedGlyphRun::default();
                    Self::remove_index_entry(shape_index, victim_hash, slot_idx);
                    *shape_count = shape_count.saturating_sub(1);
                    *resident_bytes = resident_bytes.saturating_sub(victim_bytes);
                    *evictions = evictions.saturating_add(1);
                    shape_free_slots.push(slot_idx);
                }
            }
        }
    }

    /// Returns total cached entry count combining shaping runs and wrapped line-break entries.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shaping cache reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Total cached entries.
    #[must_use]
    pub fn total_entries(&self) -> usize {
        let Self {
            shape_count,
            line_break_count,
            ..
        } = self;
        shape_count.saturating_add(*line_break_count)
    }
}