Skip to main content

euv_core/font/measurer/
impl.rs

1use super::*;
2
3/// Fast internal typography measurement helpers for `DeterministicTextMeasurer`.
4impl DeterministicTextMeasurer {
5    /// Precomputes invariant typography metrics for a single `measure` or `measure_size` call.
6    ///
7    /// # Arguments
8    ///
9    /// - `TextStyle` - Active typography style.
10    ///
11    /// # Returns
12    ///
13    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Tuple `(is_mono, font_size, bold_factor, letter_spacing, mono_w, wide_w, non_ascii_w, space_w)`.
14    #[inline(always)]
15    #[must_use]
16    fn style_metrics(style: TextStyle) -> (bool, f32, f32, f32, f32, f32, f32, f32) {
17        let is_mono: bool = style.get_family() == FontFamily::Monospace;
18        let font_size: f32 = style.get_font_size();
19        let bold_factor: f32 = text_bold_advance_factor(style);
20        let letter_spacing: f32 = style.get_letter_spacing();
21        let mono_w: f32 = font_size * MONOSPACE_ADVANCE_RATIO + letter_spacing;
22        let wide_w: f32 = font_size * WIDE_CJK_ADVANCE_RATIO + letter_spacing;
23        let non_ascii_w: f32 = if is_mono {
24            mono_w
25        } else {
26            font_size * NON_ASCII_ADVANCE_RATIO * bold_factor + letter_spacing
27        };
28        let space_w: f32 = if is_mono {
29            mono_w
30        } else {
31            font_size * ASCII_ADVANCE_LUT[b' ' as usize] * bold_factor + letter_spacing
32        };
33        (
34            is_mono,
35            font_size,
36            bold_factor,
37            letter_spacing,
38            mono_w,
39            wide_w,
40            non_ascii_w,
41            space_w,
42        )
43    }
44
45    /// Resolves the deterministic advance width for a wide Unicode scalar (`CJK` vs `emoji`).
46    ///
47    /// # Arguments
48    ///
49    /// - `char` - Wide Unicode scalar (`is_wide_unicode(ch) == true`).
50    /// - `f32` - Font size in logical pixels.
51    /// - `f32` - Letter spacing in logical pixels.
52    /// - `f32` - Precomputed CJK wide advance width.
53    ///
54    /// # Returns
55    ///
56    /// - `f32` - Advance width matching `measure_char_advance`.
57    #[inline(always)]
58    #[must_use]
59    fn wide_advance(ch: char, font_size: f32, letter_spacing: f32, wide_w: f32) -> f32 {
60        if is_emoji_unicode(ch) {
61            font_size * WIDE_EMOJI_ADVANCE_RATIO + letter_spacing
62        } else {
63            wide_w
64        }
65    }
66
67    /// Computes the exact advance width of an ASCII byte using hoisted style metrics.
68    ///
69    /// # Arguments
70    ///
71    /// - `u8` - ASCII byte (`0..128`).
72    /// - `bool` - Whether monospace family is active.
73    /// - `f32` - Font size in logical pixels.
74    /// - `f32` - Bold width multiplier.
75    /// - `f32` - Letter spacing in logical pixels.
76    /// - `f32` - Precomputed monospace advance width.
77    ///
78    /// # Returns
79    ///
80    /// - `f32` - Exact advance width matching `measure_char_advance`.
81    #[inline(always)]
82    #[must_use]
83    fn ascii_advance(
84        byte: u8,
85        is_mono: bool,
86        font_size: f32,
87        bold_factor: f32,
88        letter_spacing: f32,
89        mono_w: f32,
90    ) -> f32 {
91        if is_mono {
92            mono_w
93        } else {
94            font_size * ASCII_ADVANCE_LUT[byte as usize] * bold_factor + letter_spacing
95        }
96    }
97
98    /// Measures the unwrapped total width of one newline-free line using hoisted style metrics.
99    ///
100    /// # Arguments
101    ///
102    /// - `&str` - Single line slice without `\n`.
103    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Precomputed style metrics tuple.
104    ///
105    /// # Returns
106    ///
107    /// - `(f32, usize)` - Total line advance width and character count.
108    #[inline]
109    #[must_use]
110    fn measure_raw_line_width(
111        raw_line: &str,
112        metrics: (bool, f32, f32, f32, f32, f32, f32, f32),
113    ) -> (f32, usize) {
114        let (is_mono, font_size, bold_factor, letter_spacing, mono_w, wide_w, non_ascii_w, _): (
115            bool,
116            f32,
117            f32,
118            f32,
119            f32,
120            f32,
121            f32,
122            f32,
123        ) = metrics;
124        let mut width: f32 = 0.0;
125        if raw_line.is_ascii() {
126            let bytes: &[u8] = raw_line.as_bytes();
127            if is_mono {
128                for _ in bytes.iter() {
129                    width += mono_w;
130                }
131            } else {
132                for &blue_val in bytes.iter() {
133                    width += font_size * ASCII_ADVANCE_LUT[blue_val as usize] * bold_factor
134                        + letter_spacing;
135                }
136            }
137            return (width, bytes.len());
138        }
139        let mut char_count: usize = 0;
140        for ch in raw_line.chars() {
141            let code: u32 = ch as u32;
142            let ch_w: f32 = if matches!(code, 0x200B | 0x200C | 0x200D | 0xFE0E | 0xFE0F) {
143                0.0
144            } else if code < 128 {
145                Self::ascii_advance(
146                    code as u8,
147                    is_mono,
148                    font_size,
149                    bold_factor,
150                    letter_spacing,
151                    mono_w,
152                )
153            } else if is_wide_unicode(ch) {
154                Self::wide_advance(ch, font_size, letter_spacing, wide_w)
155            } else {
156                non_ascii_w
157            };
158            width += ch_w;
159            char_count += 1;
160        }
161        (width, char_count)
162    }
163
164    /// Computes the ellipsis-truncated display width of one unwrapped line without allocating.
165    ///
166    /// # Arguments
167    ///
168    /// - `&str` - Single unwrapped line slice.
169    /// - `f32` - Full unwrapped width of `raw_line`.
170    /// - `usize` - Unicode scalar count of `raw_line`.
171    /// - `TextStyle` - Active typography style.
172    /// - `Option<f32>` - Optional maximum width constraint.
173    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Precomputed style metrics tuple.
174    ///
175    /// # Returns
176    ///
177    /// - `f32` - Final line width after optional ellipsis truncation.
178    #[inline]
179    #[must_use]
180    fn ellipsis_line_width(
181        raw_line: &str,
182        width: f32,
183        char_count: usize,
184        style: TextStyle,
185        max_width: Option<f32>,
186        metrics: (bool, f32, f32, f32, f32, f32, f32, f32),
187    ) -> f32 {
188        let (is_mono, font_size, bold_factor, letter_spacing, mono_w, wide_w, non_ascii_w, _): (
189            bool,
190            f32,
191            f32,
192            f32,
193            f32,
194            f32,
195            f32,
196            f32,
197        ) = metrics;
198        if style.get_overflow() == TextOverflow::Ellipsis
199            && let Some(limit) = max_width
200            && width > limit + 0.5
201            && limit > 0.0
202            && char_count > 2
203        {
204            let dot_w: f32 = Self::ascii_advance(
205                ASCII_DOT_BYTE,
206                is_mono,
207                font_size,
208                bold_factor,
209                letter_spacing,
210                mono_w,
211            );
212            let ellipsis_w: f32 = dot_w * 3.0;
213            if width <= ellipsis_w + 1.0 {
214                return width;
215            }
216            let target_w: f32 = (limit - ellipsis_w).max(0.0);
217            let mut acc: f32 = 0.0;
218            for ch in raw_line.chars() {
219                let code: u32 = ch as u32;
220                let ch_w: f32 = if matches!(code, 0x200B | 0x200C | 0x200D | 0xFE0E | 0xFE0F) {
221                    0.0
222                } else if code < 128 {
223                    Self::ascii_advance(
224                        code as u8,
225                        is_mono,
226                        font_size,
227                        bold_factor,
228                        letter_spacing,
229                        mono_w,
230                    )
231                } else if is_wide_unicode(ch) {
232                    Self::wide_advance(ch, font_size, letter_spacing, wide_w)
233                } else {
234                    non_ascii_w
235                };
236                if acc + ch_w > target_w {
237                    break;
238                }
239                acc += ch_w;
240            }
241            return acc + ellipsis_w;
242        }
243        width
244    }
245
246    /// Flushes the active wrapped slice state into `lines` and resets it for the next line.
247    ///
248    /// # Arguments
249    ///
250    /// - `&str` - Source newline-free line slice.
251    /// - `f32` - Space character advance width.
252    /// - `&mut (bool, usize, usize, Option<String>, f32, usize, bool)` - Active wrapped line state tuple.
253    /// - `&mut Vec<TextLine>` - Output wrapped lines buffer.
254    /// - `bool` - Whether trailing spaces should be stripped before pushing.
255    #[inline(always)]
256    fn flush_wrapped_line(
257        raw_line: &str,
258        space_w: f32,
259        state: &mut (bool, usize, usize, Option<String>, f32, usize, bool),
260        lines: &mut Vec<TextLine>,
261        trim_spaces: bool,
262    ) {
263        let (cur_has_chars, cur_start, cur_end, cur_overflow, cur_w, trailing_spaces, skipped): (
264            &mut bool,
265            &mut usize,
266            &mut usize,
267            &mut Option<String>,
268            &mut f32,
269            &mut usize,
270            &mut bool,
271        ) = (
272            &mut state.0,
273            &mut state.1,
274            &mut state.2,
275            &mut state.3,
276            &mut state.4,
277            &mut state.5,
278            &mut state.6,
279        );
280        if trim_spaces {
281            let trim_count: usize = *trailing_spaces;
282            for _ in 0..trim_count {
283                *cur_w = (*cur_w - space_w).max(0.0);
284            }
285            if let Some(mut buf) = cur_overflow.take() {
286                for _ in 0..trim_count {
287                    let _: Option<char> = buf.pop();
288                }
289                lines.push(TextLine::new(buf, *cur_w));
290            } else if *cur_has_chars {
291                let trimmed_end: usize = *cur_end - trim_count;
292                lines.push(TextLine::new(
293                    raw_line[*cur_start..trimmed_end].to_string(),
294                    *cur_w,
295                ));
296            } else {
297                lines.push(TextLine::new(String::new(), *cur_w));
298            }
299        } else if let Some(buf) = cur_overflow.take() {
300            lines.push(TextLine::new(buf, *cur_w));
301        } else if *cur_has_chars {
302            lines.push(TextLine::new(
303                raw_line[*cur_start..*cur_end].to_string(),
304                *cur_w,
305            ));
306        } else {
307            lines.push(TextLine::new(String::new(), *cur_w));
308        }
309        *cur_has_chars = false;
310        *cur_start = 0;
311        *cur_end = 0;
312        *cur_w = 0.0;
313        *trailing_spaces = 0;
314        *skipped = false;
315    }
316
317    /// Appends a byte segment of `raw_line` onto the active wrapped line state.
318    ///
319    /// # Arguments
320    ///
321    /// - `&str` - Source newline-free line slice.
322    /// - `&mut (bool, usize, usize, Option<String>, f32, usize, bool)` - Active wrapped line state tuple.
323    /// - `(usize, usize, f32)` - Segment byte range `(seg_start, seg_end, seg_w)`.
324    /// - `bool` - Whether the appended segment is a single ASCII space.
325    #[inline(always)]
326    fn append_wrapped_segment(
327        raw_line: &str,
328        state: &mut (bool, usize, usize, Option<String>, f32, usize, bool),
329        segment: (usize, usize, f32),
330        is_space: bool,
331    ) {
332        let (seg_start, seg_end, seg_w): (usize, usize, f32) = segment;
333        let (cur_has_chars, cur_start, cur_end, cur_overflow, cur_w, trailing_spaces, skipped): (
334            &mut bool,
335            &mut usize,
336            &mut usize,
337            &mut Option<String>,
338            &mut f32,
339            &mut usize,
340            &mut bool,
341        ) = (
342            &mut state.0,
343            &mut state.1,
344            &mut state.2,
345            &mut state.3,
346            &mut state.4,
347            &mut state.5,
348            &mut state.6,
349        );
350        if !*cur_has_chars {
351            *cur_has_chars = true;
352            *cur_start = seg_start;
353            *cur_end = seg_end;
354            *cur_w = seg_w;
355            *trailing_spaces = usize::from(is_space);
356            *skipped = false;
357        } else if *skipped || cur_overflow.is_some() {
358            if cur_overflow.is_none() {
359                *cur_overflow = Some(raw_line[*cur_start..*cur_end].to_string());
360            }
361            if let Some(buf) = cur_overflow.as_mut() {
362                buf.push_str(&raw_line[seg_start..seg_end]);
363            }
364            *cur_w += seg_w;
365            *trailing_spaces = if is_space { *trailing_spaces + 1 } else { 0 };
366        } else {
367            *cur_end = seg_end;
368            *cur_w += seg_w;
369            *trailing_spaces = if is_space { *trailing_spaces + 1 } else { 0 };
370        }
371    }
372
373    /// Flushes scalar wrap metrics for one line during zero-allocation `measure_size`.
374    ///
375    /// # Arguments
376    ///
377    /// - `f32` - Space character advance width.
378    /// - `&mut (bool, f32, usize)` - Active `(cur_has_chars, cur_w, trailing_spaces)` state.
379    /// - `&mut usize` - Running wrapped line counter.
380    /// - `&mut f32` - Running maximum line width accumulator.
381    /// - `bool` - Whether trailing spaces should be stripped from `cur_w`.
382    #[inline(always)]
383    fn flush_wrapped_size(
384        space_w: f32,
385        state: &mut (bool, f32, usize),
386        line_count: &mut usize,
387        max_line_w: &mut f32,
388        trim_spaces: bool,
389    ) {
390        if trim_spaces {
391            for _ in 0..state.2 {
392                state.1 = (state.1 - space_w).max(0.0);
393            }
394        }
395        if state.1 > *max_line_w {
396            *max_line_w = state.1;
397        }
398        *line_count += 1;
399        state.0 = false;
400        state.1 = 0.0;
401        state.2 = 0;
402    }
403
404    /// Wraps one newline-free line into `lines` using zero-copy byte-slice tracking.
405    ///
406    /// # Arguments
407    ///
408    /// - `&str` - Single newline-free line slice.
409    /// - `f32` - Effective wrap width limit including `WRAP_WIDTH_EPSILON`.
410    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Precomputed style metrics tuple.
411    /// - `&mut Vec<TextLine>` - Output wrapped lines buffer.
412    fn wrap_raw_line_into(
413        raw_line: &str,
414        limit: f32,
415        metrics: (bool, f32, f32, f32, f32, f32, f32, f32),
416        lines: &mut Vec<TextLine>,
417    ) {
418        let (
419            is_mono,
420            font_size,
421            bold_factor,
422            letter_spacing,
423            mono_w,
424            wide_w,
425            non_ascii_w,
426            space_w,
427        ): (bool, f32, f32, f32, f32, f32, f32, f32) = metrics;
428        let mut cur_state: (bool, usize, usize, Option<String>, f32, usize, bool) =
429            (false, 0, 0, None, 0.0, 0, false);
430        let mut word_has_chars: bool = false;
431        let mut word_start: usize = 0;
432        let mut word_end: usize = 0;
433        let mut word_w: f32 = 0.0;
434        if raw_line.is_ascii() {
435            for (byte_idx, &blue_val) in raw_line.as_bytes().iter().enumerate() {
436                let ch_w: f32 = Self::ascii_advance(
437                    blue_val,
438                    is_mono,
439                    font_size,
440                    bold_factor,
441                    letter_spacing,
442                    mono_w,
443                );
444                let ch_end: usize = byte_idx + 1;
445                if blue_val == b' ' {
446                    if cur_state.0 && cur_state.4 + word_w > limit {
447                        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
448                    }
449                    if word_has_chars {
450                        Self::append_wrapped_segment(
451                            raw_line,
452                            &mut cur_state,
453                            (word_start, word_end, word_w),
454                            false,
455                        );
456                        word_has_chars = false;
457                        word_w = 0.0;
458                    }
459                    if cur_state.0 {
460                        if cur_state.4 + ch_w <= limit {
461                            Self::append_wrapped_segment(
462                                raw_line,
463                                &mut cur_state,
464                                (byte_idx, ch_end, ch_w),
465                                true,
466                            );
467                        } else {
468                            cur_state.6 = true;
469                        }
470                    }
471                } else {
472                    if cur_state.0 && cur_state.4 + word_w + ch_w > limit && word_w + ch_w > limit {
473                        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
474                    }
475                    if word_has_chars && !cur_state.0 && word_w + ch_w > limit {
476                        lines.push(TextLine::new(
477                            raw_line[word_start..word_end].to_string(),
478                            word_w,
479                        ));
480                        word_has_chars = false;
481                        word_w = 0.0;
482                    }
483                    if !word_has_chars {
484                        word_start = byte_idx;
485                        word_has_chars = true;
486                    }
487                    word_end = ch_end;
488                    word_w += ch_w;
489                }
490            }
491        } else {
492            for (byte_idx, ch) in raw_line.char_indices() {
493                let code: u32 = ch as u32;
494                let zero_w: bool = matches!(code, 0x200B | 0x200C | 0x200D | 0xFE0E | 0xFE0F);
495                let wide: bool = !zero_w && is_wide_unicode(ch);
496                let ch_w: f32 = if zero_w {
497                    0.0
498                } else if code < 128 {
499                    Self::ascii_advance(
500                        code as u8,
501                        is_mono,
502                        font_size,
503                        bold_factor,
504                        letter_spacing,
505                        mono_w,
506                    )
507                } else if wide {
508                    Self::wide_advance(ch, font_size, letter_spacing, wide_w)
509                } else {
510                    non_ascii_w
511                };
512                let ch_end: usize = byte_idx + ch.len_utf8();
513                if ch == ' ' {
514                    if cur_state.0 && cur_state.4 + word_w > limit {
515                        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
516                    }
517                    if word_has_chars {
518                        Self::append_wrapped_segment(
519                            raw_line,
520                            &mut cur_state,
521                            (word_start, word_end, word_w),
522                            false,
523                        );
524                        word_has_chars = false;
525                        word_w = 0.0;
526                    }
527                    if cur_state.0 {
528                        if cur_state.4 + ch_w <= limit {
529                            Self::append_wrapped_segment(
530                                raw_line,
531                                &mut cur_state,
532                                (byte_idx, ch_end, ch_w),
533                                true,
534                            );
535                        } else {
536                            cur_state.6 = true;
537                        }
538                    }
539                } else if wide {
540                    if word_has_chars {
541                        if cur_state.0 && cur_state.4 + word_w > limit {
542                            Self::flush_wrapped_line(
543                                raw_line,
544                                space_w,
545                                &mut cur_state,
546                                lines,
547                                true,
548                            );
549                        }
550                        Self::append_wrapped_segment(
551                            raw_line,
552                            &mut cur_state,
553                            (word_start, word_end, word_w),
554                            false,
555                        );
556                        word_has_chars = false;
557                        word_w = 0.0;
558                    }
559                    if cur_state.0 && cur_state.4 + ch_w > limit {
560                        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, false);
561                    }
562                    Self::append_wrapped_segment(
563                        raw_line,
564                        &mut cur_state,
565                        (byte_idx, ch_end, ch_w),
566                        false,
567                    );
568                } else {
569                    if cur_state.0 && cur_state.4 + word_w + ch_w > limit && word_w + ch_w > limit {
570                        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
571                    }
572                    if word_has_chars && !cur_state.0 && word_w + ch_w > limit {
573                        lines.push(TextLine::new(
574                            raw_line[word_start..word_end].to_string(),
575                            word_w,
576                        ));
577                        word_has_chars = false;
578                        word_w = 0.0;
579                    }
580                    if !word_has_chars {
581                        word_start = byte_idx;
582                        word_has_chars = true;
583                    }
584                    word_end = ch_end;
585                    word_w += ch_w;
586                }
587            }
588        }
589        if word_has_chars {
590            if cur_state.0 && cur_state.4 + word_w > limit {
591                Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
592            }
593            Self::append_wrapped_segment(
594                raw_line,
595                &mut cur_state,
596                (word_start, word_end, word_w),
597                false,
598            );
599        }
600        Self::flush_wrapped_line(raw_line, space_w, &mut cur_state, lines, true);
601    }
602
603    /// Accumulates wrapped line count and maximum line width for one newline-free line with zero heap allocations.
604    ///
605    /// # Arguments
606    ///
607    /// - `&str` - Single newline-free line slice.
608    /// - `f32` - Effective wrap width limit including `WRAP_WIDTH_EPSILON`.
609    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Precomputed style metrics tuple.
610    /// - `&mut usize` - Running wrapped line counter.
611    /// - `&mut f32` - Running maximum line width accumulator.
612    fn measure_wrapped_line_size(
613        raw_line: &str,
614        limit: f32,
615        metrics: (bool, f32, f32, f32, f32, f32, f32, f32),
616        line_count: &mut usize,
617        max_line_w: &mut f32,
618    ) {
619        let (
620            is_mono,
621            font_size,
622            bold_factor,
623            letter_spacing,
624            mono_w,
625            wide_w,
626            non_ascii_w,
627            space_w,
628        ): (bool, f32, f32, f32, f32, f32, f32, f32) = metrics;
629        let mut cur_state: (bool, f32, usize) = (false, 0.0, 0);
630        let mut word_has_chars: bool = false;
631        let mut word_w: f32 = 0.0;
632        if raw_line.is_ascii() {
633            for &blue_val in raw_line.as_bytes().iter() {
634                let ch_w: f32 = Self::ascii_advance(
635                    blue_val,
636                    is_mono,
637                    font_size,
638                    bold_factor,
639                    letter_spacing,
640                    mono_w,
641                );
642                if blue_val == b' ' {
643                    if cur_state.0 && cur_state.1 + word_w > limit {
644                        Self::flush_wrapped_size(
645                            space_w,
646                            &mut cur_state,
647                            line_count,
648                            max_line_w,
649                            true,
650                        );
651                    }
652                    if word_has_chars {
653                        cur_state.0 = true;
654                        cur_state.1 += word_w;
655                        cur_state.2 = 0;
656                        word_has_chars = false;
657                        word_w = 0.0;
658                    }
659                    if cur_state.0 && cur_state.1 + ch_w <= limit {
660                        cur_state.1 += ch_w;
661                        cur_state.2 += 1;
662                    }
663                } else {
664                    if cur_state.0 && cur_state.1 + word_w + ch_w > limit && word_w + ch_w > limit {
665                        Self::flush_wrapped_size(
666                            space_w,
667                            &mut cur_state,
668                            line_count,
669                            max_line_w,
670                            true,
671                        );
672                    }
673                    if word_has_chars && !cur_state.0 && word_w + ch_w > limit {
674                        if word_w > *max_line_w {
675                            *max_line_w = word_w;
676                        }
677                        *line_count += 1;
678                        word_w = 0.0;
679                    }
680                    word_has_chars = true;
681                    word_w += ch_w;
682                }
683            }
684        } else {
685            for ch in raw_line.chars() {
686                let code: u32 = ch as u32;
687                let zero_w: bool = matches!(code, 0x200B | 0x200C | 0x200D | 0xFE0E | 0xFE0F);
688                let wide: bool = !zero_w && is_wide_unicode(ch);
689                let ch_w: f32 = if zero_w {
690                    0.0
691                } else if code < 128 {
692                    Self::ascii_advance(
693                        code as u8,
694                        is_mono,
695                        font_size,
696                        bold_factor,
697                        letter_spacing,
698                        mono_w,
699                    )
700                } else if wide {
701                    Self::wide_advance(ch, font_size, letter_spacing, wide_w)
702                } else {
703                    non_ascii_w
704                };
705                if ch == ' ' {
706                    if cur_state.0 && cur_state.1 + word_w > limit {
707                        Self::flush_wrapped_size(
708                            space_w,
709                            &mut cur_state,
710                            line_count,
711                            max_line_w,
712                            true,
713                        );
714                    }
715                    if word_has_chars {
716                        cur_state.0 = true;
717                        cur_state.1 += word_w;
718                        cur_state.2 = 0;
719                        word_has_chars = false;
720                        word_w = 0.0;
721                    }
722                    if cur_state.0 && cur_state.1 + ch_w <= limit {
723                        cur_state.1 += ch_w;
724                        cur_state.2 += 1;
725                    }
726                } else if wide {
727                    if word_has_chars {
728                        if cur_state.0 && cur_state.1 + word_w > limit {
729                            Self::flush_wrapped_size(
730                                space_w,
731                                &mut cur_state,
732                                line_count,
733                                max_line_w,
734                                true,
735                            );
736                        }
737                        cur_state.0 = true;
738                        cur_state.1 += word_w;
739                        cur_state.2 = 0;
740                        word_has_chars = false;
741                        word_w = 0.0;
742                    }
743                    if cur_state.0 && cur_state.1 + ch_w > limit {
744                        Self::flush_wrapped_size(
745                            space_w,
746                            &mut cur_state,
747                            line_count,
748                            max_line_w,
749                            false,
750                        );
751                    }
752                    cur_state.0 = true;
753                    cur_state.1 += ch_w;
754                    cur_state.2 = 0;
755                } else {
756                    if cur_state.0 && cur_state.1 + word_w + ch_w > limit && word_w + ch_w > limit {
757                        Self::flush_wrapped_size(
758                            space_w,
759                            &mut cur_state,
760                            line_count,
761                            max_line_w,
762                            true,
763                        );
764                    }
765                    if word_has_chars && !cur_state.0 && word_w + ch_w > limit {
766                        if word_w > *max_line_w {
767                            *max_line_w = word_w;
768                        }
769                        *line_count += 1;
770                        word_w = 0.0;
771                    }
772                    word_has_chars = true;
773                    word_w += ch_w;
774                }
775            }
776        }
777        if word_has_chars {
778            if cur_state.0 && cur_state.1 + word_w > limit {
779                Self::flush_wrapped_size(space_w, &mut cur_state, line_count, max_line_w, true);
780            }
781            cur_state.0 = true;
782            cur_state.1 += word_w;
783            cur_state.2 = 0;
784        }
785        Self::flush_wrapped_size(space_w, &mut cur_state, line_count, max_line_w, true);
786    }
787
788    /// Formats one unwrapped line with optional ellipsis truncation and appends it to `lines`.
789    ///
790    /// # Arguments
791    ///
792    /// - `&str` - Single newline-free line slice.
793    /// - `TextStyle` - Active typography style.
794    /// - `Option<f32>` - Optional maximum width constraint.
795    /// - `(bool, f32, f32, f32, f32, f32, f32, f32)` - Precomputed style metrics tuple.
796    /// - `&mut Vec<TextLine>` - Output lines buffer.
797    fn push_unwrapped_line(
798        raw_line: &str,
799        style: TextStyle,
800        max_width: Option<f32>,
801        metrics: (bool, f32, f32, f32, f32, f32, f32, f32),
802        lines: &mut Vec<TextLine>,
803    ) {
804        let (width, char_count): (f32, usize) = Self::measure_raw_line_width(raw_line, metrics);
805        if style.get_overflow() == TextOverflow::Ellipsis
806            && let Some(limit) = max_width
807            && width > limit + 0.5
808            && limit > 0.0
809            && char_count > 2
810        {
811            let (is_mono, font_size, bold_factor, letter_spacing, mono_w, wide_w, non_ascii_w, _): (
812                bool,
813                f32,
814                f32,
815                f32,
816                f32,
817                f32,
818                f32,
819                f32,
820            ) = metrics;
821            let dot_w: f32 = Self::ascii_advance(
822                ASCII_DOT_BYTE,
823                is_mono,
824                font_size,
825                bold_factor,
826                letter_spacing,
827                mono_w,
828            );
829            let ellipsis_w: f32 = dot_w * 3.0;
830            if width <= ellipsis_w + 1.0 {
831                lines.push(TextLine::new(raw_line.to_string(), width));
832            } else {
833                let target_w: f32 = (limit - ellipsis_w).max(0.0);
834                let mut acc: f32 = 0.0;
835                let mut cut_bytes: usize = 0;
836                for (byte_idx, ch) in raw_line.char_indices() {
837                    let code: u32 = ch as u32;
838                    let ch_w: f32 = if matches!(code, 0x200B | 0x200C | 0x200D | 0xFE0E | 0xFE0F) {
839                        0.0
840                    } else if code < 128 {
841                        Self::ascii_advance(
842                            code as u8,
843                            is_mono,
844                            font_size,
845                            bold_factor,
846                            letter_spacing,
847                            mono_w,
848                        )
849                    } else if is_wide_unicode(ch) {
850                        Self::wide_advance(ch, font_size, letter_spacing, wide_w)
851                    } else {
852                        non_ascii_w
853                    };
854                    if acc + ch_w > target_w {
855                        break;
856                    }
857                    acc += ch_w;
858                    cut_bytes = byte_idx + ch.len_utf8();
859                }
860                let mut truncated: String = String::with_capacity(cut_bytes + 3);
861                truncated.push_str(&raw_line[..cut_bytes]);
862                truncated.push_str("...");
863                lines.push(TextLine::new(truncated, acc + ellipsis_w));
864            }
865        } else {
866            lines.push(TextLine::new(raw_line.to_string(), width));
867        }
868    }
869
870    /// Checks with zero heap allocations whether `text` lays out as one unmodified line identical to `measure(text, style, max_width)`.
871    ///
872    /// # Arguments
873    ///
874    /// - `&Self` - Measurer reference.
875    /// - `&'a str` - Input UTF-8 string.
876    /// - `TextStyle` - Active typography style.
877    /// - `Option<f32>` - Optional maximum available width constraint.
878    ///
879    /// # Returns
880    ///
881    /// - `Option<(&'a str, f32)>` - Exact single line slice and `line_height_px`, or `None` when multi-line wrap or ellipsis truncation is required.
882    #[must_use]
883    pub(crate) fn try_single_line<'a>(
884        &self,
885        text: &'a str,
886        style: TextStyle,
887        max_width: Option<f32>,
888    ) -> Option<(&'a str, f32)> {
889        if text.is_empty() || text.as_bytes().contains(&b'\n') {
890            return None;
891        }
892        let line_height_px: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
893        match style.get_overflow() {
894            TextOverflow::Clip => Some((text, line_height_px)),
895            TextOverflow::Ellipsis => {
896                if let Some(limit) = max_width
897                    && limit > 0.0
898                {
899                    let metrics: (bool, f32, f32, f32, f32, f32, f32, f32) =
900                        Self::style_metrics(style);
901                    let (width, char_count): (f32, usize) =
902                        Self::measure_raw_line_width(text, metrics);
903                    if width > limit + 0.5 && char_count > 2 {
904                        return None;
905                    }
906                }
907                Some((text, line_height_px))
908            }
909            TextOverflow::Wrap => {
910                if let Some(raw_limit) = max_width.filter(|width_val: &f32| *width_val > 0.0) {
911                    if text.starts_with(' ') || text.ends_with(' ') {
912                        return None;
913                    }
914                    let metrics: (bool, f32, f32, f32, f32, f32, f32, f32) =
915                        Self::style_metrics(style);
916                    let (width, _): (f32, usize) = Self::measure_raw_line_width(text, metrics);
917                    let limit: f32 = raw_limit.max(1.0) + WRAP_WIDTH_EPSILON;
918                    if width + 1e-3 > limit {
919                        return None;
920                    }
921                }
922                Some((text, line_height_px))
923            }
924        }
925    }
926}
927
928/// Deterministic cross-platform `TextMeasurer` implementation.
929impl TextMeasurer for DeterministicTextMeasurer {
930    /// Measures and lays out `text` identically on every operating system and rendering backend.
931    ///
932    /// # Arguments
933    ///
934    /// - `&Self` - Measurer instance.
935    /// - `&str` - Input UTF-8 string.
936    /// - `TextStyle` - Active typography style.
937    /// - `Option<f32>` - Optional maximum available width.
938    ///
939    /// # Returns
940    ///
941    /// - `TextLayoutResult` - Measured lines and bounding box.
942    fn measure(&self, text: &str, style: TextStyle, max_width: Option<f32>) -> TextLayoutResult {
943        let line_height_px: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
944        if text.is_empty() {
945            return TextLayoutResult::new(
946                Vec::new(),
947                Size::new(0.0, line_height_px),
948                line_height_px,
949            );
950        }
951        let metrics: (bool, f32, f32, f32, f32, f32, f32, f32) = Self::style_metrics(style);
952        let wrap_limit: Option<f32> = match style.get_overflow() {
953            TextOverflow::Wrap => max_width.filter(|width_val: &f32| *width_val > 0.0),
954            TextOverflow::Clip | TextOverflow::Ellipsis => None,
955        };
956        let single_raw_line: bool = !text.as_bytes().contains(&b'\n');
957        if single_raw_line && wrap_limit.is_none() {
958            let mut lines: Vec<TextLine> = Vec::with_capacity(1);
959            Self::push_unwrapped_line(text, style, max_width, metrics, &mut lines);
960            let line_w: f32 = lines[0].get_width();
961            return TextLayoutResult::new(lines, Size::new(line_w, line_height_px), line_height_px);
962        }
963        let mut lines: Vec<TextLine> = Vec::with_capacity(if single_raw_line { 1 } else { 4 });
964        if let Some(raw_limit) = wrap_limit {
965            let limit: f32 = raw_limit.max(1.0) + WRAP_WIDTH_EPSILON;
966            if single_raw_line {
967                Self::wrap_raw_line_into(text, limit, metrics, &mut lines);
968            } else {
969                for raw_line in text.split('\n') {
970                    Self::wrap_raw_line_into(raw_line, limit, metrics, &mut lines);
971                }
972            }
973        } else {
974            for raw_line in text.split('\n') {
975                Self::push_unwrapped_line(raw_line, style, max_width, metrics, &mut lines);
976            }
977        }
978        let max_line_w: f32 = lines.iter().fold(0.0_f32, |acc: f32, line: &TextLine| {
979            acc.max(line.get_width())
980        });
981        let total_h: f32 = (lines.len().max(1) as f32) * line_height_px;
982        TextLayoutResult::new(lines, Size::new(max_line_w, total_h), line_height_px)
983    }
984
985    /// Measures only the aggregate bounding box of `text` under `style` with zero heap allocations.
986    ///
987    /// # Arguments
988    ///
989    /// - `&Self` - Measurer instance.
990    /// - `&str` - Input UTF-8 string.
991    /// - `TextStyle` - Active typography style.
992    /// - `Option<f32>` - Optional maximum available width.
993    ///
994    /// # Returns
995    ///
996    /// - `Size` - Exact aggregate bounding box matching `measure(text, style, max_width).get_size()`.
997    fn measure_size(&self, text: &str, style: TextStyle, max_width: Option<f32>) -> Size {
998        let line_height_px: f32 = (style.get_font_size() * style.get_line_height()).max(1.0);
999        if text.is_empty() {
1000            return Size::new(0.0, line_height_px);
1001        }
1002        let metrics: (bool, f32, f32, f32, f32, f32, f32, f32) = Self::style_metrics(style);
1003        let wrap_limit: Option<f32> = match style.get_overflow() {
1004            TextOverflow::Wrap => max_width.filter(|width_val: &f32| *width_val > 0.0),
1005            TextOverflow::Clip | TextOverflow::Ellipsis => None,
1006        };
1007        let single_raw_line: bool = !text.as_bytes().contains(&b'\n');
1008        if single_raw_line && wrap_limit.is_none() {
1009            let (width, char_count): (f32, usize) = Self::measure_raw_line_width(text, metrics);
1010            let final_w: f32 =
1011                Self::ellipsis_line_width(text, width, char_count, style, max_width, metrics);
1012            return Size::new(final_w, line_height_px);
1013        }
1014        let mut line_count: usize = 0;
1015        let mut max_line_w: f32 = 0.0;
1016        if let Some(raw_limit) = wrap_limit {
1017            let limit: f32 = raw_limit.max(1.0) + WRAP_WIDTH_EPSILON;
1018            if single_raw_line {
1019                Self::measure_wrapped_line_size(
1020                    text,
1021                    limit,
1022                    metrics,
1023                    &mut line_count,
1024                    &mut max_line_w,
1025                );
1026            } else {
1027                for raw_line in text.split('\n') {
1028                    Self::measure_wrapped_line_size(
1029                        raw_line,
1030                        limit,
1031                        metrics,
1032                        &mut line_count,
1033                        &mut max_line_w,
1034                    );
1035                }
1036            }
1037        } else {
1038            for raw_line in text.split('\n') {
1039                let (width, char_count): (f32, usize) =
1040                    Self::measure_raw_line_width(raw_line, metrics);
1041                let final_w: f32 = Self::ellipsis_line_width(
1042                    raw_line, width, char_count, style, max_width, metrics,
1043                );
1044                if final_w > max_line_w {
1045                    max_line_w = final_w;
1046                }
1047                line_count += 1;
1048            }
1049        }
1050        let total_h: f32 = (line_count.max(1) as f32) * line_height_px;
1051        Size::new(max_line_w, total_h)
1052    }
1053}