Skip to main content

euv_core/render/terminal/
fn.rs

1use super::*;
2
3/// Returns `true` when `ch` is a zero-width combining mark, format control, or variation selector.
4///
5/// # Arguments
6///
7/// - `char` - Unicode scalar value to classify.
8///
9/// # Returns
10///
11/// - `bool` - `true` when the scalar occupies zero terminal columns.
12#[must_use]
13pub const fn is_zero_width_combining(ch: char) -> bool {
14    let code: u32 = ch as u32;
15    matches!(
16        code,
17        0x0300..=0x036F
18            | 0x0483..=0x0489
19            | 0x0591..=0x05BD
20            | 0x05BF
21            | 0x05C1..=0x05C2
22            | 0x05C4..=0x05C5
23            | 0x05C7
24            | 0x0610..=0x061A
25            | 0x064B..=0x065F
26            | 0x0670
27            | 0x06D6..=0x06DC
28            | 0x06DF..=0x06E4
29            | 0x06E7..=0x06E8
30            | 0x06EA..=0x06ED
31            | 0x1AB0..=0x1AFF
32            | 0x1DC0..=0x1DFF
33            | 0x200B..=0x200F
34            | 0x202A..=0x202E
35            | 0x2060..=0x206F
36            | 0x20D0..=0x20FF
37            | 0xFE00..=0xFE0F
38            | 0xFE20..=0xFE2F
39            | 0xFEFF
40            | 0xE0100..=0xE01EF
41    )
42}
43
44/// Returns `true` when `ch` is a Unicode Regional Indicator symbol (`U+1F1E6..=U+1F1FF`) forming flag pairs.
45///
46/// # Arguments
47///
48/// - `char` - Unicode scalar value to classify.
49///
50/// # Returns
51///
52/// - `bool` - `true` for regional indicator symbols.
53#[must_use]
54pub const fn is_regional_indicator(ch: char) -> bool {
55    let code: u32 = ch as u32;
56    code >= 0x1F1E6 && code <= 0x1F1FF
57}
58
59/// Returns `true` when `ch` is an Emoji Fitzpatrick skin-tone modifier (`U+1F3FB..=U+1F3FF`).
60///
61/// # Arguments
62///
63/// - `char` - Unicode scalar value to classify.
64///
65/// # Returns
66///
67/// - `bool` - `true` for emoji skin-tone modifiers.
68#[must_use]
69pub const fn is_emoji_modifier(ch: char) -> bool {
70    let code: u32 = ch as u32;
71    code >= 0x1F3FB && code <= 0x1F3FF
72}
73
74/// Returns `true` when `ch` is an emoji tag sequence character (`U+E0020..=U+E007F`, e.g. subdivision flags).
75///
76/// # Arguments
77///
78/// - `char` - Unicode scalar value to classify.
79///
80/// # Returns
81///
82/// - `bool` - `true` for Unicode tag characters.
83#[must_use]
84pub const fn is_tag_extend(ch: char) -> bool {
85    let code: u32 = ch as u32;
86    code >= 0xE0020 && code <= 0xE007F
87}
88
89/// Returns `true` when `ch` occupies two terminal columns (CJK ideographs, Hangul, fullwidth forms, and wide emoji).
90///
91/// # Arguments
92///
93/// - `char` - Unicode scalar value to classify.
94///
95/// # Returns
96///
97/// - `bool` - `true` when the scalar renders as double-width in standard terminals.
98#[must_use]
99pub const fn is_wide_char(ch: char) -> bool {
100    let code: u32 = ch as u32;
101    matches!(
102        code,
103        0x1100..=0x115F
104            | 0x231A..=0x231B
105            | 0x2329..=0x232A
106            | 0x23E9..=0x23EC
107            | 0x23F0
108            | 0x23F3
109            | 0x25FD..=0x25FE
110            | 0x2614..=0x2615
111            | 0x2648..=0x2653
112            | 0x267F
113            | 0x2693
114            | 0x26A1
115            | 0x26AA..=0x26AB
116            | 0x26BD..=0x26BE
117            | 0x26C4..=0x26C5
118            | 0x26CE
119            | 0x26D4
120            | 0x26EA
121            | 0x26F2..=0x26F3
122            | 0x26F5
123            | 0x26FA
124            | 0x26FD
125            | 0x2705
126            | 0x270A..=0x270B
127            | 0x2728
128            | 0x274C
129            | 0x274E
130            | 0x2753..=0x2755
131            | 0x2757
132            | 0x2795..=0x2797
133            | 0x27B0
134            | 0x27BF
135            | 0x2B1B..=0x2B1C
136            | 0x2B50
137            | 0x2B55
138            | 0x2E80..=0x303E
139            | 0x3041..=0x33FF
140            | 0x3400..=0x4DBF
141            | 0x4E00..=0xA4CF
142            | 0xA960..=0xA97F
143            | 0xAC00..=0xD7A3
144            | 0xF900..=0xFAFF
145            | 0xFE10..=0xFE19
146            | 0xFE30..=0xFE6F
147            | 0xFF01..=0xFF60
148            | 0xFFE0..=0xFFE6
149            | 0x1F300..=0x1FAFF
150            | 0x20000..=0x3FFFD
151    )
152}
153
154/// Computes the East-Asian / Unicode terminal cell display width of `ch` (`0`, `1`, or `2`).
155///
156/// # Arguments
157///
158/// - `char` - Unicode scalar value to measure.
159///
160/// # Returns
161///
162/// - `u8` - Display column width (`0` for control/combining marks, `2` for wide CJK/fullwidth/emoji, `1` otherwise).
163#[must_use]
164pub const fn terminal_char_width(ch: char) -> u8 {
165    let code: u32 = ch as u32;
166    if code <= 0x1F || (code >= 0x7F && code <= 0x9F) || is_zero_width_combining(ch) {
167        0
168    } else if is_wide_char(ch) {
169        2
170    } else {
171        1
172    }
173}
174
175/// Splits the leading Extended Grapheme Cluster from `input`, keeping combining marks, variation selectors, skin-tone modifiers, flag pairs, keycaps, and ZWJ emoji chains intact.
176///
177/// # Arguments
178///
179/// - `&str` - Remaining UTF-8 input slice.
180///
181/// # Returns
182///
183/// - `Option<(&str, &str)>` - `(cluster, rest)` pair, or `None` when `input` is empty.
184#[must_use]
185pub fn next_grapheme_cluster(input: &str) -> Option<(&str, &str)> {
186    let mut iter: Chars<'_> = input.chars();
187    let first: char = iter.next()?;
188    if first == '\r' {
189        let mut end: usize = first.len_utf8();
190        if input[end..].starts_with('\n') {
191            end += 1;
192        }
193        return Some((&input[..end], &input[end..]));
194    }
195    if first == '\n' {
196        return Some((&input[..1], &input[1..]));
197    }
198    let mut end: usize = first.len_utf8();
199    if is_regional_indicator(first)
200        && let Some(second) = input[end..].chars().next()
201        && is_regional_indicator(second)
202    {
203        end += second.len_utf8();
204    }
205    loop {
206        let rest: &str = &input[end..];
207        let Some(next_ch) = rest.chars().next() else {
208            break;
209        };
210        if next_ch == '\u{200D}' {
211            let after_zwj_offset: usize = end + next_ch.len_utf8();
212            if let Some(joined) = input[after_zwj_offset..].chars().next()
213                && joined != '\n'
214                && joined != '\r'
215            {
216                end = after_zwj_offset + joined.len_utf8();
217                continue;
218            }
219            end = after_zwj_offset;
220            continue;
221        }
222        if is_zero_width_combining(next_ch)
223            || is_emoji_modifier(next_ch)
224            || is_tag_extend(next_ch)
225            || next_ch == '\u{20E3}'
226        {
227            end += next_ch.len_utf8();
228            continue;
229        }
230        break;
231    }
232    Some((&input[..end], &input[end..]))
233}
234
235/// Computes the terminal column display width (`0`, `1`, or `2`) of a single Extended Grapheme Cluster.
236///
237/// # Arguments
238///
239/// - `&str` - Single Extended Grapheme Cluster slice.
240///
241/// # Returns
242///
243/// - `u8` - Display column width (`0`, `1`, or `2`).
244#[must_use]
245pub fn grapheme_display_width(cluster: &str) -> u8 {
246    let mut iter: Chars<'_> = cluster.chars();
247    let Some(first) = iter.next() else {
248        return 0;
249    };
250    let mut has_zwj: bool = false;
251    let mut has_emoji_vs: bool = false;
252    let mut has_text_vs: bool = false;
253    let mut has_keycap: bool = false;
254    let mut has_skin_mod: bool = false;
255    let mut regional_count: u8 = if is_regional_indicator(first) { 1 } else { 0 };
256    for ch in iter {
257        if ch == '\u{200D}' {
258            has_zwj = true;
259        } else if ch == '\u{FE0F}' {
260            has_emoji_vs = true;
261        } else if ch == '\u{FE0E}' {
262            has_text_vs = true;
263        } else if ch == '\u{20E3}' {
264            has_keycap = true;
265        } else if is_emoji_modifier(ch) {
266            has_skin_mod = true;
267        } else if is_regional_indicator(ch) {
268            regional_count = regional_count.saturating_add(1);
269        }
270    }
271    if regional_count >= 2 || has_zwj {
272        return 2;
273    }
274    if has_keycap || has_skin_mod {
275        return 2;
276    }
277    if has_emoji_vs && !has_text_vs {
278        return 2;
279    }
280    let base_w: u8 = terminal_char_width(first);
281    if has_text_vs && base_w == 2 && !is_cjk_ideograph(first) {
282        return 1;
283    }
284    base_w
285}
286
287/// Returns `true` when `ch` is a CJK/Hangul/Fullwidth ideograph unaffected by text presentation selector `\u{FE0E}`.
288///
289/// # Arguments
290///
291/// - `char` - Unicode scalar value to test.
292///
293/// # Returns
294///
295/// - `bool` - `true` for CJK/Hangul/Fullwidth characters.
296#[must_use]
297const fn is_cjk_ideograph(ch: char) -> bool {
298    let code: u32 = ch as u32;
299    matches!(
300        code,
301        0x1100..=0x115F
302            | 0x2E80..=0xA4CF
303            | 0xAC00..=0xD7A3
304            | 0xF900..=0xFAFF
305            | 0xFE10..=0xFE6F
306            | 0xFF01..=0xFF60
307            | 0xFFE0..=0xFFE6
308            | 0x20000..=0x3FFFD
309    )
310}
311
312/// Computes total terminal column width of a UTF-8 string across all Extended Grapheme Clusters.
313///
314/// # Arguments
315///
316/// - `&str` - UTF-8 text slice to measure.
317///
318/// # Returns
319///
320/// - `usize` - Sum of terminal display column widths.
321#[must_use]
322pub fn terminal_str_width(text: &str) -> usize {
323    let mut total: usize = 0;
324    let mut rest: &str = text;
325    while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
326        total = total.saturating_add(grapheme_display_width(cluster) as usize);
327        rest = next_rest;
328    }
329    total
330}
331
332/// Detects whether standard output is attached to an interactive TTY (`false` when piped or redirected, or on wasm32).
333///
334/// # Returns
335///
336/// - `bool` - `true` when stdout is an interactive terminal.
337#[must_use]
338pub fn detect_stdout_is_tty() -> bool {
339    #[cfg(not(target_arch = "wasm32"))]
340    {
341        io::stdout().is_terminal()
342    }
343    #[cfg(target_arch = "wasm32")]
344    {
345        false
346    }
347}
348
349/// Resolves whether CLI/TUI output should emit interactive ANSI diffs or zero-ANSI static plain text.
350///
351/// # Arguments
352///
353/// - `bool` - Whether stdout is an interactive TTY (`detect_stdout_is_tty()`).
354/// - `Option<bool>` - Explicit user override (`Some(true)` forces ANSI TUI, `Some(false)` forces plain text, `None` auto-detects).
355/// - `bool` - Whether `NO_COLOR` is active in the environment.
356/// - `bool` - Whether `TERM` is `"dumb"` or empty.
357///
358/// # Returns
359///
360/// - `TerminalRenderMode` - Resolved terminal output mode.
361#[must_use]
362pub const fn resolve_cli_render_mode(
363    is_tty: bool,
364    force_ansi: Option<bool>,
365    no_color: bool,
366    term_is_dumb: bool,
367) -> TerminalRenderMode {
368    match force_ansi {
369        Some(true) => TerminalRenderMode::InteractiveTui,
370        Some(false) => TerminalRenderMode::StaticPlainText,
371        None => {
372            if is_tty && !no_color && !term_is_dumb {
373                TerminalRenderMode::InteractiveTui
374            } else {
375                TerminalRenderMode::StaticPlainText
376            }
377        }
378    }
379}
380
381/// Stateless pure-text CLI renderer projecting `tree` directly into zero-ANSI UTF-8 text with zero previous-frame allocation and no event loop.
382///
383/// # Arguments
384///
385/// - `&SceneTree` - Retained UI scene tree to render.
386/// - `u16` - Target text width in columns.
387/// - `u16` - Maximum text height in rows.
388///
389/// # Returns
390///
391/// - `String` - Clean UTF-8 plain text containing zero ANSI escape sequences.
392#[must_use]
393pub fn render_static_plain_text(tree: &SceneTree, cols: u16, rows: u16) -> String {
394    let mut renderer: TerminalRenderer = TerminalRenderer::new();
395    let (plain, _): (String, TerminalDiffStats) =
396        renderer.render_tree(tree, cols, rows, TerminalRenderMode::StaticPlainText);
397    plain
398}
399
400/// Writes structured zero-ANSI static CLI output to `stdout` and optional diagnostics exclusively to `stderr`, handling `BrokenPipe` cleanly without panicking.
401///
402/// # Arguments
403///
404/// - `&SceneTree` - Retained UI scene tree to render.
405/// - `u16` - Target text width in columns.
406/// - `u16` - Maximum text height in rows.
407/// - `Option<&str>` - Optional diagnostic status message routed strictly to `stderr`.
408/// - `&mut WOut` - Destination standard output writer.
409/// - `&mut WErr` - Destination standard error writer.
410///
411/// # Returns
412///
413/// - `CliWriteStatus` - `Written`, `BrokenPipe`, or `IoError`.
414#[cfg(not(target_arch = "wasm32"))]
415pub fn write_cli_streams<WOut, WErr>(
416    tree: &SceneTree,
417    cols: u16,
418    rows: u16,
419    diagnostic: Option<&str>,
420    stdout: &mut WOut,
421    stderr: &mut WErr,
422) -> CliWriteStatus
423where
424    WOut: Write,
425    WErr: Write,
426{
427    let plain: String = render_static_plain_text(tree, cols, rows);
428    if let Err(err) = stdout.write_all(plain.as_bytes()) {
429        return classify_io_error(&err);
430    }
431    if !plain.is_empty()
432        && !plain.ends_with('\n')
433        && let Err(err) = stdout.write_all(TERMINAL_NEWLINE_BYTES)
434    {
435        return classify_io_error(&err);
436    }
437    if let Err(err) = stdout.flush() {
438        return classify_io_error(&err);
439    }
440    if let Some(diag) = diagnostic
441        && !diag.is_empty()
442    {
443        let _: io::Result<()> = stderr.write_all(diag.as_bytes());
444        if !diag.ends_with('\n') {
445            let _: io::Result<()> = stderr.write_all(TERMINAL_NEWLINE_BYTES);
446        }
447        let _: io::Result<()> = stderr.flush();
448    }
449    CliWriteStatus::Written
450}
451
452/// Classifies an `io::Error` into `CliWriteStatus::BrokenPipe` or `CliWriteStatus::IoError`.
453///
454/// # Arguments
455///
456/// - `&io::Error` - I/O error reference.
457///
458/// # Returns
459///
460/// - `CliWriteStatus` - Classified write failure status.
461#[cfg(not(target_arch = "wasm32"))]
462#[must_use]
463pub(crate) fn classify_io_error(err: &io::Error) -> CliWriteStatus {
464    if err.kind() == io::ErrorKind::BrokenPipe {
465        CliWriteStatus::BrokenPipe
466    } else {
467        CliWriteStatus::IoError
468    }
469}
470
471/// Zero-allocation unsigned decimal ASCII writer for `u32` values into `out`.
472///
473/// # Arguments
474///
475/// - `&mut String` - Destination ANSI output buffer.
476/// - `u32` - Integer to append in base 10.
477pub(crate) fn append_u32_ascii(out: &mut String, mut val: u32) {
478    let mut digits: [u8; 10] = [0; 10];
479    let mut idx: usize = 10;
480    if val == 0 {
481        out.push('0');
482        return;
483    }
484    while val > 0 {
485        idx -= 1;
486        digits[idx] = TERMINAL_ASCII_ZERO + ((val % 10) as u8);
487        val /= 10;
488    }
489    if let Ok(text) = from_utf8(&digits[idx..10]) {
490        out.push_str(text);
491    }
492}
493
494/// Zero-allocation unsigned decimal ASCII writer for `u8` channel values (`0..=255`).
495///
496/// # Arguments
497///
498/// - `&mut String` - Destination ANSI output buffer.
499/// - `u8` - Byte value to append in base 10.
500pub(crate) fn append_u8_ascii(out: &mut String, val: u8) {
501    if val >= 100 {
502        out.push((TERMINAL_ASCII_ZERO + (val / 100)) as char);
503        out.push((TERMINAL_ASCII_ZERO + ((val / 10) % 10)) as char);
504        out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
505    } else if val >= 10 {
506        out.push((TERMINAL_ASCII_ZERO + (val / 10)) as char);
507        out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
508    } else {
509        out.push((TERMINAL_ASCII_ZERO + val) as char);
510    }
511}
512
513/// Appends an ANSI cursor-positioning CSI sequence (`ESC[{row+1};{col+1}H`) into `out` without heap formatting.
514///
515/// # Arguments
516///
517/// - `&mut String` - Destination ANSI output buffer.
518/// - `u16` - Zero-based column coordinate.
519/// - `u16` - Zero-based row coordinate.
520pub(crate) fn append_cursor_move(out: &mut String, col: u16, row: u16) {
521    if col == 0 && row == 0 {
522        out.push_str(ANSI_CURSOR_HOME);
523        return;
524    }
525    out.push_str(ANSI_CSI_PREFIX);
526    append_u32_ascii(out, (row as u32) + 1);
527    out.push(';');
528    append_u32_ascii(out, (col as u32) + 1);
529    out.push('H');
530}
531
532/// Emits the shortest ANSI cursor movement from `cursor_pos` to `(col, row)` using `\x1b[H`, `\x1b[C`, `\x1b[nC`, or CUP.
533///
534/// # Arguments
535///
536/// - `&mut String` - Destination ANSI output buffer.
537/// - `Option<(u16, u16)>` - Current tracked terminal cursor `(col, row)` if known.
538/// - `u16` - Target zero-based column coordinate.
539/// - `u16` - Target zero-based row coordinate.
540pub(crate) fn append_cursor_move_smart(
541    out: &mut String,
542    cursor_pos: Option<(u16, u16)>,
543    col: u16,
544    row: u16,
545) {
546    if cursor_pos == Some((col, row)) {
547        return;
548    }
549    if col == 0 && row == 0 {
550        out.push_str(ANSI_CURSOR_HOME);
551        return;
552    }
553    if let Some((cur_col, cur_row)) = cursor_pos
554        && cur_row == row
555        && col > cur_col
556    {
557        let delta: u16 = col - cur_col;
558        if delta == 1 {
559            out.push_str(ANSI_CURSOR_RIGHT_ONE);
560            return;
561        }
562        out.push_str(ANSI_CSI_PREFIX);
563        append_u32_ascii(out, delta as u32);
564        out.push('C');
565        return;
566    }
567    append_cursor_move(out, col, row);
568}
569
570/// Appends a full ANSI SGR styling sequence for foreground, background, bold, reverse, and underline flags into `out` without heap allocation.
571///
572/// # Arguments
573///
574/// - `&mut String` - Destination ANSI output buffer.
575/// - `Option<Color>` - Optional foreground 24-bit color.
576/// - `Option<Color>` - Optional background 24-bit color.
577/// - `bool` - Bold flag.
578/// - `bool` - Reverse-video flag.
579/// - `bool` - Underline flag.
580pub(crate) fn append_sgr_style(
581    out: &mut String,
582    fg: Option<Color>,
583    bg: Option<Color>,
584    bold: bool,
585    reverse: bool,
586    underline: bool,
587) {
588    out.push_str(ANSI_CSI_PREFIX);
589    out.push('0');
590    if bold {
591        out.push_str(ANSI_BOLD_CODE);
592    }
593    if reverse {
594        out.push_str(ANSI_REVERSE_CODE);
595    }
596    if underline {
597        out.push_str(ANSI_UNDERLINE_CODE);
598    }
599    if let Some(color) = fg {
600        out.push_str(ANSI_FG_TRUECOLOR_PREFIX);
601        append_u8_ascii(out, color.get_r());
602        out.push(';');
603        append_u8_ascii(out, color.get_g());
604        out.push(';');
605        append_u8_ascii(out, color.get_b());
606    }
607    if let Some(color) = bg {
608        out.push_str(ANSI_BG_TRUECOLOR_PREFIX);
609        append_u8_ascii(out, color.get_r());
610        out.push(';');
611        append_u8_ascii(out, color.get_g());
612        out.push(';');
613        append_u8_ascii(out, color.get_b());
614    }
615    out.push('m');
616}
617
618/// Emits a minimal SGR delta transition from `prev_style` to `next`, falling back to full reset only when turning attributes off.
619///
620/// # Arguments
621///
622/// - `&mut String` - Destination ANSI output buffer.
623/// - `Option<TerminalCell>` - Active terminal style currently set in the stream.
624/// - `&TerminalCell` - Desired style for the next glyph.
625pub(crate) fn append_sgr_delta(
626    out: &mut String,
627    prev_style: Option<TerminalCell>,
628    next: &TerminalCell,
629) {
630    let Some(prev) = prev_style else {
631        append_sgr_style(
632            out,
633            next.fg_color(),
634            next.bg_color(),
635            next.get_bold(),
636            next.get_reverse(),
637            next.get_underline(),
638        );
639        return;
640    };
641    if prev.same_style(next) {
642        return;
643    }
644    let needs_reset: bool = (prev.get_bold() && !next.get_bold())
645        || (prev.get_reverse() && !next.get_reverse())
646        || (prev.get_underline() && !next.get_underline())
647        || (prev.fg_color().is_some() && next.fg_color().is_none())
648        || (prev.bg_color().is_some() && next.bg_color().is_none());
649    if needs_reset {
650        append_sgr_style(
651            out,
652            next.fg_color(),
653            next.bg_color(),
654            next.get_bold(),
655            next.get_reverse(),
656            next.get_underline(),
657        );
658        return;
659    }
660    out.push_str(ANSI_CSI_PREFIX);
661    let mut emitted: bool = false;
662    if next.get_bold() && !prev.get_bold() {
663        out.push('1');
664        emitted = true;
665    }
666    if next.get_reverse() && !prev.get_reverse() {
667        if emitted {
668            out.push(';');
669        }
670        out.push('7');
671        emitted = true;
672    }
673    if next.get_underline() && !prev.get_underline() {
674        if emitted {
675            out.push(';');
676        }
677        out.push('4');
678        emitted = true;
679    }
680    if let Some(fg) = next.fg_color()
681        && prev.fg_color() != Some(fg)
682    {
683        if emitted {
684            out.push(';');
685        }
686        out.push_str(ANSI_FG_TRUECOLOR_HEAD);
687        append_u8_ascii(out, fg.get_r());
688        out.push(';');
689        append_u8_ascii(out, fg.get_g());
690        out.push(';');
691        append_u8_ascii(out, fg.get_b());
692        emitted = true;
693    }
694    if let Some(bg) = next.bg_color()
695        && prev.bg_color() != Some(bg)
696    {
697        if emitted {
698            out.push(';');
699        }
700        out.push_str(ANSI_BG_TRUECOLOR_HEAD);
701        append_u8_ascii(out, bg.get_r());
702        out.push(';');
703        append_u8_ascii(out, bg.get_g());
704        out.push(';');
705        append_u8_ascii(out, bg.get_b());
706    }
707    out.push('m');
708}
709
710/// Mixes a `u64` value into an FNV-1a running hash state.
711///
712/// # Arguments
713///
714/// - `u64` - Current hash accumulator.
715/// - `u64` - Value to fold into the hash.
716///
717/// # Returns
718///
719/// - `u64` - Updated hash value.
720#[must_use]
721pub(crate) const fn fnv1a_mix_u64(mut hash: u64, value: u64) -> u64 {
722    let bytes: [u8; 8] = value.to_le_bytes();
723    let mut idx: usize = 0;
724    while idx < 8 {
725        hash ^= bytes[idx] as u64;
726        hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
727        idx += 1;
728    }
729    hash
730}
731
732/// Computes an FNV-1a row hash across a slice of `TerminalCell` entries for O(1) clean-row diff skipping.
733///
734/// # Arguments
735///
736/// - `&[TerminalCell]` - Row cell slice.
737///
738/// # Returns
739///
740/// - `u64` - Deterministic row hash.
741#[must_use]
742pub(crate) fn hash_terminal_row(cells: &[TerminalCell]) -> u64 {
743    let mut hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
744    for cell in cells.iter() {
745        let fg_bits: u64 = match cell.fg_color() {
746            Some(c) => {
747                0x0100_0000_u64
748                    | ((c.get_r() as u64) << 16)
749                    | ((c.get_g() as u64) << 8)
750                    | (c.get_b() as u64)
751            }
752            None => 0,
753        };
754        let bg_bits: u64 = match cell.bg_color() {
755            Some(c) => {
756                0x0100_0000_u64
757                    | ((c.get_r() as u64) << 16)
758                    | ((c.get_g() as u64) << 8)
759                    | (c.get_b() as u64)
760            }
761            None => 0,
762        };
763        let color_bits: u64 = fg_bits | (bg_bits << 32);
764        let style_bits: u64 = ((cell.get_ch() as u64) << 16)
765            | ((cell.get_width() as u64) << 8)
766            | ((cell.get_tail_len() as u64) << 3)
767            | (if cell.get_bold() { 1 } else { 0 })
768            | (if cell.get_reverse() { 2 } else { 0 })
769            | (if cell.get_underline() { 4 } else { 0 });
770        hash = (hash ^ style_bits).wrapping_mul(TERMINAL_FNV_PRIME);
771        hash = (hash ^ color_bits).wrapping_mul(TERMINAL_FNV_PRIME);
772        let tail_len: usize = cell.get_tail_len() as usize;
773        if tail_len > 0 {
774            let tail: &[u8] = cell.tail_bytes();
775            for byte in tail.iter().copied() {
776                hash ^= byte as u64;
777                hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
778            }
779        }
780    }
781    hash
782}
783
784/// Writes `payload` to `writer` and flushes with explicit backpressure handling (`WouldBlock` / `Interrupted` retry budget and partial-write tracking).
785///
786/// # Arguments
787///
788/// - `&mut W` - Target output writer (PTY, pipe, or test sink).
789/// - `&[u8]` - Coalesced UTF-8 output payload.
790///
791/// # Returns
792///
793/// - `Result<(u64, u64), (io::Error, u64, u64)>` - `Ok((bytes_written, backpressure_events))` or `Err((error, bytes_written, backpressure_events))`.
794#[cfg(not(target_arch = "wasm32"))]
795pub(crate) fn write_all_with_backpressure<W>(
796    writer: &mut W,
797    payload: &[u8],
798) -> Result<(u64, u64), (io::Error, u64, u64)>
799where
800    W: Write,
801{
802    let mut offset: usize = 0;
803    let mut backpressure_events: u64 = 0;
804    let mut retries: usize = 0;
805    while offset < payload.len() {
806        match writer.write(&payload[offset..]) {
807            Ok(0) => {
808                return Err((
809                    io::Error::new(ErrorKind::WriteZero, ERR_TERMINAL_WRITE_ZERO),
810                    offset as u64,
811                    backpressure_events,
812                ));
813            }
814            Ok(written) => {
815                offset = offset.saturating_add(written);
816                retries = 0;
817                if offset < payload.len() {
818                    backpressure_events = backpressure_events.saturating_add(1);
819                }
820            }
821            Err(err)
822                if matches!(err.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock)
823                    && retries < TERMINAL_BACKPRESSURE_MAX_RETRIES =>
824            {
825                backpressure_events = backpressure_events.saturating_add(1);
826                retries = retries.saturating_add(1);
827            }
828            Err(err) => {
829                return Err((err, offset as u64, backpressure_events));
830            }
831        }
832    }
833    let mut flush_retries: usize = 0;
834    loop {
835        match writer.flush() {
836            Ok(()) => break,
837            Err(err)
838                if matches!(err.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock)
839                    && flush_retries < TERMINAL_BACKPRESSURE_MAX_RETRIES =>
840            {
841                backpressure_events = backpressure_events.saturating_add(1);
842                flush_retries = flush_retries.saturating_add(1);
843            }
844            Err(err) => {
845                return Err((err, offset as u64, backpressure_events));
846            }
847        }
848    }
849    Ok((offset as u64, backpressure_events))
850}
851
852/// Coalesces CLI output `chunks` into bounded batches up to `max_batch_bytes` with explicit backpressure handling and non-Hz telemetry.
853///
854/// # Arguments
855///
856/// - `&mut W` - Destination CLI writer (stdout, pipe, or deterministic buffer).
857/// - `&[&str]` - Ordered UTF-8 output chunks to batch.
858/// - `usize` - Maximum byte size per flushed batch (`>= 1`).
859///
860/// # Returns
861///
862/// - `TerminalWriteResult` - Write status and explicit non-GPU, non-Hz telemetry (`flush_latency_ms`, `bytes_written`, `backpressure_events`, `batched_flush_count`).
863#[cfg(not(target_arch = "wasm32"))]
864pub fn write_cli_batched_output<W>(
865    writer: &mut W,
866    chunks: &[&str],
867    max_batch_bytes: usize,
868) -> TerminalWriteResult
869where
870    W: Write,
871{
872    let batch_cap: usize = max_batch_bytes.max(1);
873    let mut batch_buf: Vec<u8> =
874        Vec::with_capacity(batch_cap.min(TERMINAL_CLI_DEFAULT_BATCH_LIMIT));
875    let mut total_written: u64 = 0;
876    let mut total_bp: u64 = 0;
877    let mut flush_count: u64 = 0;
878    let start: Instant = Instant::now();
879    for chunk in chunks.iter() {
880        let bytes: &[u8] = chunk.as_bytes();
881        if bytes.is_empty() {
882            continue;
883        }
884        if !batch_buf.is_empty() && batch_buf.len().saturating_add(bytes.len()) > batch_cap {
885            match write_all_with_backpressure(writer, batch_buf.as_slice()) {
886                Ok((written, bp)) => {
887                    total_written = total_written.saturating_add(written);
888                    total_bp = total_bp.saturating_add(bp);
889                    flush_count = flush_count.saturating_add(1);
890                }
891                Err((err, written, bp)) => {
892                    let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
893                    total_written = total_written.saturating_add(written);
894                    total_bp = total_bp.saturating_add(bp).saturating_add(1);
895                    let status: CliWriteStatus = classify_io_error(&err);
896                    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
897                        mode: TerminalRenderMode::StaticPlainText,
898                        gpu_routing_opted_out: true,
899                        uses_screen_hz: false,
900                        input_to_output_ms: None,
901                        flush_latency_ms: elapsed_ms,
902                        bytes_written: total_written,
903                        total_bytes_written: total_written,
904                        changed_cells: 0,
905                        unchanged_frame_skipped: false,
906                        backpressure_events: total_bp,
907                        batched_flush_count: flush_count,
908                    };
909                    return TerminalWriteResult {
910                        status,
911                        stats: TerminalDiffStats::new(0, 0, total_written as usize, false, false),
912                        swapped: false,
913                        error_message: Some(err.to_string()),
914                        telemetry,
915                    };
916                }
917            }
918            batch_buf.clear();
919        }
920        if bytes.len() > batch_cap {
921            for slice in bytes.chunks(batch_cap) {
922                match write_all_with_backpressure(writer, slice) {
923                    Ok((written, bp)) => {
924                        total_written = total_written.saturating_add(written);
925                        total_bp = total_bp.saturating_add(bp);
926                        flush_count = flush_count.saturating_add(1);
927                    }
928                    Err((err, written, bp)) => {
929                        let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
930                        total_written = total_written.saturating_add(written);
931                        total_bp = total_bp.saturating_add(bp).saturating_add(1);
932                        let status: CliWriteStatus = classify_io_error(&err);
933                        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
934                            mode: TerminalRenderMode::StaticPlainText,
935                            gpu_routing_opted_out: true,
936                            uses_screen_hz: false,
937                            input_to_output_ms: None,
938                            flush_latency_ms: elapsed_ms,
939                            bytes_written: total_written,
940                            total_bytes_written: total_written,
941                            changed_cells: 0,
942                            unchanged_frame_skipped: false,
943                            backpressure_events: total_bp,
944                            batched_flush_count: flush_count,
945                        };
946                        return TerminalWriteResult {
947                            status,
948                            stats: TerminalDiffStats::new(
949                                0,
950                                0,
951                                total_written as usize,
952                                false,
953                                false,
954                            ),
955                            swapped: false,
956                            error_message: Some(err.to_string()),
957                            telemetry,
958                        };
959                    }
960                }
961            }
962        } else {
963            batch_buf.extend_from_slice(bytes);
964        }
965    }
966    if !batch_buf.is_empty() {
967        match write_all_with_backpressure(writer, batch_buf.as_slice()) {
968            Ok((written, bp)) => {
969                total_written = total_written.saturating_add(written);
970                total_bp = total_bp.saturating_add(bp);
971                flush_count = flush_count.saturating_add(1);
972            }
973            Err((err, written, bp)) => {
974                let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
975                total_written = total_written.saturating_add(written);
976                total_bp = total_bp.saturating_add(bp).saturating_add(1);
977                let status: CliWriteStatus = classify_io_error(&err);
978                let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
979                    mode: TerminalRenderMode::StaticPlainText,
980                    gpu_routing_opted_out: true,
981                    uses_screen_hz: false,
982                    input_to_output_ms: None,
983                    flush_latency_ms: elapsed_ms,
984                    bytes_written: total_written,
985                    total_bytes_written: total_written,
986                    changed_cells: 0,
987                    unchanged_frame_skipped: false,
988                    backpressure_events: total_bp,
989                    batched_flush_count: flush_count,
990                };
991                return TerminalWriteResult {
992                    status,
993                    stats: TerminalDiffStats::new(0, 0, total_written as usize, false, false),
994                    swapped: false,
995                    error_message: Some(err.to_string()),
996                    telemetry,
997                };
998            }
999        }
1000    }
1001    let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
1002    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
1003        mode: TerminalRenderMode::StaticPlainText,
1004        gpu_routing_opted_out: true,
1005        uses_screen_hz: false,
1006        input_to_output_ms: None,
1007        flush_latency_ms: elapsed_ms,
1008        bytes_written: total_written,
1009        total_bytes_written: total_written,
1010        changed_cells: 0,
1011        unchanged_frame_skipped: total_written == 0,
1012        backpressure_events: total_bp,
1013        batched_flush_count: flush_count,
1014    };
1015    TerminalWriteResult {
1016        status: CliWriteStatus::Written,
1017        stats: TerminalDiffStats::new(0, 0, total_written as usize, total_written == 0, false),
1018        swapped: false,
1019        error_message: None,
1020        telemetry,
1021    }
1022}