euv-core 0.48.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
use super::*;

/// Returns `true` when `ch` is a zero-width combining mark, format control, or variation selector.
///
/// # Arguments
///
/// - `char` - Unicode scalar value to classify.
///
/// # Returns
///
/// - `bool` - `true` when the scalar occupies zero terminal columns.
#[must_use]
pub const fn is_zero_width_combining(ch: char) -> bool {
    let code: u32 = ch as u32;
    matches!(
        code,
        0x0300..=0x036F
            | 0x0483..=0x0489
            | 0x0591..=0x05BD
            | 0x05BF
            | 0x05C1..=0x05C2
            | 0x05C4..=0x05C5
            | 0x05C7
            | 0x0610..=0x061A
            | 0x064B..=0x065F
            | 0x0670
            | 0x06D6..=0x06DC
            | 0x06DF..=0x06E4
            | 0x06E7..=0x06E8
            | 0x06EA..=0x06ED
            | 0x1AB0..=0x1AFF
            | 0x1DC0..=0x1DFF
            | 0x200B..=0x200F
            | 0x202A..=0x202E
            | 0x2060..=0x206F
            | 0x20D0..=0x20FF
            | 0xFE00..=0xFE0F
            | 0xFE20..=0xFE2F
            | 0xFEFF
            | 0xE0100..=0xE01EF
    )
}

/// Returns `true` when `ch` is a Unicode Regional Indicator symbol (`U+1F1E6..=U+1F1FF`) forming flag pairs.
///
/// # Arguments
///
/// - `char` - Unicode scalar value to classify.
///
/// # Returns
///
/// - `bool` - `true` for regional indicator symbols.
#[must_use]
pub const fn is_regional_indicator(ch: char) -> bool {
    let code: u32 = ch as u32;
    code >= 0x1F1E6 && code <= 0x1F1FF
}

/// Returns `true` when `ch` is an Emoji Fitzpatrick skin-tone modifier (`U+1F3FB..=U+1F3FF`).
///
/// # Arguments
///
/// - `char` - Unicode scalar value to classify.
///
/// # Returns
///
/// - `bool` - `true` for emoji skin-tone modifiers.
#[must_use]
pub const fn is_emoji_modifier(ch: char) -> bool {
    let code: u32 = ch as u32;
    code >= 0x1F3FB && code <= 0x1F3FF
}

/// Returns `true` when `ch` is an emoji tag sequence character (`U+E0020..=U+E007F`, e.g. subdivision flags).
///
/// # Arguments
///
/// - `char` - Unicode scalar value to classify.
///
/// # Returns
///
/// - `bool` - `true` for Unicode tag characters.
#[must_use]
pub const fn is_tag_extend(ch: char) -> bool {
    let code: u32 = ch as u32;
    code >= 0xE0020 && code <= 0xE007F
}

/// Returns `true` when `ch` occupies two terminal columns (CJK ideographs, Hangul, fullwidth forms, and wide emoji).
///
/// # Arguments
///
/// - `char` - Unicode scalar value to classify.
///
/// # Returns
///
/// - `bool` - `true` when the scalar renders as double-width in standard terminals.
#[must_use]
pub const fn is_wide_char(ch: char) -> bool {
    let code: u32 = ch as u32;
    matches!(
        code,
        0x1100..=0x115F
            | 0x231A..=0x231B
            | 0x2329..=0x232A
            | 0x23E9..=0x23EC
            | 0x23F0
            | 0x23F3
            | 0x25FD..=0x25FE
            | 0x2614..=0x2615
            | 0x2648..=0x2653
            | 0x267F
            | 0x2693
            | 0x26A1
            | 0x26AA..=0x26AB
            | 0x26BD..=0x26BE
            | 0x26C4..=0x26C5
            | 0x26CE
            | 0x26D4
            | 0x26EA
            | 0x26F2..=0x26F3
            | 0x26F5
            | 0x26FA
            | 0x26FD
            | 0x2705
            | 0x270A..=0x270B
            | 0x2728
            | 0x274C
            | 0x274E
            | 0x2753..=0x2755
            | 0x2757
            | 0x2795..=0x2797
            | 0x27B0
            | 0x27BF
            | 0x2B1B..=0x2B1C
            | 0x2B50
            | 0x2B55
            | 0x2E80..=0x303E
            | 0x3041..=0x33FF
            | 0x3400..=0x4DBF
            | 0x4E00..=0xA4CF
            | 0xA960..=0xA97F
            | 0xAC00..=0xD7A3
            | 0xF900..=0xFAFF
            | 0xFE10..=0xFE19
            | 0xFE30..=0xFE6F
            | 0xFF01..=0xFF60
            | 0xFFE0..=0xFFE6
            | 0x1F300..=0x1FAFF
            | 0x20000..=0x3FFFD
    )
}

/// Computes the East-Asian / Unicode terminal cell display width of `ch` (`0`, `1`, or `2`).
///
/// # Arguments
///
/// - `char` - Unicode scalar value to measure.
///
/// # Returns
///
/// - `u8` - Display column width (`0` for control/combining marks, `2` for wide CJK/fullwidth/emoji, `1` otherwise).
#[must_use]
pub const fn terminal_char_width(ch: char) -> u8 {
    let code: u32 = ch as u32;
    if code <= 0x1F || (code >= 0x7F && code <= 0x9F) || is_zero_width_combining(ch) {
        0
    } else if is_wide_char(ch) {
        2
    } else {
        1
    }
}

/// Splits the leading Extended Grapheme Cluster from `input`, keeping combining marks, variation selectors, skin-tone modifiers, flag pairs, keycaps, and ZWJ emoji chains intact.
///
/// # Arguments
///
/// - `&str` - Remaining UTF-8 input slice.
///
/// # Returns
///
/// - `Option<(&str, &str)>` - `(cluster, rest)` pair, or `None` when `input` is empty.
#[must_use]
pub fn next_grapheme_cluster(input: &str) -> Option<(&str, &str)> {
    let mut iter: Chars<'_> = input.chars();
    let first: char = iter.next()?;
    if first == '\r' {
        let mut end: usize = first.len_utf8();
        if input[end..].starts_with('\n') {
            end += 1;
        }
        return Some((&input[..end], &input[end..]));
    }
    if first == '\n' {
        return Some((&input[..1], &input[1..]));
    }
    let mut end: usize = first.len_utf8();
    if is_regional_indicator(first)
        && let Some(second) = input[end..].chars().next()
        && is_regional_indicator(second)
    {
        end += second.len_utf8();
    }
    loop {
        let rest: &str = &input[end..];
        let Some(next_ch) = rest.chars().next() else {
            break;
        };
        if next_ch == '\u{200D}' {
            let after_zwj_offset: usize = end + next_ch.len_utf8();
            if let Some(joined) = input[after_zwj_offset..].chars().next()
                && joined != '\n'
                && joined != '\r'
            {
                end = after_zwj_offset + joined.len_utf8();
                continue;
            }
            end = after_zwj_offset;
            continue;
        }
        if is_zero_width_combining(next_ch)
            || is_emoji_modifier(next_ch)
            || is_tag_extend(next_ch)
            || next_ch == '\u{20E3}'
        {
            end += next_ch.len_utf8();
            continue;
        }
        break;
    }
    Some((&input[..end], &input[end..]))
}

/// Computes the terminal column display width (`0`, `1`, or `2`) of a single Extended Grapheme Cluster.
///
/// # Arguments
///
/// - `&str` - Single Extended Grapheme Cluster slice.
///
/// # Returns
///
/// - `u8` - Display column width (`0`, `1`, or `2`).
#[must_use]
pub fn grapheme_display_width(cluster: &str) -> u8 {
    let mut iter: Chars<'_> = cluster.chars();
    let Some(first) = iter.next() else {
        return 0;
    };
    let mut has_zwj: bool = false;
    let mut has_emoji_vs: bool = false;
    let mut has_text_vs: bool = false;
    let mut has_keycap: bool = false;
    let mut has_skin_mod: bool = false;
    let mut regional_count: u8 = if is_regional_indicator(first) { 1 } else { 0 };
    for ch in iter {
        if ch == '\u{200D}' {
            has_zwj = true;
        } else if ch == '\u{FE0F}' {
            has_emoji_vs = true;
        } else if ch == '\u{FE0E}' {
            has_text_vs = true;
        } else if ch == '\u{20E3}' {
            has_keycap = true;
        } else if is_emoji_modifier(ch) {
            has_skin_mod = true;
        } else if is_regional_indicator(ch) {
            regional_count = regional_count.saturating_add(1);
        }
    }
    if regional_count >= 2 || has_zwj {
        return 2;
    }
    if has_keycap || has_skin_mod {
        return 2;
    }
    if has_emoji_vs && !has_text_vs {
        return 2;
    }
    let base_w: u8 = terminal_char_width(first);
    if has_text_vs && base_w == 2 && !is_cjk_ideograph(first) {
        return 1;
    }
    base_w
}

/// Returns `true` when `ch` is a CJK/Hangul/Fullwidth ideograph unaffected by text presentation selector `\u{FE0E}`.
///
/// # Arguments
///
/// - `char` - Unicode scalar value to test.
///
/// # Returns
///
/// - `bool` - `true` for CJK/Hangul/Fullwidth characters.
#[must_use]
const fn is_cjk_ideograph(ch: char) -> bool {
    let code: u32 = ch as u32;
    matches!(
        code,
        0x1100..=0x115F
            | 0x2E80..=0xA4CF
            | 0xAC00..=0xD7A3
            | 0xF900..=0xFAFF
            | 0xFE10..=0xFE6F
            | 0xFF01..=0xFF60
            | 0xFFE0..=0xFFE6
            | 0x20000..=0x3FFFD
    )
}

/// Computes total terminal column width of a UTF-8 string across all Extended Grapheme Clusters.
///
/// # Arguments
///
/// - `&str` - UTF-8 text slice to measure.
///
/// # Returns
///
/// - `usize` - Sum of terminal display column widths.
#[must_use]
pub fn terminal_str_width(text: &str) -> usize {
    let mut total: usize = 0;
    let mut rest: &str = text;
    while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
        total = total.saturating_add(grapheme_display_width(cluster) as usize);
        rest = next_rest;
    }
    total
}

/// Detects whether standard output is attached to an interactive TTY (`false` when piped or redirected, or on wasm32).
///
/// # Returns
///
/// - `bool` - `true` when stdout is an interactive terminal.
#[must_use]
pub fn detect_stdout_is_tty() -> bool {
    #[cfg(not(target_arch = "wasm32"))]
    {
        io::stdout().is_terminal()
    }
    #[cfg(target_arch = "wasm32")]
    {
        false
    }
}

/// Resolves whether CLI/TUI output should emit interactive ANSI diffs or zero-ANSI static plain text.
///
/// # Arguments
///
/// - `bool` - Whether stdout is an interactive TTY (`detect_stdout_is_tty()`).
/// - `Option<bool>` - Explicit user override (`Some(true)` forces ANSI TUI, `Some(false)` forces plain text, `None` auto-detects).
/// - `bool` - Whether `NO_COLOR` is active in the environment.
/// - `bool` - Whether `TERM` is `"dumb"` or empty.
///
/// # Returns
///
/// - `TerminalRenderMode` - Resolved terminal output mode.
#[must_use]
pub const fn resolve_cli_render_mode(
    is_tty: bool,
    force_ansi: Option<bool>,
    no_color: bool,
    term_is_dumb: bool,
) -> TerminalRenderMode {
    match force_ansi {
        Some(true) => TerminalRenderMode::InteractiveTui,
        Some(false) => TerminalRenderMode::StaticPlainText,
        None => {
            if is_tty && !no_color && !term_is_dumb {
                TerminalRenderMode::InteractiveTui
            } else {
                TerminalRenderMode::StaticPlainText
            }
        }
    }
}

/// Stateless pure-text CLI renderer projecting `tree` directly into zero-ANSI UTF-8 text with zero previous-frame allocation and no event loop.
///
/// # Arguments
///
/// - `&SceneTree` - Retained UI scene tree to render.
/// - `u16` - Target text width in columns.
/// - `u16` - Maximum text height in rows.
///
/// # Returns
///
/// - `String` - Clean UTF-8 plain text containing zero ANSI escape sequences.
#[must_use]
pub fn render_static_plain_text(tree: &SceneTree, cols: u16, rows: u16) -> String {
    let mut renderer: TerminalRenderer = TerminalRenderer::new();
    let (plain, _): (String, TerminalDiffStats) =
        renderer.render_tree(tree, cols, rows, TerminalRenderMode::StaticPlainText);
    plain
}

/// Writes structured zero-ANSI static CLI output to `stdout` and optional diagnostics exclusively to `stderr`, handling `BrokenPipe` cleanly without panicking.
///
/// # Arguments
///
/// - `&SceneTree` - Retained UI scene tree to render.
/// - `u16` - Target text width in columns.
/// - `u16` - Maximum text height in rows.
/// - `Option<&str>` - Optional diagnostic status message routed strictly to `stderr`.
/// - `&mut WOut` - Destination standard output writer.
/// - `&mut WErr` - Destination standard error writer.
///
/// # Returns
///
/// - `CliWriteStatus` - `Written`, `BrokenPipe`, or `IoError`.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_cli_streams<WOut, WErr>(
    tree: &SceneTree,
    cols: u16,
    rows: u16,
    diagnostic: Option<&str>,
    stdout: &mut WOut,
    stderr: &mut WErr,
) -> CliWriteStatus
where
    WOut: Write,
    WErr: Write,
{
    let plain: String = render_static_plain_text(tree, cols, rows);
    if let Err(err) = stdout.write_all(plain.as_bytes()) {
        return classify_io_error(&err);
    }
    if !plain.is_empty()
        && !plain.ends_with('\n')
        && let Err(err) = stdout.write_all(TERMINAL_NEWLINE_BYTES)
    {
        return classify_io_error(&err);
    }
    if let Err(err) = stdout.flush() {
        return classify_io_error(&err);
    }
    if let Some(diag) = diagnostic
        && !diag.is_empty()
    {
        let _: io::Result<()> = stderr.write_all(diag.as_bytes());
        if !diag.ends_with('\n') {
            let _: io::Result<()> = stderr.write_all(TERMINAL_NEWLINE_BYTES);
        }
        let _: io::Result<()> = stderr.flush();
    }
    CliWriteStatus::Written
}

/// Classifies an `io::Error` into `CliWriteStatus::BrokenPipe` or `CliWriteStatus::IoError`.
///
/// # Arguments
///
/// - `&io::Error` - I/O error reference.
///
/// # Returns
///
/// - `CliWriteStatus` - Classified write failure status.
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub(crate) fn classify_io_error(err: &io::Error) -> CliWriteStatus {
    if err.kind() == io::ErrorKind::BrokenPipe {
        CliWriteStatus::BrokenPipe
    } else {
        CliWriteStatus::IoError
    }
}

/// Zero-allocation unsigned decimal ASCII writer for `u32` values into `out`.
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `u32` - Integer to append in base 10.
pub(crate) fn append_u32_ascii(out: &mut String, mut val: u32) {
    let mut digits: [u8; 10] = [0; 10];
    let mut idx: usize = 10;
    if val == 0 {
        out.push('0');
        return;
    }
    while val > 0 {
        idx -= 1;
        digits[idx] = TERMINAL_ASCII_ZERO + ((val % 10) as u8);
        val /= 10;
    }
    if let Ok(text) = from_utf8(&digits[idx..10]) {
        out.push_str(text);
    }
}

/// Zero-allocation unsigned decimal ASCII writer for `u8` channel values (`0..=255`).
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `u8` - Byte value to append in base 10.
pub(crate) fn append_u8_ascii(out: &mut String, val: u8) {
    if val >= 100 {
        out.push((TERMINAL_ASCII_ZERO + (val / 100)) as char);
        out.push((TERMINAL_ASCII_ZERO + ((val / 10) % 10)) as char);
        out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
    } else if val >= 10 {
        out.push((TERMINAL_ASCII_ZERO + (val / 10)) as char);
        out.push((TERMINAL_ASCII_ZERO + (val % 10)) as char);
    } else {
        out.push((TERMINAL_ASCII_ZERO + val) as char);
    }
}

/// Appends an ANSI cursor-positioning CSI sequence (`ESC[{row+1};{col+1}H`) into `out` without heap formatting.
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `u16` - Zero-based column coordinate.
/// - `u16` - Zero-based row coordinate.
pub(crate) fn append_cursor_move(out: &mut String, col: u16, row: u16) {
    if col == 0 && row == 0 {
        out.push_str(ANSI_CURSOR_HOME);
        return;
    }
    out.push_str(ANSI_CSI_PREFIX);
    append_u32_ascii(out, (row as u32) + 1);
    out.push(';');
    append_u32_ascii(out, (col as u32) + 1);
    out.push('H');
}

/// Emits the shortest ANSI cursor movement from `cursor_pos` to `(col, row)` using `\x1b[H`, `\x1b[C`, `\x1b[nC`, or CUP.
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `Option<(u16, u16)>` - Current tracked terminal cursor `(col, row)` if known.
/// - `u16` - Target zero-based column coordinate.
/// - `u16` - Target zero-based row coordinate.
pub(crate) fn append_cursor_move_smart(
    out: &mut String,
    cursor_pos: Option<(u16, u16)>,
    col: u16,
    row: u16,
) {
    if cursor_pos == Some((col, row)) {
        return;
    }
    if col == 0 && row == 0 {
        out.push_str(ANSI_CURSOR_HOME);
        return;
    }
    if let Some((cur_col, cur_row)) = cursor_pos
        && cur_row == row
        && col > cur_col
    {
        let delta: u16 = col - cur_col;
        if delta == 1 {
            out.push_str(ANSI_CURSOR_RIGHT_ONE);
            return;
        }
        out.push_str(ANSI_CSI_PREFIX);
        append_u32_ascii(out, delta as u32);
        out.push('C');
        return;
    }
    append_cursor_move(out, col, row);
}

/// Appends a full ANSI SGR styling sequence for foreground, background, bold, reverse, and underline flags into `out` without heap allocation.
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `Option<Color>` - Optional foreground 24-bit color.
/// - `Option<Color>` - Optional background 24-bit color.
/// - `bool` - Bold flag.
/// - `bool` - Reverse-video flag.
/// - `bool` - Underline flag.
pub(crate) fn append_sgr_style(
    out: &mut String,
    fg: Option<Color>,
    bg: Option<Color>,
    bold: bool,
    reverse: bool,
    underline: bool,
) {
    out.push_str(ANSI_CSI_PREFIX);
    out.push('0');
    if bold {
        out.push_str(ANSI_BOLD_CODE);
    }
    if reverse {
        out.push_str(ANSI_REVERSE_CODE);
    }
    if underline {
        out.push_str(ANSI_UNDERLINE_CODE);
    }
    if let Some(color) = fg {
        out.push_str(ANSI_FG_TRUECOLOR_PREFIX);
        append_u8_ascii(out, color.get_r());
        out.push(';');
        append_u8_ascii(out, color.get_g());
        out.push(';');
        append_u8_ascii(out, color.get_b());
    }
    if let Some(color) = bg {
        out.push_str(ANSI_BG_TRUECOLOR_PREFIX);
        append_u8_ascii(out, color.get_r());
        out.push(';');
        append_u8_ascii(out, color.get_g());
        out.push(';');
        append_u8_ascii(out, color.get_b());
    }
    out.push('m');
}

/// Emits a minimal SGR delta transition from `prev_style` to `next`, falling back to full reset only when turning attributes off.
///
/// # Arguments
///
/// - `&mut String` - Destination ANSI output buffer.
/// - `Option<TerminalCell>` - Active terminal style currently set in the stream.
/// - `&TerminalCell` - Desired style for the next glyph.
pub(crate) fn append_sgr_delta(
    out: &mut String,
    prev_style: Option<TerminalCell>,
    next: &TerminalCell,
) {
    let Some(prev) = prev_style else {
        append_sgr_style(
            out,
            next.fg_color(),
            next.bg_color(),
            next.get_bold(),
            next.get_reverse(),
            next.get_underline(),
        );
        return;
    };
    if prev.same_style(next) {
        return;
    }
    let needs_reset: bool = (prev.get_bold() && !next.get_bold())
        || (prev.get_reverse() && !next.get_reverse())
        || (prev.get_underline() && !next.get_underline())
        || (prev.fg_color().is_some() && next.fg_color().is_none())
        || (prev.bg_color().is_some() && next.bg_color().is_none());
    if needs_reset {
        append_sgr_style(
            out,
            next.fg_color(),
            next.bg_color(),
            next.get_bold(),
            next.get_reverse(),
            next.get_underline(),
        );
        return;
    }
    out.push_str(ANSI_CSI_PREFIX);
    let mut emitted: bool = false;
    if next.get_bold() && !prev.get_bold() {
        out.push('1');
        emitted = true;
    }
    if next.get_reverse() && !prev.get_reverse() {
        if emitted {
            out.push(';');
        }
        out.push('7');
        emitted = true;
    }
    if next.get_underline() && !prev.get_underline() {
        if emitted {
            out.push(';');
        }
        out.push('4');
        emitted = true;
    }
    if let Some(fg) = next.fg_color()
        && prev.fg_color() != Some(fg)
    {
        if emitted {
            out.push(';');
        }
        out.push_str(ANSI_FG_TRUECOLOR_HEAD);
        append_u8_ascii(out, fg.get_r());
        out.push(';');
        append_u8_ascii(out, fg.get_g());
        out.push(';');
        append_u8_ascii(out, fg.get_b());
        emitted = true;
    }
    if let Some(bg) = next.bg_color()
        && prev.bg_color() != Some(bg)
    {
        if emitted {
            out.push(';');
        }
        out.push_str(ANSI_BG_TRUECOLOR_HEAD);
        append_u8_ascii(out, bg.get_r());
        out.push(';');
        append_u8_ascii(out, bg.get_g());
        out.push(';');
        append_u8_ascii(out, bg.get_b());
    }
    out.push('m');
}

/// Mixes a `u64` value into an FNV-1a running hash state.
///
/// # Arguments
///
/// - `u64` - Current hash accumulator.
/// - `u64` - Value to fold into the hash.
///
/// # Returns
///
/// - `u64` - Updated hash value.
#[must_use]
pub(crate) const fn fnv1a_mix_u64(mut hash: u64, value: u64) -> u64 {
    let bytes: [u8; 8] = value.to_le_bytes();
    let mut idx: usize = 0;
    while idx < 8 {
        hash ^= bytes[idx] as u64;
        hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
        idx += 1;
    }
    hash
}

/// Computes an FNV-1a row hash across a slice of `TerminalCell` entries for O(1) clean-row diff skipping.
///
/// # Arguments
///
/// - `&[TerminalCell]` - Row cell slice.
///
/// # Returns
///
/// - `u64` - Deterministic row hash.
#[must_use]
pub(crate) fn hash_terminal_row(cells: &[TerminalCell]) -> u64 {
    let mut hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
    for cell in cells.iter() {
        let fg_bits: u64 = match cell.fg_color() {
            Some(c) => {
                0x0100_0000_u64
                    | ((c.get_r() as u64) << 16)
                    | ((c.get_g() as u64) << 8)
                    | (c.get_b() as u64)
            }
            None => 0,
        };
        let bg_bits: u64 = match cell.bg_color() {
            Some(c) => {
                0x0100_0000_u64
                    | ((c.get_r() as u64) << 16)
                    | ((c.get_g() as u64) << 8)
                    | (c.get_b() as u64)
            }
            None => 0,
        };
        let color_bits: u64 = fg_bits | (bg_bits << 32);
        let style_bits: u64 = ((cell.get_ch() as u64) << 16)
            | ((cell.get_width() as u64) << 8)
            | ((cell.get_tail_len() as u64) << 3)
            | (if cell.get_bold() { 1 } else { 0 })
            | (if cell.get_reverse() { 2 } else { 0 })
            | (if cell.get_underline() { 4 } else { 0 });
        hash = (hash ^ style_bits).wrapping_mul(TERMINAL_FNV_PRIME);
        hash = (hash ^ color_bits).wrapping_mul(TERMINAL_FNV_PRIME);
        let tail_len: usize = cell.get_tail_len() as usize;
        if tail_len > 0 {
            let tail: &[u8] = cell.tail_bytes();
            for byte in tail.iter().copied() {
                hash ^= byte as u64;
                hash = hash.wrapping_mul(TERMINAL_FNV_PRIME);
            }
        }
    }
    hash
}

/// Writes `payload` to `writer` and flushes with explicit backpressure handling (`WouldBlock` / `Interrupted` retry budget and partial-write tracking).
///
/// # Arguments
///
/// - `&mut W` - Target output writer (PTY, pipe, or test sink).
/// - `&[u8]` - Coalesced UTF-8 output payload.
///
/// # Returns
///
/// - `Result<(u64, u64), (io::Error, u64, u64)>` - `Ok((bytes_written, backpressure_events))` or `Err((error, bytes_written, backpressure_events))`.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn write_all_with_backpressure<W>(
    writer: &mut W,
    payload: &[u8],
) -> Result<(u64, u64), (io::Error, u64, u64)>
where
    W: Write,
{
    let mut offset: usize = 0;
    let mut backpressure_events: u64 = 0;
    let mut retries: usize = 0;
    while offset < payload.len() {
        match writer.write(&payload[offset..]) {
            Ok(0) => {
                return Err((
                    io::Error::new(ErrorKind::WriteZero, ERR_TERMINAL_WRITE_ZERO),
                    offset as u64,
                    backpressure_events,
                ));
            }
            Ok(written) => {
                offset = offset.saturating_add(written);
                retries = 0;
                if offset < payload.len() {
                    backpressure_events = backpressure_events.saturating_add(1);
                }
            }
            Err(err)
                if matches!(err.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock)
                    && retries < TERMINAL_BACKPRESSURE_MAX_RETRIES =>
            {
                backpressure_events = backpressure_events.saturating_add(1);
                retries = retries.saturating_add(1);
            }
            Err(err) => {
                return Err((err, offset as u64, backpressure_events));
            }
        }
    }
    let mut flush_retries: usize = 0;
    loop {
        match writer.flush() {
            Ok(()) => break,
            Err(err)
                if matches!(err.kind(), ErrorKind::Interrupted | ErrorKind::WouldBlock)
                    && flush_retries < TERMINAL_BACKPRESSURE_MAX_RETRIES =>
            {
                backpressure_events = backpressure_events.saturating_add(1);
                flush_retries = flush_retries.saturating_add(1);
            }
            Err(err) => {
                return Err((err, offset as u64, backpressure_events));
            }
        }
    }
    Ok((offset as u64, backpressure_events))
}

/// Coalesces CLI output `chunks` into bounded batches up to `max_batch_bytes` with explicit backpressure handling and non-Hz telemetry.
///
/// # Arguments
///
/// - `&mut W` - Destination CLI writer (stdout, pipe, or deterministic buffer).
/// - `&[&str]` - Ordered UTF-8 output chunks to batch.
/// - `usize` - Maximum byte size per flushed batch (`>= 1`).
///
/// # Returns
///
/// - `TerminalWriteResult` - Write status and explicit non-GPU, non-Hz telemetry (`flush_latency_ms`, `bytes_written`, `backpressure_events`, `batched_flush_count`).
#[cfg(not(target_arch = "wasm32"))]
pub fn write_cli_batched_output<W>(
    writer: &mut W,
    chunks: &[&str],
    max_batch_bytes: usize,
) -> TerminalWriteResult
where
    W: Write,
{
    let batch_cap: usize = max_batch_bytes.max(1);
    let mut batch_buf: Vec<u8> =
        Vec::with_capacity(batch_cap.min(TERMINAL_CLI_DEFAULT_BATCH_LIMIT));
    let mut total_written: u64 = 0;
    let mut total_bp: u64 = 0;
    let mut flush_count: u64 = 0;
    let start: Instant = Instant::now();
    for chunk in chunks.iter() {
        let bytes: &[u8] = chunk.as_bytes();
        if bytes.is_empty() {
            continue;
        }
        if !batch_buf.is_empty() && batch_buf.len().saturating_add(bytes.len()) > batch_cap {
            match write_all_with_backpressure(writer, batch_buf.as_slice()) {
                Ok((written, bp)) => {
                    total_written = total_written.saturating_add(written);
                    total_bp = total_bp.saturating_add(bp);
                    flush_count = flush_count.saturating_add(1);
                }
                Err((err, written, bp)) => {
                    let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
                    total_written = total_written.saturating_add(written);
                    total_bp = total_bp.saturating_add(bp).saturating_add(1);
                    let status: CliWriteStatus = classify_io_error(&err);
                    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
                        mode: TerminalRenderMode::StaticPlainText,
                        gpu_routing_opted_out: true,
                        uses_screen_hz: false,
                        input_to_output_ms: None,
                        flush_latency_ms: elapsed_ms,
                        bytes_written: total_written,
                        total_bytes_written: total_written,
                        changed_cells: 0,
                        unchanged_frame_skipped: false,
                        backpressure_events: total_bp,
                        batched_flush_count: flush_count,
                    };
                    return TerminalWriteResult {
                        status,
                        stats: TerminalDiffStats::new(0, 0, total_written as usize, false, false),
                        swapped: false,
                        error_message: Some(err.to_string()),
                        telemetry,
                    };
                }
            }
            batch_buf.clear();
        }
        if bytes.len() > batch_cap {
            for slice in bytes.chunks(batch_cap) {
                match write_all_with_backpressure(writer, slice) {
                    Ok((written, bp)) => {
                        total_written = total_written.saturating_add(written);
                        total_bp = total_bp.saturating_add(bp);
                        flush_count = flush_count.saturating_add(1);
                    }
                    Err((err, written, bp)) => {
                        let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
                        total_written = total_written.saturating_add(written);
                        total_bp = total_bp.saturating_add(bp).saturating_add(1);
                        let status: CliWriteStatus = classify_io_error(&err);
                        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
                            mode: TerminalRenderMode::StaticPlainText,
                            gpu_routing_opted_out: true,
                            uses_screen_hz: false,
                            input_to_output_ms: None,
                            flush_latency_ms: elapsed_ms,
                            bytes_written: total_written,
                            total_bytes_written: total_written,
                            changed_cells: 0,
                            unchanged_frame_skipped: false,
                            backpressure_events: total_bp,
                            batched_flush_count: flush_count,
                        };
                        return TerminalWriteResult {
                            status,
                            stats: TerminalDiffStats::new(
                                0,
                                0,
                                total_written as usize,
                                false,
                                false,
                            ),
                            swapped: false,
                            error_message: Some(err.to_string()),
                            telemetry,
                        };
                    }
                }
            }
        } else {
            batch_buf.extend_from_slice(bytes);
        }
    }
    if !batch_buf.is_empty() {
        match write_all_with_backpressure(writer, batch_buf.as_slice()) {
            Ok((written, bp)) => {
                total_written = total_written.saturating_add(written);
                total_bp = total_bp.saturating_add(bp);
                flush_count = flush_count.saturating_add(1);
            }
            Err((err, written, bp)) => {
                let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
                total_written = total_written.saturating_add(written);
                total_bp = total_bp.saturating_add(bp).saturating_add(1);
                let status: CliWriteStatus = classify_io_error(&err);
                let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
                    mode: TerminalRenderMode::StaticPlainText,
                    gpu_routing_opted_out: true,
                    uses_screen_hz: false,
                    input_to_output_ms: None,
                    flush_latency_ms: elapsed_ms,
                    bytes_written: total_written,
                    total_bytes_written: total_written,
                    changed_cells: 0,
                    unchanged_frame_skipped: false,
                    backpressure_events: total_bp,
                    batched_flush_count: flush_count,
                };
                return TerminalWriteResult {
                    status,
                    stats: TerminalDiffStats::new(0, 0, total_written as usize, false, false),
                    swapped: false,
                    error_message: Some(err.to_string()),
                    telemetry,
                };
            }
        }
    }
    let elapsed_ms: f64 = start.elapsed().as_secs_f64() * 1000.0;
    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
        mode: TerminalRenderMode::StaticPlainText,
        gpu_routing_opted_out: true,
        uses_screen_hz: false,
        input_to_output_ms: None,
        flush_latency_ms: elapsed_ms,
        bytes_written: total_written,
        total_bytes_written: total_written,
        changed_cells: 0,
        unchanged_frame_skipped: total_written == 0,
        backpressure_events: total_bp,
        batched_flush_count: flush_count,
    };
    TerminalWriteResult {
        status: CliWriteStatus::Written,
        stats: TerminalDiffStats::new(0, 0, total_written as usize, total_written == 0, false),
        swapped: false,
        error_message: None,
        telemetry,
    }
}