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