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
85/// Bounded 2-way set-associative text measurement cache operations.
86impl TextSizeCache {
87    /// Returns the cached bounding box for `(text, style, max_width)` or computes and caches it via `measure_fn`.
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Mutable text-size cache.
92    /// - `&str` - UTF-8 text string to measure.
93    /// - `TextStyle` - Typography style parameters affecting measurement.
94    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
95    /// - `F` - Closure invoked only on a cache miss to measure the exact bounding `Size`.
96    ///
97    /// # Returns
98    ///
99    /// - `Size` - Exact measured bounding box.
100    pub(crate) fn get_or_measure<F>(
101        &mut self,
102        text: &str,
103        style: TextStyle,
104        max_width: Option<f32>,
105        measure_fn: F,
106    ) -> Size
107    where
108        F: FnOnce(&str, TextStyle, Option<f32>) -> Size,
109    {
110        let Ok(text_len) = u32::try_from(text.len()) else {
111            return measure_fn(text, style, max_width);
112        };
113        let (hash_a, hash_b): (u64, u64) = Self::hash_text_128(text.as_bytes());
114        let font_size_bits: u32 = Self::normalize_f32_bits(style.get_font_size());
115        let line_height_bits: u32 = Self::normalize_f32_bits(style.get_line_height());
116        let letter_spacing_bits: u32 = Self::normalize_f32_bits(style.get_letter_spacing());
117        let max_width_bits: u32 = match max_width {
118            Some(w) if w.is_nan() => 0,
119            Some(w) => Self::normalize_f32_bits(w),
120            None => TEXT_SIZE_MAX_WIDTH_NONE_BITS,
121        };
122        let style_flags: u16 = Self::pack_style_flags(style);
123        let style_mix: u64 = ((font_size_bits as u64) << 32)
124            ^ (max_width_bits as u64)
125            ^ ((line_height_bits as u64).rotate_left(17))
126            ^ ((letter_spacing_bits as u64).rotate_left(41))
127            ^ ((style_flags as u64).wrapping_mul(TEXT_HASH_PRIME_B));
128        let set_index: usize = (((hash_a ^ style_mix).wrapping_mul(TEXT_HASH_FINAL_A) >> 16)
129            as usize)
130            & TEXT_SIZE_CACHE_SET_MASK;
131        let base: usize = set_index * TEXT_SIZE_CACHE_WAYS;
132        let probe: TextSizeEntry = TextSizeEntry {
133            hash_a,
134            hash_b,
135            text_len,
136            font_size_bits,
137            line_height_bits,
138            letter_spacing_bits,
139            max_width_bits,
140            width: 0.0,
141            height: 0.0,
142            style_flags,
143        };
144        let Self { entries } = self;
145        if entries.is_empty() {
146            entries.resize(TEXT_SIZE_CACHE_SLOTS, TextSizeEntry::default());
147        }
148        let way0: TextSizeEntry = entries[base];
149        if Self::entry_matches(way0, probe) {
150            return Size::new(way0.width, way0.height);
151        }
152        let way1: TextSizeEntry = entries[base + 1];
153        if Self::entry_matches(way1, probe) {
154            entries[base] = way1;
155            entries[base + 1] = way0;
156            return Size::new(way1.width, way1.height);
157        }
158        let measured: Size = measure_fn(text, style, max_width);
159        entries[base + 1] = way0;
160        entries[base] = TextSizeEntry {
161            width: measured.get_width(),
162            height: measured.get_height(),
163            ..probe
164        };
165        measured
166    }
167
168    /// Checks whether a cached `TextSizeEntry` matches all text and typography key fields of `probe`.
169    ///
170    /// # Arguments
171    ///
172    /// - `TextSizeEntry` - Candidate cache entry.
173    /// - `TextSizeEntry` - Probe entry carrying all key fields to match.
174    ///
175    /// # Returns
176    ///
177    /// - `bool` - `true` when the entry is populated and matches every key component.
178    #[inline(always)]
179    fn entry_matches(entry: TextSizeEntry, probe: TextSizeEntry) -> bool {
180        entry.style_flags == probe.style_flags
181            && entry.text_len == probe.text_len
182            && entry.hash_a == probe.hash_a
183            && entry.hash_b == probe.hash_b
184            && entry.max_width_bits == probe.max_width_bits
185            && entry.font_size_bits == probe.font_size_bits
186            && entry.line_height_bits == probe.line_height_bits
187            && entry.letter_spacing_bits == probe.letter_spacing_bits
188    }
189
190    /// Computes two independent 64-bit hashes over `bytes` in a single 8-byte-chunked pass.
191    ///
192    /// # Arguments
193    ///
194    /// - `&[u8]` - UTF-8 input bytes.
195    ///
196    /// # Returns
197    ///
198    /// - `(u64, u64)` - Pair of independent 64-bit hashes with avalanche mixing.
199    #[inline(always)]
200    fn hash_text_128(bytes: &[u8]) -> (u64, u64) {
201        let len: usize = bytes.len();
202        let len_u64: u64 = len as u64;
203        let mut h1: u64 = TEXT_HASH_SEED_A ^ len_u64;
204        let mut h2: u64 = TEXT_HASH_SEED_B ^ len_u64.wrapping_mul(TEXT_HASH_PRIME_B);
205        let mut offset: usize = 0;
206        while offset + 8 <= len {
207            let word: u64 = u64::from_le_bytes([
208                bytes[offset],
209                bytes[offset + 1],
210                bytes[offset + 2],
211                bytes[offset + 3],
212                bytes[offset + 4],
213                bytes[offset + 5],
214                bytes[offset + 6],
215                bytes[offset + 7],
216            ]);
217            h1 = (h1 ^ word).wrapping_mul(TEXT_HASH_PRIME_A);
218            h2 = (h2.rotate_left(27) ^ word).wrapping_mul(TEXT_HASH_PRIME_B);
219            offset += 8;
220        }
221        let mut tail: u64 = 0;
222        let mut shift: u32 = 0;
223        while offset < len {
224            tail |= (bytes[offset] as u64) << shift;
225            shift += 8;
226            offset += 1;
227        }
228        h1 = (h1 ^ tail).wrapping_mul(TEXT_HASH_PRIME_A);
229        h2 = (h2.rotate_left(27) ^ tail).wrapping_mul(TEXT_HASH_PRIME_B);
230        h1 ^= h1 >> 33;
231        h1 = h1.wrapping_mul(TEXT_HASH_FINAL_A);
232        h1 ^= h1 >> 33;
233        h2 ^= h2 >> 31;
234        h2 = h2.wrapping_mul(TEXT_HASH_FINAL_B);
235        h2 ^= h2 >> 31;
236        (h1, h2)
237    }
238
239    /// Normalizes floating-point bits so `-0.0` and `+0.0` map identically.
240    ///
241    /// # Arguments
242    ///
243    /// - `f32` - Input scalar value.
244    ///
245    /// # Returns
246    ///
247    /// - `u32` - Normalized IEEE-754 bit pattern.
248    #[inline(always)]
249    fn normalize_f32_bits(value: f32) -> u32 {
250        if value == 0.0 { 0 } else { value.to_bits() }
251    }
252
253    /// Packs layout-relevant discrete typography flags plus the occupied marker bit into `u16`.
254    ///
255    /// # Arguments
256    ///
257    /// - `TextStyle` - Source typography style.
258    ///
259    /// # Returns
260    ///
261    /// - `u16` - Packed flag bitfield with `TEXT_SIZE_ENTRY_OCCUPIED` set.
262    #[inline(always)]
263    fn pack_style_flags(style: TextStyle) -> u16 {
264        let family_bits: u16 = match style.get_family() {
265            FontFamily::Sans => 0,
266            FontFamily::Monospace => 1,
267            FontFamily::Serif => 2,
268        };
269        let weight_bits: u16 = match style.get_weight() {
270            FontWeight::Light => 0,
271            FontWeight::Normal => 1,
272            FontWeight::Medium => 2,
273            FontWeight::SemiBold => 3,
274            FontWeight::Bold => 4,
275        };
276        let overflow_bits: u16 = match style.get_overflow() {
277            TextOverflow::Wrap => 0,
278            TextOverflow::Clip => 1,
279            TextOverflow::Ellipsis => 2,
280        };
281        let italic_bit: u16 = if style.get_italic() { 1 } else { 0 };
282        TEXT_SIZE_ENTRY_OCCUPIED
283            | family_bits
284            | (weight_bits << 2)
285            | (overflow_bits << 5)
286            | (italic_bit << 7)
287    }
288}