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    /// - `CallbackFn` - 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<CallbackFn>(
248        &mut self,
249        text: &str,
250        text_key: (u64, u64, u32),
251        style: TextStyle,
252        max_width: Option<f32>,
253        mut measure_fn: CallbackFn,
254    ) -> TextSizeMeasurement
255    where
256        CallbackFn: 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(width_val) if width_val.is_nan() => Some(0.0),
309            other => other,
310        };
311        let max_w_bits: u32 = match effective_limit {
312            Some(span_width) => Self::normalize_f32_bits(span_width),
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> =
384                    effective_limit.filter(|weight_val: &f32| *weight_val > 0.0);
385                let Some(limit) = active_limit else {
386                    if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_NONE) != 0 {
387                        return TextSizeMeasurement {
388                            size: Size::new(entry.none_w, entry.none_h),
389                            unwrapped: true,
390                            max_content_w: entry.none_w,
391                            cache_hit: true,
392                        };
393                    }
394                    let measured: Size = measure_fn(text, style, None);
395                    entry.none_w = measured.get_width();
396                    entry.none_h = measured.get_height();
397                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_NONE;
398                    if !Self::has_line_edge_spaces(text) {
399                        entry.max_content_w = measured.get_width();
400                        entry.single_line_h = measured.get_height();
401                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_UNWRAPPED;
402                    }
403                    return TextSizeMeasurement {
404                        size: measured,
405                        unwrapped: true,
406                        max_content_w: measured.get_width(),
407                        cache_hit: false,
408                    };
409                };
410                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
411                    && (limit >= entry.max_content_w
412                        || ((entry.entry_flags & TEXT_SIZE_ENTRY_HAS_MIN_CONTENT) != 0
413                            && (entry.min_content_w - entry.max_content_w).abs() <= 0.001))
414                {
415                    return TextSizeMeasurement {
416                        size: Size::new(entry.max_content_w, entry.single_line_h),
417                        unwrapped: true,
418                        max_content_w: entry.max_content_w,
419                        cache_hit: true,
420                    };
421                }
422                if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_WRAPPED) != 0
423                    && entry.last_max_w_bits == max_w_bits
424                {
425                    let known_max: f32 = if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
426                    {
427                        entry.max_content_w
428                    } else {
429                        f32::INFINITY
430                    };
431                    return TextSizeMeasurement {
432                        size: Size::new(entry.last_wrapped_w, entry.last_wrapped_h),
433                        unwrapped: false,
434                        max_content_w: known_max,
435                        cache_hit: true,
436                    };
437                }
438                let measured: Size = measure_fn(text, style, Some(limit));
439                let line_h: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
440                let expected_h: f32 = (Self::count_raw_lines(text) as f32) * line_h;
441                if (measured.get_height() - expected_h).abs() <= 0.01 {
442                    entry.max_content_w = measured.get_width();
443                    entry.single_line_h = measured.get_height();
444                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_UNWRAPPED;
445                    if measured.get_width() > limit {
446                        entry.min_content_w = measured.get_width();
447                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_MIN_CONTENT;
448                    }
449                    TextSizeMeasurement {
450                        size: measured,
451                        unwrapped: true,
452                        max_content_w: entry.max_content_w,
453                        cache_hit: false,
454                    }
455                } else {
456                    entry.last_max_w_bits = max_w_bits;
457                    entry.last_wrapped_w = measured.get_width();
458                    entry.last_wrapped_h = measured.get_height();
459                    entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_WRAPPED;
460                    if limit <= 1.01 {
461                        entry.min_content_w = measured.get_width();
462                        entry.entry_flags |= TEXT_SIZE_ENTRY_HAS_MIN_CONTENT;
463                    }
464                    let known_max: f32 = if (entry.entry_flags & TEXT_SIZE_ENTRY_HAS_UNWRAPPED) != 0
465                    {
466                        entry.max_content_w
467                    } else {
468                        f32::INFINITY
469                    };
470                    TextSizeMeasurement {
471                        size: measured,
472                        unwrapped: false,
473                        max_content_w: known_max,
474                        cache_hit: false,
475                    }
476                }
477            }
478        }
479    }
480
481    /// Computes two independent 64-bit hashes over `bytes` in a single 8-byte-chunked pass.
482    ///
483    /// # Arguments
484    ///
485    /// - `&[u8]` - UTF-8 input bytes.
486    ///
487    /// # Returns
488    ///
489    /// - `(u64, u64)` - Pair of independent 64-bit hashes with avalanche mixing.
490    #[inline(always)]
491    pub(crate) fn hash_text_128(bytes: &[u8]) -> (u64, u64) {
492        let len: usize = bytes.len();
493        let len_u64: u64 = len as u64;
494        let mut h1: u64 = TEXT_HASH_SEED_A ^ len_u64;
495        let mut h2: u64 = TEXT_HASH_SEED_B ^ len_u64.wrapping_mul(TEXT_HASH_PRIME_B);
496        let mut offset: usize = 0;
497        while offset + 8 <= len {
498            let word: u64 = u64::from_le_bytes([
499                bytes[offset],
500                bytes[offset + 1],
501                bytes[offset + 2],
502                bytes[offset + 3],
503                bytes[offset + 4],
504                bytes[offset + 5],
505                bytes[offset + 6],
506                bytes[offset + 7],
507            ]);
508            h1 = (h1 ^ word).wrapping_mul(TEXT_HASH_PRIME_A);
509            h2 = (h2.rotate_left(27) ^ word).wrapping_mul(TEXT_HASH_PRIME_B);
510            offset += 8;
511        }
512        let mut tail: u64 = 0;
513        let mut shift: u32 = 0;
514        while offset < len {
515            tail |= (bytes[offset] as u64) << shift;
516            shift += 8;
517            offset += 1;
518        }
519        h1 = (h1 ^ tail).wrapping_mul(TEXT_HASH_PRIME_A);
520        h2 = (h2.rotate_left(27) ^ tail).wrapping_mul(TEXT_HASH_PRIME_B);
521        h1 ^= h1 >> 33;
522        h1 = h1.wrapping_mul(TEXT_HASH_FINAL_A);
523        h1 ^= h1 >> 33;
524        h2 ^= h2 >> 31;
525        h2 = h2.wrapping_mul(TEXT_HASH_FINAL_B);
526        h2 ^= h2 >> 31;
527        (h1, h2)
528    }
529
530    /// Checks whether a cached `TextSizeEntry` matches the `(hash_a, hash_b, text_len, style_key)` key.
531    ///
532    /// # Arguments
533    ///
534    /// - `TextSizeEntry` - Candidate cache entry.
535    /// - `u64` - Primary text hash.
536    /// - `u64` - Secondary text hash.
537    /// - `u32` - Text byte length.
538    /// - `TextStyleKey` - Packed typography key.
539    ///
540    /// # Returns
541    ///
542    /// - `bool` - `true` when the entry is occupied and matches all key components.
543    #[inline(always)]
544    fn entry_key_matches(
545        entry: TextSizeEntry,
546        hash_a: u64,
547        hash_b: u64,
548        text_len: u32,
549        style_key: TextStyleKey,
550    ) -> bool {
551        entry.style_key == style_key
552            && entry.text_len == text_len
553            && entry.hash_a == hash_a
554            && entry.hash_b == hash_b
555    }
556
557    /// Packs a `TextStyle` into a compact `TextStyleKey` with `TEXT_SIZE_ENTRY_OCCUPIED` set.
558    ///
559    /// # Arguments
560    ///
561    /// - `TextStyle` - Source typography style.
562    ///
563    /// # Returns
564    ///
565    /// - `TextStyleKey` - Normalized typography key.
566    #[inline(always)]
567    fn build_style_key(style: TextStyle) -> TextStyleKey {
568        TextStyleKey {
569            font_size_bits: Self::normalize_f32_bits(style.get_font_size()),
570            line_height_bits: Self::normalize_f32_bits(style.get_line_height()),
571            letter_spacing_bits: Self::normalize_f32_bits(style.get_letter_spacing()),
572            style_flags: Self::pack_style_flags(style),
573        }
574    }
575
576    /// Counts explicit `\n`-delimited raw lines in `text`.
577    ///
578    /// # Arguments
579    ///
580    /// - `&str` - Input UTF-8 string.
581    ///
582    /// # Returns
583    ///
584    /// - `usize` - Number of raw lines (`>= 1`).
585    #[inline(always)]
586    fn count_raw_lines(text: &str) -> usize {
587        let bytes: &[u8] = text.as_bytes();
588        if !bytes.contains(&b'\n') {
589            return 1;
590        }
591        let mut count: usize = 1;
592        for &blue_val in bytes.iter() {
593            if blue_val == b'\n' {
594                count += 1;
595            }
596        }
597        count
598    }
599
600    /// Checks whether any `\n`-delimited line in `text` begins or ends with an ASCII space.
601    ///
602    /// # Arguments
603    ///
604    /// - `&str` - Input UTF-8 string.
605    ///
606    /// # Returns
607    ///
608    /// - `bool` - `true` when leading or trailing spaces could differentiate `None` vs wrapped widths.
609    #[inline(always)]
610    fn has_line_edge_spaces(text: &str) -> bool {
611        let bytes: &[u8] = text.as_bytes();
612        if bytes.is_empty() {
613            return false;
614        }
615        if !bytes.contains(&b'\n') {
616            return bytes[0] == b' ' || bytes[bytes.len() - 1] == b' ';
617        }
618        for line in text.split('\n') {
619            let lb: &[u8] = line.as_bytes();
620            if !lb.is_empty() && (lb[0] == b' ' || lb[lb.len() - 1] == b' ') {
621                return true;
622            }
623        }
624        false
625    }
626
627    /// Normalizes floating-point bits so `-0.0` and `+0.0` map identically.
628    ///
629    /// # Arguments
630    ///
631    /// - `f32` - Input scalar value.
632    ///
633    /// # Returns
634    ///
635    /// - `u32` - Normalized IEEE-754 bit pattern.
636    #[inline(always)]
637    fn normalize_f32_bits(value: f32) -> u32 {
638        if value == 0.0 { 0 } else { value.to_bits() }
639    }
640
641    /// Packs layout-relevant discrete typography flags plus the occupied marker bit into `u16`.
642    ///
643    /// # Arguments
644    ///
645    /// - `TextStyle` - Source typography style.
646    ///
647    /// # Returns
648    ///
649    /// - `u16` - Packed flag bitfield with `TEXT_SIZE_ENTRY_OCCUPIED` set.
650    #[inline(always)]
651    fn pack_style_flags(style: TextStyle) -> u16 {
652        let family_bits: u16 = match style.get_family() {
653            FontFamily::Sans => 0,
654            FontFamily::Monospace => 1,
655            FontFamily::Serif => 2,
656        };
657        let weight_bits: u16 = match style.get_weight() {
658            FontWeight::Light => 0,
659            FontWeight::Normal => 1,
660            FontWeight::Medium => 2,
661            FontWeight::SemiBold => 3,
662            FontWeight::Bold => 4,
663        };
664        let overflow_bits: u16 = match style.get_overflow() {
665            TextOverflow::Wrap => 0,
666            TextOverflow::Clip => 1,
667            TextOverflow::Ellipsis => 2,
668        };
669        let italic_bit: u16 = if style.get_italic() { 1 } else { 0 };
670        TEXT_SIZE_ENTRY_OCCUPIED
671            | family_bits
672            | (weight_bits << 2)
673            | (overflow_bits << 5)
674            | (italic_bit << 7)
675    }
676}
677
678/// Matching helpers for `MeasureCacheSlot`.
679impl MeasureCacheSlot {
680    /// Checks whether this LRU measure slot matches an incoming constraint and content generation.
681    ///
682    /// # Arguments
683    ///
684    /// - `&Self` - Candidate measure cache slot.
685    /// - `AvailableSpace` - Incoming sizing constraint.
686    /// - `u32` - Expected node `content_gen`.
687    ///
688    /// # Returns
689    ///
690    /// - `bool` - `true` when the cached measurement is guaranteed exact for `space`.
691    #[must_use]
692    #[inline(always)]
693    pub(crate) fn matches(&self, space: AvailableSpace, expected_gen: u32) -> bool {
694        let Self {
695            occupied,
696            known_w,
697            known_h,
698            avail_w,
699            avail_h,
700            viewport_w,
701            viewport_h,
702            min_avail_w,
703            run_mode,
704            content_gen,
705            dep_flags,
706            ..
707        } = self;
708        if !*occupied || *content_gen != expected_gen {
709            return false;
710        }
711        let mode_compatible: bool = matches!(
712            *run_mode,
713            LayoutRunMode::ComputeSize | LayoutRunMode::PerformLayout
714        );
715        if !mode_compatible {
716            return false;
717        }
718        let (in_kw, in_kh): (f32, f32) = space.known_dimensions();
719        let kw_ok: bool = (known_w.is_nan() && in_kw.is_nan())
720            || (!known_w.is_nan() && !in_kw.is_nan() && (*known_w - in_kw).abs() <= 0.01);
721        if !kw_ok {
722            return false;
723        }
724        let kh_ok: bool = (known_h.is_nan() && in_kh.is_nan())
725            || (!known_h.is_nan() && !in_kh.is_nan() && (*known_h - in_kh).abs() <= 0.01);
726        if !kh_ok {
727            return false;
728        }
729        let in_aw: f32 = space.get_width();
730        let aw_ok: bool = if (*dep_flags & LAYOUT_DEP_AVAIL_W) != 0 {
731            (*avail_w - in_aw).abs() <= 0.01
732        } else {
733            in_aw >= *min_avail_w
734        };
735        if !aw_ok {
736            return false;
737        }
738        if (*dep_flags & LAYOUT_DEP_AVAIL_H) != 0 && (*avail_h - space.get_height()).abs() > 0.01 {
739            return false;
740        }
741        if (*dep_flags & LAYOUT_DEP_VIEWPORT) != 0 {
742            let box_size: Size = space.get_viewport();
743            if (*viewport_w - box_size.get_width()).abs() > 0.01
744                || (*viewport_h - box_size.get_height()).abs() > 0.01
745            {
746                return false;
747            }
748        }
749        true
750    }
751}
752
753/// SoA layout cache, subtree-bounds, text-hash, and generation-stamped dedup operations.
754impl SplitLayoutCache {
755    /// Advances the layout pass epoch in O(1), clearing `invalidated_epochs` only on `u32` wrap-around.
756    ///
757    /// # Arguments
758    ///
759    /// - `&Self` - Mutable split layout cache.
760    #[inline(always)]
761    pub(crate) fn begin_pass(&mut self) {
762        let Self {
763            invalidated_epochs,
764            pass_epoch,
765            ..
766        } = self;
767        let next: u32 = pass_epoch.wrapping_add(1);
768        if next == 0 {
769            invalidated_epochs.fill(0);
770            *pass_epoch = 1;
771        } else {
772            *pass_epoch = next;
773        }
774    }
775
776    /// Advances the snapshot deduplication generation in O(1), clearing `snapshot_seen_gen` only on wrap-around.
777    ///
778    /// # Arguments
779    ///
780    /// - `&Self` - Mutable split layout cache.
781    #[inline(always)]
782    pub(crate) fn begin_snapshot_pass(&mut self) {
783        let Self {
784            snapshot_seen_gen,
785            snapshot_gen,
786            ..
787        } = self;
788        let next: u32 = snapshot_gen.wrapping_add(1);
789        if next == 0 {
790            snapshot_seen_gen.fill(0);
791            *snapshot_gen = 1;
792        } else {
793            *snapshot_gen = next;
794        }
795    }
796
797    /// Checks whether `node_id` has already been recorded in the active damage-tracking pass in O(1).
798    ///
799    /// # Arguments
800    ///
801    /// - `&Self` - Mutable split layout cache.
802    /// - `NodeId` - Target node handle.
803    ///
804    /// # Returns
805    ///
806    /// - `bool` - `true` when `node_id` was already recorded during the active pass.
807    #[must_use]
808    #[inline(always)]
809    pub(crate) fn is_snapshot_seen(&self, node_id: NodeId) -> bool {
810        let Self {
811            snapshot_seen_gen,
812            snapshot_gen,
813            ..
814        } = self;
815        let idx: usize = node_id.as_usize();
816        idx < snapshot_seen_gen.len() && snapshot_seen_gen[idx] == *snapshot_gen
817    }
818
819    /// Stamps `node_id` as recorded in the active damage-tracking pass in O(1).
820    ///
821    /// # Arguments
822    ///
823    /// - `&Self` - Mutable split layout cache.
824    /// - `NodeId` - Target node handle.
825    #[inline(always)]
826    pub(crate) fn mark_snapshot_seen(&mut self, node_id: NodeId) {
827        let Self {
828            snapshot_seen_gen,
829            snapshot_gen,
830            ..
831        } = self;
832        let idx: usize = node_id.as_usize();
833        if idx >= snapshot_seen_gen.len() {
834            snapshot_seen_gen.resize(idx + 1, 0);
835        }
836        snapshot_seen_gen[idx] = *snapshot_gen;
837    }
838
839    /// Ensures all parallel SoA vectors cover `idx` and resets stale slot metadata when `node_gen` changed.
840    ///
841    /// # Arguments
842    ///
843    /// - `&Self` - Mutable split layout cache.
844    /// - `NodeId` - Live scene node handle.
845    /// - `bool` - Whether the node currently carries any `DIRTY_LAYOUT_PASS_MASK` bit.
846    ///
847    /// # Returns
848    ///
849    /// - `(usize, u32)` - Arena index and active `content_gen` for `node_id`.
850    #[inline(always)]
851    pub(crate) fn prepare_node(&mut self, node_id: NodeId, is_dirty: bool) -> (usize, u32) {
852        let idx: usize = node_id.as_usize();
853        let node_gen: u32 = node_id.get_generation();
854        let Self {
855            node_gens,
856            content_gens,
857            invalidated_epochs,
858            measure_slots,
859            final_slots,
860            text_hashes,
861            subtree_bounds,
862            subtree_flags,
863            snapshot_seen_gen,
864            pass_epoch,
865            ..
866        } = self;
867        if idx >= node_gens.len() {
868            let new_len: usize = idx + 1;
869            node_gens.resize(new_len, 0);
870            content_gens.resize(new_len, 0);
871            invalidated_epochs.resize(new_len, 0);
872            measure_slots.resize(new_len, [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS]);
873            final_slots.resize(new_len, None);
874            text_hashes.resize(new_len, NodeTextHashSlot::default());
875            subtree_bounds.resize(new_len, Rect::default());
876            subtree_flags.resize(new_len, 0);
877            snapshot_seen_gen.resize(new_len, 0);
878        }
879        if node_gens[idx] != node_gen {
880            node_gens[idx] = node_gen;
881            content_gens[idx] = 1;
882            invalidated_epochs[idx] = *pass_epoch;
883            measure_slots[idx] = [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS];
884            final_slots[idx] = None;
885            text_hashes[idx] = NodeTextHashSlot::default();
886            subtree_bounds[idx] = Rect::default();
887            subtree_flags[idx] = 0;
888            return (idx, 1);
889        }
890        if is_dirty && invalidated_epochs[idx] != *pass_epoch {
891            let next_gen: u32 = content_gens[idx].wrapping_add(1).max(1);
892            content_gens[idx] = next_gen;
893            invalidated_epochs[idx] = *pass_epoch;
894            measure_slots[idx] = [MeasureCacheSlot::default(); MEASURE_CACHE_SLOTS];
895            final_slots[idx] = None;
896            return (idx, next_gen);
897        }
898        (idx, content_gens[idx])
899    }
900
901    /// Probes the 4-slot LRU `measure_slots[idx]` for a hit matching `(space, content_gen)` and promotes MRU.
902    ///
903    /// # Arguments
904    ///
905    /// - `&Self` - Mutable split layout cache.
906    /// - `usize` - Node arena index.
907    /// - `AvailableSpace` - Incoming sizing constraint.
908    /// - `u32` - Active node `content_gen`.
909    ///
910    /// # Returns
911    ///
912    /// - `Option<(Size, u8, f32)>` - Cached `(size, dep_flags, min_avail_w)` on hit.
913    #[inline(always)]
914    pub(crate) fn lookup_measure(
915        &mut self,
916        idx: usize,
917        space: AvailableSpace,
918        content_gen: u32,
919    ) -> Option<(Size, u8, f32)> {
920        let Self { measure_slots, .. } = self;
921        let slots: &mut [MeasureCacheSlot; MEASURE_CACHE_SLOTS] = &mut measure_slots[idx];
922        for pos in 0..MEASURE_CACHE_SLOTS {
923            if slots[pos].matches(space, content_gen) {
924                let hit: MeasureCacheSlot = slots[pos];
925                if pos > 0 {
926                    let mut shift: usize = pos;
927                    while shift > 0 {
928                        slots[shift] = slots[shift - 1];
929                        shift -= 1;
930                    }
931                    slots[0] = hit;
932                }
933                return Some((hit.size, hit.dep_flags, hit.min_avail_w));
934            }
935        }
936        None
937    }
938
939    /// Inserts a newly measured `(space, size, dep_flags, min_avail_w)` into the front of `measure_slots[idx]`.
940    ///
941    /// # Arguments
942    ///
943    /// - `&Self` - Mutable split layout cache.
944    /// - `usize` - Node arena index.
945    /// - `AvailableSpace` - Constraint under which `size` was computed.
946    /// - `LayoutRunMode` - Execution mode that produced this entry.
947    /// - `u32` - Active node `content_gen`.
948    /// - `(Size, u8, f32)` - Measured `(size, dep_flags, min_avail_w)` tuple.
949    #[inline(always)]
950    pub(crate) fn store_measure(
951        &mut self,
952        idx: usize,
953        space: AvailableSpace,
954        run_mode: LayoutRunMode,
955        content_gen: u32,
956        result: (Size, u8, f32),
957    ) {
958        let (size, dep_flags, min_avail_w): (Size, u8, f32) = result;
959        let (known_w, known_h): (f32, f32) = space.known_dimensions();
960        let box_size: Size = space.get_viewport();
961        let new_slot: MeasureCacheSlot = MeasureCacheSlot {
962            occupied: true,
963            known_w,
964            known_h,
965            avail_w: space.get_width(),
966            avail_h: space.get_height(),
967            viewport_w: box_size.get_width(),
968            viewport_h: box_size.get_height(),
969            min_avail_w,
970            run_mode,
971            content_gen,
972            dep_flags,
973            size,
974        };
975        let Self { measure_slots, .. } = self;
976        let slots: &mut [MeasureCacheSlot; MEASURE_CACHE_SLOTS] = &mut measure_slots[idx];
977        slots[3] = slots[2];
978        slots[2] = slots[1];
979        slots[1] = slots[0];
980        slots[0] = new_slot;
981    }
982
983    /// Reads the cached `FinalLayoutSlot` at `idx` when matching `content_gen`.
984    ///
985    /// # Arguments
986    ///
987    /// - `&Self` - Split layout cache reference.
988    /// - `usize` - Node arena index.
989    /// - `u32` - Active node `content_gen`.
990    ///
991    /// # Returns
992    ///
993    /// - `Option<FinalLayoutSlot>` - Matching committed final layout slot, if valid.
994    #[must_use]
995    #[inline(always)]
996    pub(crate) fn lookup_final(&self, idx: usize, content_gen: u32) -> Option<FinalLayoutSlot> {
997        let Self { final_slots, .. } = self;
998        let slot: FinalLayoutSlot = final_slots[idx]?;
999        if slot.subtree_gen == content_gen {
1000            Some(slot)
1001        } else {
1002            None
1003        }
1004    }
1005
1006    /// Writes `slot` into `final_slots[idx]` without touching `measure_slots[idx]`.
1007    ///
1008    /// # Arguments
1009    ///
1010    /// - `&Self` - Mutable split layout cache.
1011    /// - `usize` - Node arena index.
1012    /// - `FinalLayoutSlot` - Committed final layout snapshot.
1013    #[inline(always)]
1014    pub(crate) fn store_final(&mut self, idx: usize, slot: FinalLayoutSlot) {
1015        let Self { final_slots, .. } = self;
1016        final_slots[idx] = Some(slot);
1017    }
1018
1019    /// Marks `final_slots[idx]` as post-stretched by its parent and updates `subtree_bounds[idx]` to include `bounds`.
1020    ///
1021    /// # Arguments
1022    ///
1023    /// - `&Self` - Mutable split layout cache.
1024    /// - `NodeId` - Target child node handle.
1025    /// - `Rect` - Post-stretched border-box bounds.
1026    /// - `Transform2D` - Node paint transform.
1027    /// - `bool` - Whether the node clips descendants (`Overflow::Hidden | Scroll`).
1028    #[inline(always)]
1029    pub(crate) fn mark_post_stretched(
1030        &mut self,
1031        node_id: NodeId,
1032        bounds: Rect,
1033        transform: Transform2D,
1034        is_clipped: bool,
1035    ) {
1036        let idx: usize = node_id.as_usize();
1037        let Self {
1038            node_gens,
1039            final_slots,
1040            subtree_bounds,
1041            subtree_flags,
1042            ..
1043        } = self;
1044        if idx >= node_gens.len() || node_gens[idx] != node_id.get_generation() {
1045            return;
1046        }
1047        if let Some(slot) = final_slots[idx].as_mut() {
1048            slot.post_stretched = true;
1049        }
1050        let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), transform);
1051        if is_clipped || (subtree_flags[idx] & SUBTREE_FLAG_VALID) == 0 {
1052            subtree_bounds[idx] = own_vis;
1053            subtree_flags[idx] |= SUBTREE_FLAG_VALID;
1054        } else {
1055            subtree_bounds[idx] = subtree_bounds[idx].union(own_vis);
1056        }
1057    }
1058
1059    /// Returns or computes the cached 128-bit text hash for `node_id` without re-hashing unchanged text.
1060    ///
1061    /// # Arguments
1062    ///
1063    /// - `&Self` - Mutable split layout cache.
1064    /// - `NodeId` - Target text or input node handle.
1065    /// - `&str` - Active UTF-8 text slice.
1066    /// - `bool` - Whether `DIRTY_TEXT` is set on the node.
1067    ///
1068    /// # Returns
1069    ///
1070    /// - `Option<(u64, u64, u32, bool)>` - `(hash_a, hash_b, text_len, reused)` tuple where `reused` is `true` on hash cache hit.
1071    #[inline(always)]
1072    pub(crate) fn text_hash_for_node(
1073        &mut self,
1074        node_id: NodeId,
1075        text: &str,
1076        dirty_text: bool,
1077    ) -> Option<(u64, u64, u32, bool)> {
1078        let text_len: u32 = u32::try_from(text.len()).ok()?;
1079        let text_ptr: usize = text.as_ptr() as usize;
1080        let idx: usize = node_id.as_usize();
1081        let node_gen: u32 = node_id.get_generation();
1082        let Self { text_hashes, .. } = self;
1083        if idx >= text_hashes.len() {
1084            text_hashes.resize(idx + 1, NodeTextHashSlot::default());
1085        }
1086        let slot: &mut NodeTextHashSlot = &mut text_hashes[idx];
1087        if !dirty_text
1088            && slot.node_gen == node_gen
1089            && slot.text_len == text_len
1090            && slot.text_ptr == text_ptr
1091        {
1092            return Some((slot.hash_a, slot.hash_b, text_len, true));
1093        }
1094        let (hash_a, hash_b): (u64, u64) = TextSizeCache::hash_text_128(text.as_bytes());
1095        slot.node_gen = node_gen;
1096        slot.hash_a = hash_a;
1097        slot.hash_b = hash_b;
1098        slot.text_len = text_len;
1099        slot.text_ptr = text_ptr;
1100        Some((hash_a, hash_b, text_len, false))
1101    }
1102
1103    /// Shifts cached `final_slot` and `subtree_bounds` for `node_id` by `(dx, dy)` during subtree translation.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// - `&Self` - Mutable split layout cache.
1108    /// - `NodeId` - Translated node handle.
1109    /// - `f32` - Horizontal delta in logical pixels.
1110    /// - `f32` - Vertical delta in logical pixels.
1111    #[inline(always)]
1112    pub(crate) fn translate_node_cache(&mut self, node_id: NodeId, dx: f32, dy: f32) {
1113        let idx: usize = node_id.as_usize();
1114        let Self {
1115            node_gens,
1116            final_slots,
1117            subtree_bounds,
1118            subtree_flags,
1119            ..
1120        } = self;
1121        if idx >= node_gens.len() || node_gens[idx] != node_id.get_generation() {
1122            return;
1123        }
1124        if let Some(slot) = final_slots[idx].as_mut() {
1125            slot.space.set_origin_x(slot.space.get_origin_x() + dx);
1126            slot.space.set_origin_y(slot.space.get_origin_y() + dy);
1127            slot.bounds.set_x(slot.bounds.get_x() + dx);
1128            slot.bounds.set_y(slot.bounds.get_y() + dy);
1129            slot.content_bounds.set_x(slot.content_bounds.get_x() + dx);
1130            slot.content_bounds.set_y(slot.content_bounds.get_y() + dy);
1131        }
1132        if (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0 {
1133            let next_x: f32 = subtree_bounds[idx].get_x() + dx;
1134            let next_y: f32 = subtree_bounds[idx].get_y() + dy;
1135            subtree_bounds[idx].set_x(next_x);
1136            subtree_bounds[idx].set_y(next_y);
1137        }
1138    }
1139
1140    /// Stores the computed spatial `subtree_bounds` and `has_nonzero_z_child` flag for `node_id`.
1141    ///
1142    /// # Arguments
1143    ///
1144    /// - `&Self` - Mutable split layout cache.
1145    /// - `usize` - Node arena index.
1146    /// - `Rect` - Computed subtree visual/interactive bounds in root logical coordinates.
1147    /// - `bool` - Whether any immediate child has `z_index != 0`.
1148    #[inline(always)]
1149    pub(crate) fn store_subtree_meta(
1150        &mut self,
1151        idx: usize,
1152        bounds: Rect,
1153        has_nonzero_z_child: bool,
1154    ) {
1155        let Self {
1156            subtree_bounds,
1157            subtree_flags,
1158            ..
1159        } = self;
1160        subtree_bounds[idx] = bounds;
1161        let mut flags: u8 = SUBTREE_FLAG_VALID;
1162        if has_nonzero_z_child {
1163            flags |= SUBTREE_FLAG_NONZERO_Z_CHILD;
1164        }
1165        subtree_flags[idx] = flags;
1166    }
1167
1168    /// Reads the cached `subtree_bounds` for `node_id` if valid for its generation.
1169    ///
1170    /// # Arguments
1171    ///
1172    /// - `&Self` - Split layout cache reference.
1173    /// - `NodeId` - Target node handle.
1174    ///
1175    /// # Returns
1176    ///
1177    /// - `Option<Rect>` - Cached subtree bounds in root logical coordinates, if populated and valid.
1178    #[must_use]
1179    #[inline(always)]
1180    pub(crate) fn subtree_bounds_for(&self, node_id: NodeId) -> Option<Rect> {
1181        let idx: usize = node_id.as_usize();
1182        let Self {
1183            node_gens,
1184            subtree_bounds,
1185            subtree_flags,
1186            ..
1187        } = self;
1188        if idx < node_gens.len()
1189            && node_gens[idx] == node_id.get_generation()
1190            && (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0
1191        {
1192            Some(subtree_bounds[idx])
1193        } else {
1194            None
1195        }
1196    }
1197
1198    /// Returns whether `node_id` has a cached `has_nonzero_z_child == false` guarantee for fast-path hit testing.
1199    ///
1200    /// # Arguments
1201    ///
1202    /// - `&Self` - Split layout cache reference.
1203    /// - `NodeId` - Container node handle.
1204    ///
1205    /// # Returns
1206    ///
1207    /// - `Option<bool>` - `Some(has_nonzero_z_child)` when valid metadata is cached for `node_id`.
1208    #[must_use]
1209    #[inline(always)]
1210    pub(crate) fn has_nonzero_z_child(&self, node_id: NodeId) -> Option<bool> {
1211        let idx: usize = node_id.as_usize();
1212        let Self {
1213            node_gens,
1214            subtree_flags,
1215            ..
1216        } = self;
1217        if idx < node_gens.len()
1218            && node_gens[idx] == node_id.get_generation()
1219            && (subtree_flags[idx] & SUBTREE_FLAG_VALID) != 0
1220        {
1221            Some((subtree_flags[idx] & SUBTREE_FLAG_NONZERO_Z_CHILD) != 0)
1222        } else {
1223            None
1224        }
1225    }
1226
1227    /// Stamps the synced `SceneTree` root and revision after a completed layout pass.
1228    ///
1229    /// # Arguments
1230    ///
1231    /// - `&Self` - Mutable split layout cache.
1232    /// - `NodeId` - Laid-out scene root handle.
1233    /// - `u64` - `SceneTree::revision` snapshot.
1234    #[inline(always)]
1235    pub(crate) fn mark_synced(&mut self, root: NodeId, revision: u64) {
1236        let Self {
1237            synced_root,
1238            synced_tree_revision,
1239            ..
1240        } = self;
1241        *synced_root = root;
1242        *synced_tree_revision = revision;
1243    }
1244
1245    /// Checks whether cached `subtree_bounds` and `has_nonzero_z_child` are strictly synchronized with `tree`.
1246    ///
1247    /// # Arguments
1248    ///
1249    /// - `&Self` - Split layout cache reference.
1250    /// - `&SceneTree` - Live scene tree being hit-tested.
1251    ///
1252    /// # Returns
1253    ///
1254    /// - `bool` - `true` when `tree` has not been mutated since the last layout pass on the same root.
1255    #[must_use]
1256    #[inline(always)]
1257    pub(crate) fn is_synced_with(&self, tree: &SceneTree) -> bool {
1258        let Self {
1259            synced_root,
1260            synced_tree_revision,
1261            ..
1262        } = self;
1263        *synced_root == tree.get_root()
1264            && *synced_tree_revision == tree.get_revision()
1265            && synced_root.is_valid()
1266    }
1267}