Skip to main content

euv_core/layout/cache/
impl.rs

1use super::*;
2
3/// Construction helpers for `AvailableSpace`.
4impl AvailableSpace {
5    /// Creates root-level `AvailableSpace` matching the window viewport.
6    ///
7    /// # Arguments
8    ///
9    /// - `Size` - Logical viewport dimensions.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Root available space at `(0, 0)`.
14    #[must_use]
15    #[inline(always)]
16    pub fn root(viewport: Size) -> Self {
17        Self::new(
18            viewport.get_width(),
19            viewport.get_height(),
20            viewport,
21            0.0,
22            0.0,
23        )
24    }
25
26    /// Marks whether this node's auto width or height is stretched to fill the available slot.
27    ///
28    /// # Arguments
29    ///
30    /// - `Self` - Source available space.
31    /// - `bool` - Whether auto width stretches to `width`.
32    /// - `bool` - Whether auto height stretches to `height`.
33    ///
34    /// # Returns
35    ///
36    /// - `Self` - Updated available space with stretch flags applied.
37    #[must_use]
38    #[inline(always)]
39    pub fn with_stretch(mut self, stretch_width: bool, stretch_height: bool) -> Self {
40        self.set_stretch_width(stretch_width);
41        self.set_stretch_height(stretch_height);
42        self
43    }
44
45    /// Checks whether this cached layout constraint matches `incoming` size, viewport, and stretch flags.
46    ///
47    /// # Arguments
48    ///
49    /// - `&Self` - Previously cached layout constraint.
50    /// - `Self` - Incoming layout constraint for the current pass.
51    ///
52    /// # Returns
53    ///
54    /// - `bool` - `true` when cached node dimensions can be reused without recomputing layout.
55    #[must_use]
56    #[inline(always)]
57    pub(crate) fn can_reuse(&self, incoming: Self) -> bool {
58        self.get_stretch_width() == incoming.get_stretch_width()
59            && self.get_stretch_height() == incoming.get_stretch_height()
60            && (self.get_width() - incoming.get_width()).abs() <= 0.01
61            && (self.get_height() - incoming.get_height()).abs() <= 0.01
62            && (self.get_viewport().get_width() - incoming.get_viewport().get_width()).abs() <= 0.01
63            && (self.get_viewport().get_height() - incoming.get_viewport().get_height()).abs()
64                <= 0.01
65    }
66
67    /// Checks whether this cached layout constraint shares the same logical origin as `incoming`.
68    ///
69    /// # Arguments
70    ///
71    /// - `&Self` - Previously cached layout constraint.
72    /// - `Self` - Incoming layout constraint for the current pass.
73    ///
74    /// # Returns
75    ///
76    /// - `bool` - `true` when subtree translation can be skipped completely.
77    #[must_use]
78    #[inline(always)]
79    pub(crate) fn same_origin(&self, incoming: Self) -> bool {
80        (self.get_origin_x() - incoming.get_origin_x()).abs() <= 0.001
81            && (self.get_origin_y() - incoming.get_origin_y()).abs() <= 0.001
82    }
83
84    /// Encodes `stretch_width` and `stretch_height` into Taffy-style `(known_w, known_h)` values (`NaN` when unstretched).
85    ///
86    /// # Arguments
87    ///
88    /// - `&Self` - Source available space.
89    ///
90    /// # Returns
91    ///
92    /// - `(f32, f32)` - Pair of `(known_w, known_h)` with `f32::NAN` sentinel for unstretched axes.
93    #[must_use]
94    #[inline(always)]
95    pub(crate) fn known_dimensions(&self) -> (f32, f32) {
96        let known_w: f32 = if self.get_stretch_width() {
97            self.get_width()
98        } else {
99            f32::NAN
100        };
101        let known_h: f32 = if self.get_stretch_height() {
102            self.get_height()
103        } else {
104            f32::NAN
105        };
106        (known_w, known_h)
107    }
108}
109
110/// Public read-only accessors for `SplitCacheStats`.
111impl SplitCacheStats {
112    /// Returns the number of O(1) measure cache hits in `SplitLayoutCache::measure_slots`.
113    ///
114    /// # Arguments
115    ///
116    /// - `&Self` - Split cache diagnostics snapshot.
117    ///
118    /// # Returns
119    ///
120    /// - `u64` - Measure cache hit count.
121    #[must_use]
122    #[inline(always)]
123    pub fn measure_hits(&self) -> u64 {
124        let Self { measure_hits, .. } = self;
125        *measure_hits
126    }
127
128    /// Returns the number of measure cache misses in `ComputeSize` mode.
129    ///
130    /// # Arguments
131    ///
132    /// - `&Self` - Split cache diagnostics snapshot.
133    ///
134    /// # Returns
135    ///
136    /// - `u64` - Measure cache miss count.
137    #[must_use]
138    #[inline(always)]
139    pub fn measure_misses(&self) -> u64 {
140        let Self { measure_misses, .. } = self;
141        *measure_misses
142    }
143
144    /// Returns the number of O(1) final layout cache hits in `SplitLayoutCache::final_slots`.
145    ///
146    /// # Arguments
147    ///
148    /// - `&Self` - Split cache diagnostics snapshot.
149    ///
150    /// # Returns
151    ///
152    /// - `u64` - Final layout cache hit count.
153    #[must_use]
154    #[inline(always)]
155    pub fn final_hits(&self) -> u64 {
156        let Self { final_hits, .. } = self;
157        *final_hits
158    }
159
160    /// Returns the number of final layout cache misses in `PerformLayout` mode.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Split cache diagnostics snapshot.
165    ///
166    /// # Returns
167    ///
168    /// - `u64` - Final layout cache miss count.
169    #[must_use]
170    #[inline(always)]
171    pub fn final_misses(&self) -> u64 {
172        let Self { final_misses, .. } = self;
173        *final_misses
174    }
175
176    /// Returns the number of `Display::None` subtrees short-circuited in O(1).
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Split cache diagnostics snapshot.
181    ///
182    /// # Returns
183    ///
184    /// - `u64` - `Display::None` O(1) skip count.
185    #[must_use]
186    #[inline(always)]
187    pub fn display_none_skips(&self) -> u64 {
188        let Self {
189            display_none_skips, ..
190        } = self;
191        *display_none_skips
192    }
193
194    /// Returns the number of text measurements served from `TextSizeCache` without invoking the measurer.
195    ///
196    /// # Arguments
197    ///
198    /// - `&Self` - Split cache diagnostics snapshot.
199    ///
200    /// # Returns
201    ///
202    /// - `u64` - Interval or wrapped text cache hit count.
203    #[must_use]
204    #[inline(always)]
205    pub fn text_interval_hits(&self) -> u64 {
206        let Self {
207            text_interval_hits, ..
208        } = self;
209        *text_interval_hits
210    }
211
212    /// Returns the number of text measurements that reused cached per-node text hashes without re-hashing.
213    ///
214    /// # Arguments
215    ///
216    /// - `&Self` - Split cache diagnostics snapshot.
217    ///
218    /// # Returns
219    ///
220    /// - `u64` - Cached text hash reuse count.
221    #[must_use]
222    #[inline(always)]
223    pub fn text_hash_reuses(&self) -> u64 {
224        let Self {
225            text_hash_reuses, ..
226        } = self;
227        *text_hash_reuses
228    }
229}
230
231/// Bounded 2-way set-associative interval-aware text measurement cache operations.
232impl TextSizeCache {
233    /// Measures `(text, style, max_width)` using a precomputed `(hash_a, hash_b, text_len)` key without re-hashing `text`.
234    ///
235    /// # Arguments
236    ///
237    /// - `&Self` - Mutable text-size cache.
238    /// - `&str` - UTF-8 text string to measure on miss.
239    /// - `(u64, u64, u32)` - Precomputed `(hash_a, hash_b, text_len)` identity of `text`.
240    /// - `TextStyle` - Active typography style.
241    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
242    /// - `F` - Closure invoked only on a cache miss to compute exact bounding `Size`.
243    ///
244    /// # Returns
245    ///
246    /// - `TextSizeMeasurement` - Measured bounding size, unwrapped interval flag, and cache-hit flag.
247    pub(crate) fn get_or_measure_hashed<F>(
248        &mut self,
249        text: &str,
250        text_key: (u64, u64, u32),
251        style: TextStyle,
252        max_width: Option<f32>,
253        mut measure_fn: F,
254    ) -> TextSizeMeasurement
255    where
256        F: FnMut(&str, TextStyle, Option<f32>) -> Size,
257    {
258        if text.is_empty() {
259            let line_h: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
260            return TextSizeMeasurement {
261                size: Size::new(0.0, line_h),
262                unwrapped: true,
263                max_content_w: 0.0,
264                cache_hit: true,
265            };
266        }
267        let (hash_a, hash_b, text_len): (u64, u64, u32) = text_key;
268        let style_key: TextStyleKey = Self::build_style_key(style);
269        let style_mix: u64 = ((style_key.font_size_bits as u64) << 32)
270            ^ ((style_key.line_height_bits as u64).rotate_left(17))
271            ^ ((style_key.letter_spacing_bits as u64).rotate_left(41))
272            ^ ((style_key.style_flags as u64).wrapping_mul(TEXT_HASH_PRIME_B));
273        let set_index: usize = (((hash_a ^ style_mix).wrapping_mul(TEXT_HASH_FINAL_A) >> 16)
274            as usize)
275            & TEXT_SIZE_CACHE_SET_MASK;
276        let base: usize = set_index * TEXT_SIZE_CACHE_WAYS;
277        let Self { entries } = self;
278        if entries.is_empty() {
279            entries.resize(TEXT_SIZE_CACHE_SLOTS, TextSizeEntry::default());
280        }
281        let way0: TextSizeEntry = entries[base];
282        if !Self::entry_key_matches(way0, hash_a, hash_b, text_len, style_key) {
283            let way1: TextSizeEntry = entries[base + 1];
284            if Self::entry_key_matches(way1, hash_a, hash_b, text_len, style_key) {
285                entries[base] = way1;
286                entries[base + 1] = way0;
287            } else {
288                entries[base + 1] = way0;
289                entries[base] = TextSizeEntry {
290                    hash_a,
291                    hash_b,
292                    text_len,
293                    style_key,
294                    entry_flags: 0,
295                    min_content_w: 0.0,
296                    max_content_w: 0.0,
297                    single_line_h: 0.0,
298                    none_w: 0.0,
299                    none_h: 0.0,
300                    last_max_w_bits: TEXT_SIZE_MAX_WIDTH_NONE_BITS,
301                    last_wrapped_w: 0.0,
302                    last_wrapped_h: 0.0,
303                };
304            }
305        }
306        let entry: &mut TextSizeEntry = &mut entries[base];
307        let effective_limit: Option<f32> = match max_width {
308            Some(w) if w.is_nan() => Some(0.0),
309            other => other,
310        };
311        let max_w_bits: u32 = match effective_limit {
312            Some(w) => Self::normalize_f32_bits(w),
313            None => TEXT_SIZE_MAX_WIDTH_NONE_BITS,
314        };
315        match style.get_overflow() {
316            TextOverflow::Clip => {
317                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0 {
318                    return TextSizeMeasurement {
319                        size: Size::new(entry.max_content_w, entry.single_line_h),
320                        unwrapped: true,
321                        max_content_w: entry.max_content_w,
322                        cache_hit: true,
323                    };
324                }
325                let measured: Size = measure_fn(text, style, None);
326                entry.min_content_w = measured.get_width();
327                entry.max_content_w = measured.get_width();
328                entry.single_line_h = measured.get_height();
329                entry.entry_flags |=
330                    TEXT_SIZE_ENTRY_HAS_UNWRAPPED | TEXT_SIZE_ENTRY_HAS_MIN_CONTENT;
331                TextSizeMeasurement {
332                    size: measured,
333                    unwrapped: true,
334                    max_content_w: entry.max_content_w,
335                    cache_hit: false,
336                }
337            }
338            TextOverflow::Ellipsis => {
339                let mut had_unwrapped: bool =
340                    (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0;
341                if !had_unwrapped {
342                    let unwrapped_sz: Size = measure_fn(text, style, None);
343                    entry.max_content_w = unwrapped_sz.get_width();
344                    entry.single_line_h = unwrapped_sz.get_height();
345                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_UNWRAPPED;
346                    had_unwrapped = false;
347                }
348                let fits_untruncated: bool = match effective_limit {
349                    None => true,
350                    Some(limit) => limit <= 0.0 || entry.max_content_w <= limit + 0.5,
351                };
352                if fits_untruncated {
353                    return TextSizeMeasurement {
354                        size: Size::new(entry.max_content_w, entry.single_line_h),
355                        unwrapped: true,
356                        max_content_w: entry.max_content_w,
357                        cache_hit: had_unwrapped,
358                    };
359                }
360                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_WRAPPED) != 0
361                    && entry.last_max_w_bits == max_w_bits
362                {
363                    return TextSizeMeasurement {
364                        size: Size::new(entry.last_wrapped_w, entry.last_wrapped_h),
365                        unwrapped: false,
366                        max_content_w: entry.max_content_w,
367                        cache_hit: true,
368                    };
369                }
370                let measured: Size = measure_fn(text, style, effective_limit);
371                entry.last_max_w_bits = max_w_bits;
372                entry.last_wrapped_w = measured.get_width();
373                entry.last_wrapped_h = measured.get_height();
374                entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_WRAPPED;
375                TextSizeMeasurement {
376                    size: measured,
377                    unwrapped: false,
378                    max_content_w: entry.max_content_w,
379                    cache_hit: false,
380                }
381            }
382            TextOverflow::Wrap => {
383                let active_limit: Option<f32> = effective_limit.filter(|w: &f32| *w > 0.0);
384                let Some(limit) = active_limit else {
385                    if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_NONE) != 0 {
386                        return TextSizeMeasurement {
387                            size: Size::new(entry.none_w, entry.none_h),
388                            unwrapped: true,
389                            max_content_w: entry.none_w,
390                            cache_hit: true,
391                        };
392                    }
393                    let measured: Size = measure_fn(text, style, None);
394                    entry.none_w = measured.get_width();
395                    entry.none_h = measured.get_height();
396                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_NONE;
397                    if !Self::has_line_edge_spaces(text) {
398                        entry.max_content_w = measured.get_width();
399                        entry.single_line_h = measured.get_height();
400                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_UNWRAPPED;
401                    }
402                    return TextSizeMeasurement {
403                        size: measured,
404                        unwrapped: true,
405                        max_content_w: measured.get_width(),
406                        cache_hit: false,
407                    };
408                };
409                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
410                    && (limit >= entry.max_content_w
411                        || ((entry.entry_flags & TEXT_SIZE_ENTRY_HAS_MIN_CONTENT) != 0
412                            && (entry.min_content_w - entry.max_content_w).abs() <= 0.001))
413                {
414                    return TextSizeMeasurement {
415                        size: Size::new(entry.max_content_w, entry.single_line_h),
416                        unwrapped: true,
417                        max_content_w: entry.max_content_w,
418                        cache_hit: true,
419                    };
420                }
421                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_WRAPPED) != 0
422                    && entry.last_max_w_bits == max_w_bits
423                {
424                    let known_max: f32 = if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
425                    {
426                        entry.max_content_w
427                    } else {
428                        f32::INFINITY
429                    };
430                    return TextSizeMeasurement {
431                        size: Size::new(entry.last_wrapped_w, entry.last_wrapped_h),
432                        unwrapped: false,
433                        max_content_w: known_max,
434                        cache_hit: true,
435                    };
436                }
437                let measured: Size = measure_fn(text, style, Some(limit));
438                let line_h: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
439                let expected_h: f32 = (Self::count_raw_lines(text) as f32) * line_h;
440                if (measured.get_height() - expected_h).abs() <= 0.01 {
441                    entry.max_content_w = measured.get_width();
442                    entry.single_line_h = measured.get_height();
443                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_UNWRAPPED;
444                    if measured.get_width() > limit {
445                        entry.min_content_w = measured.get_width();
446                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_MIN_CONTENT;
447                    }
448                    TextSizeMeasurement {
449                        size: measured,
450                        unwrapped: true,
451                        max_content_w: entry.max_content_w,
452                        cache_hit: false,
453                    }
454                } else {
455                    entry.last_max_w_bits = max_w_bits;
456                    entry.last_wrapped_w = measured.get_width();
457                    entry.last_wrapped_h = measured.get_height();
458                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_WRAPPED;
459                    if limit <= 1.01 {
460                        entry.min_content_w = measured.get_width();
461                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_MIN_CONTENT;
462                    }
463                    let known_max: f32 = if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
464                    {
465                        entry.max_content_w
466                    } else {
467                        f32::INFINITY
468                    };
469                    TextSizeMeasurement {
470                        size: measured,
471                        unwrapped: false,
472                        max_content_w: known_max,
473                        cache_hit: false,
474                    }
475                }
476            }
477        }
478    }
479
480    /// Computes two independent 64-bit hashes over `bytes` in a single 8-byte-chunked pass.
481    ///
482    /// # Arguments
483    ///
484    /// - `&[u8]` - UTF-8 input bytes.
485    ///
486    /// # Returns
487    ///
488    /// - `(u64, u64)` - Pair of independent 64-bit hashes with avalanche mixing.
489    #[inline(always)]
490    pub(crate) fn hash_text_128(bytes: &[u8]) -> (u64, u64) {
491        let len: usize = bytes.len();
492        let len_u64: u64 = len as u64;
493        let mut h1: u64 = TEXT_HASH_SEED_A ^ len_u64;
494        let mut h2: u64 = TEXT_HASH_SEED_B ^ len_u64.wrapping_mul(TEXT_HASH_PRIME_B);
495        let mut offset: usize = 0;
496        while offset + 8 <= len {
497            let word: u64 = u64::from_le_bytes([
498                bytes[offset],
499                bytes[offset + 1],
500                bytes[offset + 2],
501                bytes[offset + 3],
502                bytes[offset + 4],
503                bytes[offset + 5],
504                bytes[offset + 6],
505                bytes[offset + 7],
506            ]);
507            h1 = (h1 ^ word).wrapping_mul(TEXT_HASH_PRIME_A);
508            h2 = (h2.rotate_left(27) ^ word).wrapping_mul(TEXT_HASH_PRIME_B);
509            offset += 8;
510        }
511        let mut tail: u64 = 0;
512        let mut shift: u32 = 0;
513        while offset < len {
514            tail |= (bytes[offset] as u64) << shift;
515            shift += 8;
516            offset += 1;
517        }
518        h1 = (h1 ^ tail).wrapping_mul(TEXT_HASH_PRIME_A);
519        h2 = (h2.rotate_left(27) ^ tail).wrapping_mul(TEXT_HASH_PRIME_B);
520        h1 ^= h1 >> 33;
521        h1 = h1.wrapping_mul(TEXT_HASH_FINAL_A);
522        h1 ^= h1 >> 33;
523        h2 ^= h2 >> 31;
524        h2 = h2.wrapping_mul(TEXT_HASH_FINAL_B);
525        h2 ^= h2 >> 31;
526        (h1, h2)
527    }
528
529    /// Checks whether a cached `TextSizeEntry` matches the `(hash_a, hash_b, text_len, style_key)` key.
530    ///
531    /// # Arguments
532    ///
533    /// - `TextSizeEntry` - Candidate cache entry.
534    /// - `u64` - Primary text hash.
535    /// - `u64` - Secondary text hash.
536    /// - `u32` - Text byte length.
537    /// - `TextStyleKey` - Packed typography key.
538    ///
539    /// # Returns
540    ///
541    /// - `bool` - `true` when the entry is occupied and matches all key components.
542    #[inline(always)]
543    fn entry_key_matches(
544        entry: TextSizeEntry,
545        hash_a: u64,
546        hash_b: u64,
547        text_len: u32,
548        style_key: TextStyleKey,
549    ) -> bool {
550        entry.style_key == style_key
551            && entry.text_len == text_len
552            && entry.hash_a == hash_a
553            && entry.hash_b == hash_b
554    }
555
556    /// Packs a `TextStyle` into a compact `TextStyleKey` with `TEXT_SIZE_ENTRY_OCCUPIED` set.
557    ///
558    /// # Arguments
559    ///
560    /// - `TextStyle` - Source typography style.
561    ///
562    /// # Returns
563    ///
564    /// - `TextStyleKey` - Normalized typography key.
565    #[inline(always)]
566    fn build_style_key(style: TextStyle) -> TextStyleKey {
567        TextStyleKey {
568            font_size_bits: Self::normalize_f32_bits(style.get_font_size()),
569            line_height_bits: Self::normalize_f32_bits(style.get_line_height()),
570            letter_spacing_bits: Self::normalize_f32_bits(style.get_letter_spacing()),
571            style_flags: Self::pack_style_flags(style),
572        }
573    }
574
575    /// Counts explicit `\n`-delimited raw lines in `text`.
576    ///
577    /// # Arguments
578    ///
579    /// - `&str` - Input UTF-8 string.
580    ///
581    /// # Returns
582    ///
583    /// - `usize` - Number of raw lines (`>= 1`).
584    #[inline(always)]
585    fn count_raw_lines(text: &str) -> usize {
586        let bytes: &[u8] = text.as_bytes();
587        if !bytes.contains(&b'\n') {
588            return 1;
589        }
590        let mut count: usize = 1;
591        for &b in bytes.iter() {
592            if b == b'\n' {
593                count += 1;
594            }
595        }
596        count
597    }
598
599    /// Checks whether any `\n`-delimited line in `text` begins or ends with an ASCII space.
600    ///
601    /// # Arguments
602    ///
603    /// - `&str` - Input UTF-8 string.
604    ///
605    /// # Returns
606    ///
607    /// - `bool` - `true` when leading or trailing spaces could differentiate `None` vs wrapped widths.
608    #[inline(always)]
609    fn has_line_edge_spaces(text: &str) -> bool {
610        let bytes: &[u8] = text.as_bytes();
611        if bytes.is_empty() {
612            return false;
613        }
614        if !bytes.contains(&b'\n') {
615            return bytes[0] == b' ' || bytes[bytes.len() - 1] == b' ';
616        }
617        for line in text.split('\n') {
618            let lb: &[u8] = line.as_bytes();
619            if !lb.is_empty() && (lb[0] == b' ' || lb[lb.len() - 1] == b' ') {
620                return true;
621            }
622        }
623        false
624    }
625
626    /// Normalizes floating-point bits so `-0.0` and `+0.0` map identically.
627    ///
628    /// # Arguments
629    ///
630    /// - `f32` - Input scalar value.
631    ///
632    /// # Returns
633    ///
634    /// - `u32` - Normalized IEEE-754 bit pattern.
635    #[inline(always)]
636    fn normalize_f32_bits(value: f32) -> u32 {
637        if value == 0.0 { 0 } else { value.to_bits() }
638    }
639
640    /// Packs layout-relevant discrete typography flags plus the occupied marker bit into `u16`.
641    ///
642    /// # Arguments
643    ///
644    /// - `TextStyle` - Source typography style.
645    ///
646    /// # Returns
647    ///
648    /// - `u16` - Packed flag bitfield with `TEXT_SIZE_ENTRY_OCCUPIED` set.
649    #[inline(always)]
650    fn pack_style_flags(style: TextStyle) -> u16 {
651        let family_bits: u16 = match style.get_family() {
652            FontFamily::Sans => 0,
653            FontFamily::Monospace => 1,
654            FontFamily::Serif => 2,
655        };
656        let weight_bits: u16 = match style.get_weight() {
657            FontWeight::Light => 0,
658            FontWeight::Normal => 1,
659            FontWeight::Medium => 2,
660            FontWeight::SemiBold => 3,
661            FontWeight::Bold => 4,
662        };
663        let overflow_bits: u16 = match style.get_overflow() {
664            TextOverflow::Wrap => 0,
665            TextOverflow::Clip => 1,
666            TextOverflow::Ellipsis => 2,
667        };
668        let italic_bit: u16 = if style.get_italic() { 1 } else { 0 };
669        TEXT_SIZE_ENTRY_OCCUPIED
670            | family_bits
671            | (weight_bits << 2)
672            | (overflow_bits << 5)
673            | (italic_bit << 7)
674    }
675}
676
677/// Matching helpers for `MeasureCacheSlot`.
678impl MeasureCacheSlot {
679    /// Checks whether this LRU measure slot matches an incoming constraint and content generation.
680    ///
681    /// # Arguments
682    ///
683    /// - `&Self` - Candidate measure cache slot.
684    /// - `AvailableSpace` - Incoming sizing constraint.
685    /// - `u32` - Expected node `content_gen`.
686    ///
687    /// # Returns
688    ///
689    /// - `bool` - `true` when the cached measurement is guaranteed exact for `space`.
690    #[must_use]
691    #[inline(always)]
692    pub(crate) fn matches(&self, space: AvailableSpace, expected_gen: u32) -> bool {
693        let Self {
694            occupied,
695            known_w,
696            known_h,
697            avail_w,
698            avail_h,
699            viewport_w,
700            viewport_h,
701            min_avail_w,
702            run_mode,
703            content_gen,
704            dep_flags,
705            ..
706        } = self;
707        if !*occupied || *content_gen != expected_gen {
708            return false;
709        }
710        let mode_compatible: bool = matches!(
711            *run_mode,
712            LayoutRunMode::ComputeSize | LayoutRunMode::PerformLayout
713        );
714        if !mode_compatible {
715            return false;
716        }
717        let (in_kw, in_kh): (f32, f32) = space.known_dimensions();
718        let kw_ok: bool = (known_w.is_nan() && in_kw.is_nan())
719            || (!known_w.is_nan() && !in_kw.is_nan() && (*known_w - in_kw).abs() <= 0.01);
720        if !kw_ok {
721            return false;
722        }
723        let kh_ok: bool = (known_h.is_nan() && in_kh.is_nan())
724            || (!known_h.is_nan() && !in_kh.is_nan() && (*known_h - in_kh).abs() <= 0.01);
725        if !kh_ok {
726            return false;
727        }
728        let in_aw: f32 = space.get_width();
729        let aw_ok: bool = if (*dep_flags & LAYOUT_DEP_AVAIL_W) != 0 {
730            (*avail_w - in_aw).abs() <= 0.01
731        } else {
732            in_aw >= *min_avail_w
733        };
734        if !aw_ok {
735            return false;
736        }
737        if (*dep_flags & LAYOUT_DEP_AVAIL_H) != 0 && (*avail_h - space.get_height()).abs() > 0.01 {
738            return false;
739        }
740        if (*dep_flags & LAYOUT_DEP_VIEWPORT) != 0 {
741            let vp: Size = space.get_viewport();
742            if (*viewport_w - vp.get_width()).abs() > 0.01
743                || (*viewport_h - vp.get_height()).abs() > 0.01
744            {
745                return false;
746            }
747        }
748        true
749    }
750}
751
752/// SoA layout cache, subtree-bounds, text-hash, and generation-stamped dedup operations.
753impl SplitLayoutCache {
754    /// Advances the layout pass epoch in O(1), clearing `invalidated_epochs` only on `u32` wrap-around.
755    ///
756    /// # Arguments
757    ///
758    /// - `&Self` - Mutable split layout cache.
759    #[inline(always)]
760    pub(crate) fn begin_pass(&mut self) {
761        let Self {
762            invalidated_epochs,
763            pass_epoch,
764            ..
765        } = self;
766        let next: u32 = pass_epoch.wrapping_add(1);
767        if next == 0 {
768            invalidated_epochs.fill(0);
769            *pass_epoch = 1;
770        } else {
771            *pass_epoch = next;
772        }
773    }
774
775    /// Advances the snapshot deduplication generation in O(1), clearing `snapshot_seen_gen` only on wrap-around.
776    ///
777    /// # Arguments
778    ///
779    /// - `&Self` - Mutable split layout cache.
780    #[inline(always)]
781    pub(crate) fn begin_snapshot_pass(&mut self) {
782        let Self {
783            snapshot_seen_gen,
784            snapshot_gen,
785            ..
786        } = self;
787        let next: u32 = snapshot_gen.wrapping_add(1);
788        if next == 0 {
789            snapshot_seen_gen.fill(0);
790            *snapshot_gen = 1;
791        } else {
792            *snapshot_gen = next;
793        }
794    }
795
796    /// Checks whether `node_id` has already been recorded in the active damage-tracking pass in O(1).
797    ///
798    /// # Arguments
799    ///
800    /// - `&Self` - Mutable split layout cache.
801    /// - `NodeId` - Target node handle.
802    ///
803    /// # Returns
804    ///
805    /// - `bool` - `true` when `node_id` was already recorded during the active pass.
806    #[must_use]
807    #[inline(always)]
808    pub(crate) fn is_snapshot_seen(&self, node_id: NodeId) -> bool {
809        let Self {
810            snapshot_seen_gen,
811            snapshot_gen,
812            ..
813        } = self;
814        let idx: usize = node_id.as_usize();
815        idx < snapshot_seen_gen.len() && snapshot_seen_gen[idx] == *snapshot_gen
816    }
817
818    /// Stamps `node_id` as recorded in the active damage-tracking pass in O(1).
819    ///
820    /// # Arguments
821    ///
822    /// - `&Self` - Mutable split layout cache.
823    /// - `NodeId` - Target node handle.
824    #[inline(always)]
825    pub(crate) fn mark_snapshot_seen(&mut self, node_id: NodeId) {
826        let Self {
827            snapshot_seen_gen,
828            snapshot_gen,
829            ..
830        } = self;
831        let idx: usize = node_id.as_usize();
832        if idx >= snapshot_seen_gen.len() {
833            snapshot_seen_gen.resize(idx + 1, 0);
834        }
835        snapshot_seen_gen[idx] = *snapshot_gen;
836    }
837
838    /// Ensures all parallel SoA vectors cover `idx` and resets stale slot metadata when `node_gen` changed.
839    ///
840    /// # Arguments
841    ///
842    /// - `&Self` - Mutable split layout cache.
843    /// - `NodeId` - Live scene node handle.
844    /// - `bool` - Whether the node currently carries any `DIRTY_LAYOUT_PASS_MASK` bit.
845    ///
846    /// # Returns
847    ///
848    /// - `(usize, u32)` - Arena index and active `content_gen` for `node_id`.
849    #[inline(always)]
850    pub(crate) fn prepare_node(&mut self, node_id: NodeId, is_dirty: bool) -> (usize, u32) {
851        let idx: usize = node_id.as_usize();
852        let node_gen: u32 = node_id.get_generation();
853        let Self {
854            node_gens,
855            content_gens,
856            invalidated_epochs,
857            measure_slots,
858            final_slots,
859            text_hashes,
860            subtree_bounds,
861            subtree_flags,
862            snapshot_seen_gen,
863            pass_epoch,
864            ..
865        } = self;
866        if idx >= node_gens.len() {
867            let new_len: usize = idx + 1;
868            node_gens.resize(new_len, 0);
869            content_gens.resize(new_len, 0);
870            invalidated_epochs.resize(new_len, 0);
871            measure_slots.resize(new_len, [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS]);
872            final_slots.resize(new_len, None);
873            text_hashes.resize(new_len, NodeTextHashSlot::default());
874            subtree_bounds.resize(new_len, Rect::default());
875            subtree_flags.resize(new_len, 0);
876            snapshot_seen_gen.resize(new_len, 0);
877        }
878        if node_gens[idx] != node_gen {
879            node_gens[idx] = node_gen;
880            content_gens[idx] = 1;
881            invalidated_epochs[idx] = *pass_epoch;
882            measure_slots[idx] = [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS];
883            final_slots[idx] = None;
884            text_hashes[idx] = NodeTextHashSlot::default();
885            subtree_bounds[idx] = Rect::default();
886            subtree_flags[idx] = 0;
887            return (idx, 1);
888        }
889        if is_dirty && invalidated_epochs[idx] != *pass_epoch {
890            let next_gen: u32 = content_gens[idx].wrapping_add(1).max(1);
891            content_gens[idx] = next_gen;
892            invalidated_epochs[idx] = *pass_epoch;
893            measure_slots[idx] = [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS];
894            final_slots[idx] = None;
895            return (idx, next_gen);
896        }
897        (idx, content_gens[idx])
898    }
899
900    /// Probes the 4-slot LRU `measure_slots[idx]` for a hit matching `(space, content_gen)` and promotes MRU.
901    ///
902    /// # Arguments
903    ///
904    /// - `&Self` - Mutable split layout cache.
905    /// - `usize` - Node arena index.
906    /// - `AvailableSpace` - Incoming sizing constraint.
907    /// - `u32` - Active node `content_gen`.
908    ///
909    /// # Returns
910    ///
911    /// - `Option<(Size, u8, f32)>` - Cached `(size, dep_flags, min_avail_w)` on hit.
912    #[inline(always)]
913    pub(crate) fn lookup_measure(
914        &mut self,
915        idx: usize,
916        space: AvailableSpace,
917        content_gen: u32,
918    ) -> Option<(Size, u8, f32)> {
919        let Self { measure_slots, .. } = self;
920        let slots: &mut [MeasureCacheSlot; MEASURE_CACHE_SLOTS] = &mut measure_slots[idx];
921        for pos in 0..MEASURE_CACHE_SLOTS {
922            if slots[pos].matches(space, content_gen) {
923                let hit: MeasureCacheSlot = slots[pos];
924                if pos > 0 {
925                    let mut shift: usize = pos;
926                    while shift > 0 {
927                        slots[shift] = slots[shift - 1];
928                        shift -= 1;
929                    }
930                    slots[0] = hit;
931                }
932                return Some((hit.size, hit.dep_flags, hit.min_avail_w));
933            }
934        }
935        None
936    }
937
938    /// Inserts a newly measured `(space, size, dep_flags, min_avail_w)` into the front of `measure_slots[idx]`.
939    ///
940    /// # Arguments
941    ///
942    /// - `&Self` - Mutable split layout cache.
943    /// - `usize` - Node arena index.
944    /// - `AvailableSpace` - Constraint under which `size` was computed.
945    /// - `LayoutRunMode` - Execution mode that produced this entry.
946    /// - `u32` - Active node `content_gen`.
947    /// - `(Size, u8, f32)` - Measured `(size, dep_flags, min_avail_w)` tuple.
948    #[inline(always)]
949    pub(crate) fn store_measure(
950        &mut self,
951        idx: usize,
952        space: AvailableSpace,
953        run_mode: LayoutRunMode,
954        content_gen: u32,
955        result: (Size, u8, f32),
956    ) {
957        let (size, dep_flags, min_avail_w): (Size, u8, f32) = result;
958        let (known_w, known_h): (f32, f32) = space.known_dimensions();
959        let vp: Size = space.get_viewport();
960        let new_slot: MeasureCacheSlot = MeasureCacheSlot {
961            occupied: true,
962            known_w,
963            known_h,
964            avail_w: space.get_width(),
965            avail_h: space.get_height(),
966            viewport_w: vp.get_width(),
967            viewport_h: vp.get_height(),
968            min_avail_w,
969            run_mode,
970            content_gen,
971            dep_flags,
972            size,
973        };
974        let Self { measure_slots, .. } = self;
975        let slots: &mut [MeasureCacheSlot; MEASURE_CACHE_SLOTS] = &mut measure_slots[idx];
976        slots[3] = slots[2];
977        slots[2] = slots[1];
978        slots[1] = slots[0];
979        slots[0] = new_slot;
980    }
981
982    /// Reads the cached `FinalLayoutSlot` at `idx` when matching `content_gen`.
983    ///
984    /// # Arguments
985    ///
986    /// - `&Self` - Split layout cache reference.
987    /// - `usize` - Node arena index.
988    /// - `u32` - Active node `content_gen`.
989    ///
990    /// # Returns
991    ///
992    /// - `Option<FinalLayoutSlot>` - Matching committed final layout slot, if valid.
993    #[must_use]
994    #[inline(always)]
995    pub(crate) fn lookup_final(&self, idx: usize, content_gen: u32) -> Option<FinalLayoutSlot> {
996        let Self { final_slots, .. } = self;
997        let slot: FinalLayoutSlot = final_slots[idx]?;
998        if slot.subtree_gen == content_gen {
999            Some(slot)
1000        } else {
1001            None
1002        }
1003    }
1004
1005    /// Writes `slot` into `final_slots[idx]` without touching `measure_slots[idx]`.
1006    ///
1007    /// # Arguments
1008    ///
1009    /// - `&Self` - Mutable split layout cache.
1010    /// - `usize` - Node arena index.
1011    /// - `FinalLayoutSlot` - Committed final layout snapshot.
1012    #[inline(always)]
1013    pub(crate) fn store_final(&mut self, idx: usize, slot: FinalLayoutSlot) {
1014        let Self { final_slots, .. } = self;
1015        final_slots[idx] = Some(slot);
1016    }
1017
1018    /// Marks `final_slots[idx]` as post-stretched by its parent and updates `subtree_bounds[idx]` to include `bounds`.
1019    ///
1020    /// # Arguments
1021    ///
1022    /// - `&Self` - Mutable split layout cache.
1023    /// - `NodeId` - Target child node handle.
1024    /// - `Rect` - Post-stretched border-box bounds.
1025    /// - `Transform2D` - Node paint transform.
1026    /// - `bool` - Whether the node clips descendants (`Overflow::Hidden | Scroll`).
1027    #[inline(always)]
1028    pub(crate) fn mark_post_stretched(
1029        &mut self,
1030        node_id: NodeId,
1031        bounds: Rect,
1032        transform: Transform2D,
1033        is_clipped: bool,
1034    ) {
1035        let idx: usize = node_id.as_usize();
1036        let Self {
1037            node_gens,
1038            final_slots,
1039            subtree_bounds,
1040            subtree_flags,
1041            ..
1042        } = self;
1043        if idx >= node_gens.len() || node_gens[idx] != node_id.get_generation() {
1044            return;
1045        }
1046        if let Some(slot) = final_slots[idx].as_mut() {
1047            slot.post_stretched = true;
1048        }
1049        let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), transform);
1050        if is_clipped || (subtree_flags[idx] & SUBTREE_FLAG_VALID) == 0 {
1051            subtree_bounds[idx] = own_vis;
1052            subtree_flags[idx] |= SUBTREE_FLAG_VALID;
1053        } else {
1054            subtree_bounds[idx] = subtree_bounds[idx].union(own_vis);
1055        }
1056    }
1057
1058    /// Returns or computes the cached 128-bit text hash for `node_id` without re-hashing unchanged text.
1059    ///
1060    /// # Arguments
1061    ///
1062    /// - `&Self` - Mutable split layout cache.
1063    /// - `NodeId` - Target text or input node handle.
1064    /// - `&str` - Active UTF-8 text slice.
1065    /// - `bool` - Whether `DIRTY_TEXT` is set on the node.
1066    ///
1067    /// # Returns
1068    ///
1069    /// - `Option<(u64, u64, u32, bool)>` - `(hash_a, hash_b, text_len, reused)` tuple where `reused` is `true` on hash cache hit.
1070    #[inline(always)]
1071    pub(crate) fn text_hash_for_node(
1072        &mut self,
1073        node_id: NodeId,
1074        text: &str,
1075        dirty_text: bool,
1076    ) -> Option<(u64, u64, u32, bool)> {
1077        let text_len: u32 = u32::try_from(text.len()).ok()?;
1078        let text_ptr: usize = text.as_ptr() as usize;
1079        let idx: usize = node_id.as_usize();
1080        let node_gen: u32 = node_id.get_generation();
1081        let Self { text_hashes, .. } = self;
1082        if idx >= text_hashes.len() {
1083            text_hashes.resize(idx + 1, NodeTextHashSlot::default());
1084        }
1085        let slot: &mut NodeTextHashSlot = &mut text_hashes[idx];
1086        if !dirty_text
1087            && slot.node_gen == node_gen
1088            && slot.text_len == text_len
1089            && slot.text_ptr == text_ptr
1090        {
1091            return Some((slot.hash_a, slot.hash_b, text_len, true));
1092        }
1093        let (hash_a, hash_b): (u64, u64) = TextSizeCache::hash_text_128(text.as_bytes());
1094        slot.node_gen = node_gen;
1095        slot.hash_a = hash_a;
1096        slot.hash_b = hash_b;
1097        slot.text_len = text_len;
1098        slot.text_ptr = text_ptr;
1099        Some((hash_a, hash_b, text_len, false))
1100    }
1101
1102    /// Shifts cached `final_slot` and `subtree_bounds` for `node_id` by `(dx, dy)` during subtree translation.
1103    ///
1104    /// # Arguments
1105    ///
1106    /// - `&Self` - Mutable split layout cache.
1107    /// - `NodeId` - Translated node handle.
1108    /// - `f32` - Horizontal delta in logical pixels.
1109    /// - `f32` - Vertical delta in logical pixels.
1110    #[inline(always)]
1111    pub(crate) fn translate_node_cache(&mut self, node_id: NodeId, dx: f32, dy: f32) {
1112        let idx: usize = node_id.as_usize();
1113        let Self {
1114            node_gens,
1115            final_slots,
1116            subtree_bounds,
1117            subtree_flags,
1118            ..
1119        } = self;
1120        if idx >= node_gens.len() || node_gens[idx] != node_id.get_generation() {
1121            return;
1122        }
1123        if let Some(slot) = final_slots[idx].as_mut() {
1124            slot.space.set_origin_x(slot.space.get_origin_x() + dx);
1125            slot.space.set_origin_y(slot.space.get_origin_y() + dy);
1126            slot.bounds.set_x(slot.bounds.get_x() + dx);
1127            slot.bounds.set_y(slot.bounds.get_y() + dy);
1128            slot.content_bounds.set_x(slot.content_bounds.get_x() + dx);
1129            slot.content_bounds.set_y(slot.content_bounds.get_y() + dy);
1130        }
1131        if (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0 {
1132            let next_x: f32 = subtree_bounds[idx].get_x() + dx;
1133            let next_y: f32 = subtree_bounds[idx].get_y() + dy;
1134            subtree_bounds[idx].set_x(next_x);
1135            subtree_bounds[idx].set_y(next_y);
1136        }
1137    }
1138
1139    /// Stores the computed spatial `subtree_bounds` and `has_nonzero_z_child` flag for `node_id`.
1140    ///
1141    /// # Arguments
1142    ///
1143    /// - `&Self` - Mutable split layout cache.
1144    /// - `usize` - Node arena index.
1145    /// - `Rect` - Computed subtree visual/interactive bounds in root logical coordinates.
1146    /// - `bool` - Whether any immediate child has `z_index != 0`.
1147    #[inline(always)]
1148    pub(crate) fn store_subtree_meta(
1149        &mut self,
1150        idx: usize,
1151        bounds: Rect,
1152        has_nonzero_z_child: bool,
1153    ) {
1154        let Self {
1155            subtree_bounds,
1156            subtree_flags,
1157            ..
1158        } = self;
1159        subtree_bounds[idx] = bounds;
1160        let mut flags: u8 = SUBTREE_FLAG_VALID;
1161        if has_nonzero_z_child {
1162            flags |= SUBTREE_FLAG_NONZERO_Z_CHILD;
1163        }
1164        subtree_flags[idx] = flags;
1165    }
1166
1167    /// Reads the cached `subtree_bounds` for `node_id` if valid for its generation.
1168    ///
1169    /// # Arguments
1170    ///
1171    /// - `&Self` - Split layout cache reference.
1172    /// - `NodeId` - Target node handle.
1173    ///
1174    /// # Returns
1175    ///
1176    /// - `Option<Rect>` - Cached subtree bounds in root logical coordinates, if populated and valid.
1177    #[must_use]
1178    #[inline(always)]
1179    pub(crate) fn subtree_bounds_for(&self, node_id: NodeId) -> Option<Rect> {
1180        let idx: usize = node_id.as_usize();
1181        let Self {
1182            node_gens,
1183            subtree_bounds,
1184            subtree_flags,
1185            ..
1186        } = self;
1187        if idx < node_gens.len()
1188            && node_gens[idx] == node_id.get_generation()
1189            && (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0
1190        {
1191            Some(subtree_bounds[idx])
1192        } else {
1193            None
1194        }
1195    }
1196
1197    /// Returns whether `node_id` has a cached `has_nonzero_z_child == false` guarantee for fast-path hit testing.
1198    ///
1199    /// # Arguments
1200    ///
1201    /// - `&Self` - Split layout cache reference.
1202    /// - `NodeId` - Container node handle.
1203    ///
1204    /// # Returns
1205    ///
1206    /// - `Option<bool>` - `Some(has_nonzero_z_child)` when valid metadata is cached for `node_id`.
1207    #[must_use]
1208    #[inline(always)]
1209    pub(crate) fn has_nonzero_z_child(&self, node_id: NodeId) -> Option<bool> {
1210        let idx: usize = node_id.as_usize();
1211        let Self {
1212            node_gens,
1213            subtree_flags,
1214            ..
1215        } = self;
1216        if idx < node_gens.len()
1217            && node_gens[idx] == node_id.get_generation()
1218            && (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0
1219        {
1220            Some((subtree_flags[idx] & SUBTREE_FLAG_NONZERO_Z_CHILD) != 0)
1221        } else {
1222            None
1223        }
1224    }
1225
1226    /// Stamps the synced `SceneTree` root and revision after a completed layout pass.
1227    ///
1228    /// # Arguments
1229    ///
1230    /// - `&Self` - Mutable split layout cache.
1231    /// - `NodeId` - Laid-out scene root handle.
1232    /// - `u64` - `SceneTree::revision` snapshot.
1233    #[inline(always)]
1234    pub(crate) fn mark_synced(&mut self, root: NodeId, revision: u64) {
1235        let Self {
1236            synced_root,
1237            synced_tree_revision,
1238            ..
1239        } = self;
1240        *synced_root = root;
1241        *synced_tree_revision = revision;
1242    }
1243
1244    /// Checks whether cached `subtree_bounds` and `has_nonzero_z_child` are strictly synchronized with `tree`.
1245    ///
1246    /// # Arguments
1247    ///
1248    /// - `&Self` - Split layout cache reference.
1249    /// - `&SceneTree` - Live scene tree being hit-tested.
1250    ///
1251    /// # Returns
1252    ///
1253    /// - `bool` - `true` when `tree` has not been mutated since the last layout pass on the same root.
1254    #[must_use]
1255    #[inline(always)]
1256    pub(crate) fn is_synced_with(&self, tree: &SceneTree) -> bool {
1257        let Self {
1258            synced_root,
1259            synced_tree_revision,
1260            ..
1261        } = self;
1262        *synced_root == tree.get_root()
1263            && *synced_tree_revision == tree.get_revision()
1264            && synced_root.is_valid()
1265    }
1266}