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
use super::*;
/// Construction 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 {
text_hash_a,
text_hash_b,
text_len: text.len() as u32,
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,
}
}
/// 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 mut ha: u64 = self.get_text_hash_a();
let mut hb: u64 = self.get_text_hash_b();
let meta: u64 =
((self.get_font_size_bits() as u64) << 32) | (self.get_letter_spacing_bits() as u64);
ha = (ha ^ meta).wrapping_mul(SHAPING_FNV_PRIME);
hb = (hb ^ self.get_locale_hash() ^ ((self.get_family() as u64) << 8))
.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(),
}
}
}
/// 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)
}
}
/// Split shaping & line-break caching, independent font-chain invalidation, and bounded LRU eviction for `TextShapingCache`.
impl TextShapingCache {
/// Creates a `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,
shaped_runs: HashMap::new(),
line_breaks: HashMap::new(),
shaping_hits: 0,
shaping_misses: 0,
line_break_hits: 0,
line_break_misses: 0,
evictions: 0,
}
}
/// 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,
shaped_runs,
line_breaks,
resident_bytes,
..
} = self;
*font_chain_revision = new_revision;
shaped_runs.clear();
line_breaks.clear();
*resident_bytes = 0;
true
}
/// Looks up or computes a DPI- and wrap-width-independent `ShapedGlyphRun` for `key`.
///
/// # 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 hit: bool = self.get_shaped_runs().contains_key(&key);
if hit {
let Self {
shaped_runs,
lru_clock,
shaping_hits,
..
} = self;
*lru_clock = lru_clock.wrapping_add(1);
*shaping_hits = shaping_hits.saturating_add(1);
let tick: u64 = *lru_clock;
if let Some(entry) = shaped_runs.get_mut(&key) {
entry.set_last_used_tick(tick);
}
return &shaped_runs[&key];
}
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 {
shaped_runs,
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 _: Option<ShapedGlyphRun> = shaped_runs.insert(key, run);
*resident_bytes = resident_bytes.saturating_add(entry_bytes);
&shaped_runs[&key]
}
/// Looks up or computes a DPI- and color-independent wrapped `TextLayoutResult` for `key`.
///
/// # 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 hit: bool = self.get_line_breaks().contains_key(&key);
if hit {
let Self {
line_breaks,
lru_clock,
line_break_hits,
..
} = self;
*lru_clock = lru_clock.wrapping_add(1);
*line_break_hits = line_break_hits.saturating_add(1);
let tick: u64 = *lru_clock;
if let Some(entry) = line_breaks.get_mut(&key) {
entry.set_last_used_tick(tick);
}
return line_breaks[&key].get_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_breaks,
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 entry: CachedLineBreakEntry = CachedLineBreakEntry {
layout,
byte_size: entry_bytes,
last_used_tick: *lru_clock,
};
let _: Option<CachedLineBreakEntry> = line_breaks.insert(key, entry);
*resident_bytes = resident_bytes.saturating_add(entry_bytes);
line_breaks[&key].get_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 shaping and line-break entries until `resident_bytes <= target_bytes`.
///
/// # Arguments
///
/// - `&Self` - Mutable shaping cache.
/// - `usize` - Target post-eviction resident byte ceiling.
fn evict_lru_to_target(&mut self, target_bytes: usize) {
let Self {
shaped_runs,
line_breaks,
resident_bytes,
evictions,
..
} = self;
let mut victims: Vec<ShapingEvictVictim> =
Vec::with_capacity(shaped_runs.len() + line_breaks.len());
for (k, v) in shaped_runs.iter() {
victims.push(ShapingEvictVictim {
last_used_tick: v.get_last_used_tick(),
is_shape: true,
shape_key: *k,
line_break_key: LineBreakKey::default(),
byte_size: v.get_byte_size(),
});
}
for (k, v) in line_breaks.iter() {
victims.push(ShapingEvictVictim {
last_used_tick: v.get_last_used_tick(),
is_shape: false,
shape_key: TextShapingKey::default(),
line_break_key: *k,
byte_size: v.get_byte_size(),
});
}
victims.sort_unstable_by_key(|item: &ShapingEvictVictim| item.last_used_tick);
for victim in victims.into_iter() {
if *resident_bytes <= target_bytes {
break;
}
if victim.is_shape {
if shaped_runs.remove(&victim.shape_key).is_some() {
*resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
*evictions = evictions.saturating_add(1);
}
} else if line_breaks.remove(&victim.line_break_key).is_some() {
*resident_bytes = resident_bytes.saturating_sub(victim.byte_size);
*evictions = evictions.saturating_add(1);
}
}
}
/// 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 {
self.get_shaped_runs()
.len()
.saturating_add(self.get_line_breaks().len())
}
}