eger 1.2.0

A high-level, parallel ASCII-art media pipeline built on top of iascii: images, video, GIFs, dithering, animated text/banners, and procedural illusions, all rendered to ANSI.
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
//! Fast, byte-identical ANSI emission for `Grid` rendering.
//!
//! [`iascii::render::render_ansi`] is correct but slow for large grids
//! (e.g. every frame of a high-resolution video): it formats each color
//! change with `write!` (fmt machinery), finds the nearest palette entry
//! with iterator-based searches, and does float math per cell for
//! `Ansi256`. This module reimplements the exact same mapping with:
//!
//! - plain integer loops (unrolled where it matters) instead of
//!   iterator/`min_by_key` searches,
//! - branch-threshold channel quantization instead of per-level scans and
//!   float `round()` for `Ansi256`,
//! - direct byte pushes with manual `u8` decimal conversion instead of
//!   `format!`/`write!`,
//! - a single `Vec<u8>` output buffer with an ASCII fast path for glyphs.
//!
//! Output is byte-for-byte identical to `iascii::render::render_ansi`
//! (same escapes, same row resets), so this is a pure performance swap.
//!
//! The module also owns *cell-space* frame diffing ([`diff_cells_into`]):
//! damage regions are located on parsed (glyph, color) cells and re-emitted
//! with fresh, well-formed escapes. Diffing rendered bytes instead can cut
//! an SGR sequence in half when only a color changed — the classic
//! partial-update corruption bug.

use crate::rgb::Rgb;
use iascii::grid::Grid;
use iascii::render::ColorDepth;

/// Standard 16-color ANSI palette, same order as SGR 30-37 / 90-97.
pub(crate) static ANSI16_PALETTE: [(u8, u8, u8); 16] = [
    (0, 0, 0),
    (128, 0, 0),
    (0, 128, 0),
    (128, 128, 0),
    (0, 0, 128),
    (128, 0, 128),
    (0, 128, 128),
    (192, 192, 192),
    (128, 128, 128),
    (255, 0, 0),
    (0, 255, 0),
    (255, 255, 0),
    (0, 0, 255),
    (255, 0, 255),
    (0, 255, 255),
    (255, 255, 255),
];

/// Pre-rendered SGR sequences for the 16-color palette.
static ANSI16_ESCAPES: [&[u8]; 16] = [
    b"\x1b[30m",
    b"\x1b[31m",
    b"\x1b[32m",
    b"\x1b[33m",
    b"\x1b[34m",
    b"\x1b[35m",
    b"\x1b[36m",
    b"\x1b[37m",
    b"\x1b[90m",
    b"\x1b[91m",
    b"\x1b[92m",
    b"\x1b[93m",
    b"\x1b[94m",
    b"\x1b[95m",
    b"\x1b[96m",
    b"\x1b[97m",
];

const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];

/// Nearest of the 16 standard ANSI colors. Same result as an exhaustive
/// squared-Euclidean search; written as a plain loop so LLVM unrolls it
/// instead of paying iterator/`min_by_key` overhead per cell.
#[inline]
pub(crate) fn nearest_ansi16(r: u8, g: u8, b: u8) -> u8 {
    let r = r as i32;
    let g = g as i32;
    let b = b as i32;
    let mut best_idx: u8 = 0;
    let mut best_dist = u32::MAX;
    let mut i: usize = 0;
    while i < 16 {
        let (pr, pg, pb) = ANSI16_PALETTE[i];
        let dr = r - pr as i32;
        let dg = g - pg as i32;
        let db = b - pb as i32;
        let d = (dr * dr + dg * dg + db * db) as u32;
        if d < best_dist {
            best_dist = d;
            best_idx = i as u8;
            if d == 0 {
                break;
            }
        }
        i += 1;
    }
    best_idx
}

/// Maps one channel to its nearest xterm cube level index.
///
/// `CUBE_LEVELS = [0, 95, 135, 175, 215, 255]`; midpoints between adjacent
/// levels are 47.5, 115, 155, 195, 235. Ties keep the lower index (matching
/// the original `<`-only linear scan), so `v <= 47 -> 0`, `<= 115 -> 1`,
/// etc. Exact, no loop.
#[inline]
fn cube_level_index(v: u8) -> usize {
    if v <= 47 {
        0
    } else if v <= 115 {
        1
    } else if v <= 155 {
        2
    } else if v <= 195 {
        3
    } else if v <= 235 {
        4
    } else {
        5
    }
}

#[inline]
fn dist2(ar: i32, ag: i32, ab: i32, br: i32, bg: i32, bb: i32) -> u32 {
    let dr = ar - br;
    let dg = ag - bg;
    let db = ab - bb;
    (dr * dr + dg * dg + db * db) as u32
}

/// Nearest xterm 256-color index, matching `iascii`'s search over the
/// 6x6x6 cube (16..=231) plus grayscale ramp (232..=255). Integer-only and
/// branch-threshold based; bit-identical to the float/loop version.
#[inline]
pub(crate) fn nearest_ansi256(r: u8, g: u8, b: u8) -> u8 {
    let ri = cube_level_index(r);
    let gi = cube_level_index(g);
    let bi = cube_level_index(b);
    let rv = CUBE_LEVELS[ri] as i32;
    let gv = CUBE_LEVELS[gi] as i32;
    let bv = CUBE_LEVELS[bi] as i32;
    let cube_dist = dist2(r as i32, g as i32, b as i32, rv, gv, bv);

    let avg = ((r as u32 + g as u32 + b as u32) / 3) as u8;
    // Integer form of `((avg - 8) as f32 / 10.0).round()`: exact for all
    // 0..=255 inputs (verified by `gray_index_matches_float_round`).
    let gray_idx: u8 = if avg < 8 {
        0
    } else if avg > 238 {
        23
    } else {
        (avg - 8 + 5) / 10
    };
    let gray_val = (8 + gray_idx * 10) as i32;
    let gray_dist = dist2(r as i32, g as i32, b as i32, gray_val, gray_val, gray_val);

    // Strict `<`: ties keep the cube color, matching the original.
    if gray_dist < cube_dist {
        232 + gray_idx
    } else {
        16 + (36 * ri + 6 * gi + bi) as u8
    }
}

/// Appends the decimal form of `v` (no padding) to `buf`.
#[inline]
pub(crate) fn push_u8(buf: &mut Vec<u8>, v: u8) {
    if v >= 100 {
        buf.push(b'0' + v / 100);
        let rem = v % 100;
        buf.push(b'0' + rem / 10);
        buf.push(b'0' + rem % 10);
    } else if v >= 10 {
        buf.push(b'0' + v / 10);
        buf.push(b'0' + v % 10);
    } else {
        buf.push(b'0' + v);
    }
}

#[inline]
pub(crate) fn push_ansi16_escape(buf: &mut Vec<u8>, idx: u8) {
    buf.extend_from_slice(ANSI16_ESCAPES[(idx & 15) as usize]);
}

#[inline]
pub(crate) fn push_ansi256_escape(buf: &mut Vec<u8>, code: u8) {
    buf.extend_from_slice(b"\x1b[38;5;");
    push_u8(buf, code);
    buf.push(b'm');
}

#[inline]
pub(crate) fn push_truecolor_escape(buf: &mut Vec<u8>, r: u8, g: u8, b: u8) {
    buf.extend_from_slice(b"\x1b[38;2;");
    push_u8(buf, r);
    buf.push(b';');
    push_u8(buf, g);
    buf.push(b';');
    push_u8(buf, b);
    buf.push(b'm');
}

/// Pushes one glyph cell with an ASCII fast path (all built-in ramps are
/// ASCII; only exotic script ramps take the slow path).
#[inline]
pub(crate) fn push_char(buf: &mut Vec<u8>, ch: char) {
    if (ch as u32) < 128 {
        buf.push(ch as u8);
    } else {
        let mut tmp = [0u8; 4];
        buf.extend_from_slice(ch.encode_utf8(&mut tmp).as_bytes());
    }
}

// ---------------------------------------------------------------------------
// SGR parsing and cell-space frame diffing
// ---------------------------------------------------------------------------

/// One parsed display cell: a glyph plus an optional foreground color.
pub(crate) type ParsedCell = (char, Option<Rgb>);

/// How many *unchanged* cells may sit between two changed cells before the
/// span is ended and a second cursor-position escape is emitted instead.
/// Rewriting a bridged cell costs its glyph bytes (~1 for ASCII); ending
/// the span costs `\x1b[<row>;<col>H` (~10 bytes) plus a color escape if
/// the next span's first cell is colored (~19 bytes) — so merging gaps up
/// to this size is always a win, and small-gap merging is what collapses
/// contiguous motion (a sprite crossing a static row) into one cursor move
/// per row.
pub(crate) const SPAN_MERGE_GAP: usize = 4;

/// Applies one SGR parameter string (the text between `\x1b[` and `m`) to
/// the current foreground color: `38;2;r;g;b` sets TrueColor, `38;5;n` and
/// `30-37`/`90-97` set palette colors, `0`/`39` clear it, anything else is
/// ignored. Allocation-free (fixed-capacity parse).
pub(crate) fn apply_sgr(params: &str, cur: &mut Option<Rgb>) {
    let mut nums = [0u8; 5];
    let mut n = 0usize;
    let mut overflow = false;
    for p in params.split(';') {
        if let Ok(v) = p.parse::<u8>() {
            if n < nums.len() {
                nums[n] = v;
                n += 1;
            } else {
                overflow = true;
            }
        }
    }
    if overflow {
        return; // more params than we model: not one of the patterns above
    }
    match &nums[..n] {
        [] | [0] | [39] => *cur = None,
        [38, 2, r, g, b] => *cur = Some(Rgb::new(*r, *g, *b)),
        [38, 5, idx] => {
            let (r, g, b) = crate::palette::ansi256_rgb(*idx);
            *cur = Some(Rgb::new(r, g, b));
        }
        [code] if (30..=37).contains(code) => {
            let (r, g, b) = ANSI16_PALETTE[(code - 30) as usize];
            *cur = Some(Rgb::new(r, g, b));
        }
        [code] if (90..=97).contains(code) => {
            let (r, g, b) = ANSI16_PALETTE[(code - 90 + 8) as usize];
            *cur = Some(Rgb::new(r, g, b));
        }
        _ => {}
    }
}

/// Parses one rendered ANSI line into display cells, appended to `out`
/// (cleared first): SGR color escapes update the current color, every
/// other character is a glyph. A `\x1b[` sequence without an `m` terminator
/// stops the line — frames this crate renders contain SGR only; use
/// [`crate::render::DiffGranularity::Line`] for foreign sequences.
pub(crate) fn parse_sgr_cells(line: &str, out: &mut Vec<ParsedCell>) {
    out.clear();
    let mut cur: Option<Rgb> = None;
    let mut rest = line;
    while !rest.is_empty() {
        if let Some(after_esc) = rest.strip_prefix("\x1b[") {
            match after_esc.find('m') {
                Some(end) => {
                    apply_sgr(&after_esc[..end], &mut cur);
                    rest = &after_esc[end + 1..];
                }
                None => break, // unterminated / non-SGR escape: stop here
            }
            continue;
        }
        let mut chars = rest.chars();
        let ch = chars.next().unwrap_or(' ');
        out.push((ch, cur));
        rest = chars.as_str();
    }
}

/// Appends `cells` as run-merged SGR text: one escape per color run and a
/// reset when a run ends. The cursor's active SGR state on entry is
/// unknown, so an *uncolored* first cell is preceded by a reset — every
/// emitted span therefore starts from a known state.
fn push_cells_run(out: &mut String, cells: &[ParsedCell]) {
    use std::fmt::Write as _;
    let mut run: Option<Rgb> = None;
    let mut first = true;
    for (ch, color) in cells {
        match color {
            None => {
                if run.take().is_some() || first {
                    out.push_str("\x1b[0m");
                }
                out.push(*ch);
            }
            Some(c) => {
                if run != Some(*c) {
                    if run.is_some() {
                        out.push_str("\x1b[0m");
                    }
                    let _ = write!(out, "\x1b[38;2;{};{};{}m", c.0, c.1, c.2);
                    run = Some(*c);
                }
                out.push(*ch);
            }
        }
        first = false;
    }
    if run.is_some() {
        out.push_str("\x1b[0m");
    }
}

/// Appends the minimal cursor-addressed patches that turn the `prev` row
/// into the `next` row on terminal row `row1` (1-based): each changed span
/// (with small-gap merging, see [`SPAN_MERGE_GAP`]) re-emitted with fresh,
/// well-formed escapes, plus one clear-to-EOL when a shrunken `next` left a
/// stale tail. Appends nothing when the rows are equal.
pub(crate) fn diff_cells_into(
    out: &mut String,
    row1: usize,
    prev: &[ParsedCell],
    next: &[ParsedCell],
) {
    use std::fmt::Write as _;
    let max_len = prev.len().max(next.len());
    let mut col = 0usize;
    while col < max_len {
        if prev.get(col) == next.get(col) {
            col += 1;
            continue;
        }
        // Start of a changed span; keep it open across small equal gaps.
        // Only gaps *between* differences are bridged — the span always
        // ends at the last differing cell, so unchanged tails are never
        // re-sent (and merge gaps can't creep to the row end).
        let start = col;
        let mut last_diff = col;
        let mut gap = 0usize;
        col += 1;
        while col < max_len {
            if prev.get(col) != next.get(col) {
                last_diff = col;
                gap = 0;
            } else {
                gap += 1;
                if gap > SPAN_MERGE_GAP {
                    break;
                }
            }
            col += 1;
        }
        let end = last_diff + 1; // exclusive
                                 // Only cells that exist in `next` can be written; a vanished tail
                                 // is wiped by the clear-to-EOL below instead of space-padded.
        let emit_end = end.min(next.len());
        if start < emit_end {
            let _ = write!(out, "\x1b[{row1};{}H", start + 1);
            push_cells_run(out, &next[start..emit_end]);
        }
        if end > next.len() {
            // `next` ran out inside this span: clear the stale remainder.
            let _ = write!(out, "\x1b[{row1};{}H\x1b[K", next.len() + 1);
        }
    }
}

/// Builds a posterize lookup table for `levels` steps using the exact same
/// formula as before (`round(v/step)*step`), computed once per render
/// instead of with float math per cell.
pub(crate) fn posterize_lut(levels: u8) -> [u8; 256] {
    let levels = levels.max(2) as f32;
    let step = 255.0 / (levels - 1.0);
    let mut lut = [0u8; 256];
    for (v, slot) in lut.iter_mut().enumerate() {
        *slot = ((v as f32 / step).round() * step).clamp(0.0, 255.0) as u8;
    }
    lut
}

fn bytes_to_string(buf: Vec<u8>) -> String {
    // Safe: we only ever push ASCII escape bytes and valid UTF-8 glyphs.
    unsafe { String::from_utf8_unchecked(buf) }
}

/// Fast, byte-identical replacement for `iascii::render::render_ansi`.
pub(crate) fn render_ansi_fast(grid: &Grid, depth: ColorDepth) -> String {
    let w = grid.width() as usize;
    let h = grid.height() as usize;
    if w == 0 || h == 0 {
        return String::new();
    }
    let cells = grid.as_slice();
    debug_assert_eq!(cells.len(), w * h);

    let per_cell = match depth {
        ColorDepth::TrueColor => 20,
        ColorDepth::Ansi256 => 13,
        ColorDepth::Ansi16 => 7,
    };
    let mut buf = Vec::with_capacity(h * (w * per_cell + 5));

    match depth {
        ColorDepth::TrueColor => {
            let mut cur = u32::MAX;
            for row in cells.chunks_exact(w) {
                for cell in row {
                    let key = (cell.color.r as u32) << 16
                        | (cell.color.g as u32) << 8
                        | cell.color.b as u32;
                    if key != cur {
                        push_truecolor_escape(&mut buf, cell.color.r, cell.color.g, cell.color.b);
                        cur = key;
                    }
                    push_char(&mut buf, cell.ch);
                }
                buf.extend_from_slice(b"\x1b[0m\n");
                cur = u32::MAX;
            }
        }
        ColorDepth::Ansi256 => {
            let mut cur: u32 = u32::MAX;
            for row in cells.chunks_exact(w) {
                for cell in row {
                    let code = nearest_ansi256(cell.color.r, cell.color.g, cell.color.b) as u32;
                    if code != cur {
                        push_ansi256_escape(&mut buf, code as u8);
                        cur = code;
                    }
                    push_char(&mut buf, cell.ch);
                }
                buf.extend_from_slice(b"\x1b[0m\n");
                cur = u32::MAX;
            }
        }
        ColorDepth::Ansi16 => {
            let mut cur: u32 = u32::MAX;
            for row in cells.chunks_exact(w) {
                for cell in row {
                    let code = nearest_ansi16(cell.color.r, cell.color.g, cell.color.b) as u32;
                    if code != cur {
                        push_ansi16_escape(&mut buf, code as u8);
                        cur = code;
                    }
                    push_char(&mut buf, cell.ch);
                }
                buf.extend_from_slice(b"\x1b[0m\n");
                cur = u32::MAX;
            }
        }
    }

    bytes_to_string(buf)
}

/// Row-direct variant of [`render_ansi_fast`]: one `String` per grid row
/// (each keeping its trailing `\x1b[0m`), without joining and re-splitting
/// a single blob.
pub(crate) fn render_ansi_fast_lines(grid: &Grid, depth: ColorDepth) -> Vec<String> {
    let w = grid.width() as usize;
    let h = grid.height() as usize;
    if w == 0 || h == 0 {
        return Vec::new();
    }
    let cells = grid.as_slice();
    let per_cell = match depth {
        ColorDepth::TrueColor => 20,
        ColorDepth::Ansi256 => 13,
        ColorDepth::Ansi16 => 7,
    };
    let mut lines = Vec::with_capacity(h);
    for row in cells.chunks_exact(w) {
        let mut buf = Vec::with_capacity(w * per_cell + 4);
        match depth {
            ColorDepth::TrueColor => {
                let mut cur = u32::MAX;
                for cell in row {
                    let key = (cell.color.r as u32) << 16
                        | (cell.color.g as u32) << 8
                        | cell.color.b as u32;
                    if key != cur {
                        push_truecolor_escape(&mut buf, cell.color.r, cell.color.g, cell.color.b);
                        cur = key;
                    }
                    push_char(&mut buf, cell.ch);
                }
            }
            ColorDepth::Ansi256 => {
                let mut cur: u32 = u32::MAX;
                for cell in row {
                    let code = nearest_ansi256(cell.color.r, cell.color.g, cell.color.b) as u32;
                    if code != cur {
                        push_ansi256_escape(&mut buf, code as u8);
                        cur = code;
                    }
                    push_char(&mut buf, cell.ch);
                }
            }
            ColorDepth::Ansi16 => {
                let mut cur: u32 = u32::MAX;
                for cell in row {
                    let code = nearest_ansi16(cell.color.r, cell.color.g, cell.color.b) as u32;
                    if code != cur {
                        push_ansi16_escape(&mut buf, code as u8);
                        cur = code;
                    }
                    push_char(&mut buf, cell.ch);
                }
            }
        }
        buf.extend_from_slice(b"\x1b[0m");
        lines.push(bytes_to_string(buf));
    }
    lines
}

#[cfg(test)]
mod tests {
    use super::*;
    use iascii::config::{ConfigBuilder as AsciiConfigBuilder, OutputSizing};
    use iascii::convert::convert_image;

    fn gradient_grid(w: u32, h: u32) -> Grid {
        let cfg = AsciiConfigBuilder::new()
            .output_sizing(OutputSizing::Explicit {
                width: w as usize,
                height: h as usize,
            })
            .build()
            .unwrap();
        let mut pix = Vec::with_capacity((w * h * 3) as usize);
        for y in 0..h {
            for x in 0..w {
                pix.push((x * 255 / w.max(1)) as u8);
                pix.push((y * 255 / h.max(1)) as u8);
                pix.push(((x + y) * 255 / (w + h).max(1)) as u8);
            }
        }
        convert_image(w, h, &pix, &cfg).unwrap()
    }

    #[test]
    fn matches_iascii_render_on_all_depths() {
        for (w, h) in [(1, 1), (2, 2), (7, 5), (64, 32)] {
            let grid = gradient_grid(w, h);
            for depth in [
                ColorDepth::TrueColor,
                ColorDepth::Ansi256,
                ColorDepth::Ansi16,
            ] {
                assert_eq!(
                    render_ansi_fast(&grid, depth),
                    iascii::render::render_ansi(&grid, depth),
                    "mismatch at {w}x{h} {depth:?}"
                );
            }
        }
    }

    #[test]
    fn lines_variant_matches_split_render() {
        let grid = gradient_grid(9, 6);
        for depth in [
            ColorDepth::TrueColor,
            ColorDepth::Ansi256,
            ColorDepth::Ansi16,
        ] {
            let joined = render_ansi_fast(&grid, depth);
            let expected: Vec<String> = joined.lines().map(str::to_owned).collect();
            assert_eq!(render_ansi_fast_lines(&grid, depth), expected);
        }
    }

    #[test]
    fn ansi256_matches_reference_on_all_inputs() {
        // Exhaustive over a strided sample plus all gray values and cube
        // corners: compares against the original loop+float algorithm.
        let mut checked = 0u32;
        for r in (0..=255u16).step_by(7) {
            for g in (0..=255u16).step_by(13) {
                let b = ((r * 31 + g * 17) % 256) as u8;
                assert_eq!(
                    nearest_ansi256(r as u8, g as u8, b),
                    reference_ansi256(r as u8, g as u8, b),
                    "mismatch at ({r},{g},{b})"
                );
                checked += 1;
            }
        }
        for v in 0..=255u8 {
            assert_eq!(nearest_ansi256(v, v, v), reference_ansi256(v, v, v));
        }
        assert!(checked > 500);
    }

    fn reference_ansi256(r: u8, g: u8, b: u8) -> u8 {
        let closest = |v: u8| -> (usize, u8) {
            let mut best_d = u32::MAX;
            let mut best = (0, CUBE_LEVELS[0]);
            for (i, &l) in CUBE_LEVELS.iter().enumerate() {
                let d = (v as i32 - l as i32).unsigned_abs();
                if d < best_d {
                    best_d = d;
                    best = (i, l);
                }
            }
            best
        };
        let (ri, rv) = closest(r);
        let (gi, gv) = closest(g);
        let (bi, bv) = closest(b);
        let cube_dist = {
            let dr = r as i32 - rv as i32;
            let dg = g as i32 - gv as i32;
            let db = b as i32 - bv as i32;
            (dr * dr + dg * dg + db * db) as u32
        };
        let gray_avg = ((r as u32 + g as u32 + b as u32) / 3) as u8;
        let gray_idx = if gray_avg < 8 {
            0
        } else if gray_avg > 238 {
            23
        } else {
            ((gray_avg - 8) as f32 / 10.0).round() as u8
        };
        let gray_val = 8 + gray_idx * 10;
        let gray_dist = {
            let dr = r as i32 - gray_val as i32;
            let dg = g as i32 - gray_val as i32;
            let db = b as i32 - gray_val as i32;
            (dr * dr + dg * dg + db * db) as u32
        };
        if gray_dist < cube_dist {
            232 + gray_idx
        } else {
            16 + (36 * ri + 6 * gi + bi) as u8
        }
    }

    #[test]
    fn ansi16_matches_reference_on_sampled_inputs() {
        for r in (0..=255u16).step_by(17) {
            for g in (0..=255u16).step_by(19) {
                let b = ((r + g * 3) % 256) as u8;
                let (rr, gg, bb) = (r as u8, g as u8, b);
                let mut best_d = u32::MAX;
                let mut best_i = 0u8;
                for (i, &(pr, pg, pb)) in ANSI16_PALETTE.iter().enumerate() {
                    let dr = rr as i32 - pr as i32;
                    let dg = gg as i32 - pg as i32;
                    let db = bb as i32 - pb as i32;
                    let d = (dr * dr + dg * dg + db * db) as u32;
                    if d < best_d {
                        best_d = d;
                        best_i = i as u8;
                    }
                }
                assert_eq!(nearest_ansi16(rr, gg, bb), best_i);
            }
        }
    }

    #[test]
    fn posterize_lut_matches_float_formula() {
        for levels in [2u8, 3, 6, 16] {
            let lut = posterize_lut(levels);
            let l = levels.max(2) as f32;
            let step = 255.0 / (l - 1.0);
            for v in 0..=255u8 {
                let expected = ((v as f32 / step).round() * step).clamp(0.0, 255.0) as u8;
                assert_eq!(lut[v as usize], expected, "levels={levels} v={v}");
            }
        }
    }

    // -----------------------------------------------------------------------
    // SGR parsing / cell-space diffing
    // -----------------------------------------------------------------------

    fn parse(line: &str) -> Vec<ParsedCell> {
        let mut out = Vec::new();
        parse_sgr_cells(line, &mut out);
        out
    }

    #[test]
    fn parse_sgr_cells_reads_truecolor_256_and_16_color_escapes() {
        let cells = parse("\x1b[38;2;10;20;30mAB\x1b[0mC\x1b[38;5;196mD");
        assert_eq!(
            cells,
            vec![
                ('A', Some(Rgb::new(10, 20, 30))),
                ('B', Some(Rgb::new(10, 20, 30))),
                ('C', None),
                ('D', Some(Rgb::new(255, 0, 0))), // 256-color 196 = pure red
            ]
        );
        let cells = parse("\x1b[91mX\x1b[37mY");
        assert_eq!(cells[0].1, Some(Rgb::new(255, 0, 0)));
        assert_eq!(cells[1].1, Some(Rgb::new(192, 192, 192)));
        // Plain text parses to uncolored cells.
        assert_eq!(parse("ab"), vec![('a', None), ('b', None)]);
    }

    #[test]
    fn diff_cells_into_is_empty_for_equal_rows() {
        let row = parse("\x1b[38;2;1;2;3mab\x1b[0m");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &row, &row);
        assert_eq!(out, "");
    }

    #[test]
    fn diff_cells_into_patches_only_the_changed_span() {
        let prev = parse("abcXXXghi");
        let next = parse("abcYYYghi");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &prev, &next);
        assert!(out.contains("YYY"));
        assert!(!out.contains("abc"), "unchanged prefix must not be re-sent");
        assert!(!out.contains("ghi"), "unchanged suffix must not be re-sent");
        assert!(
            out.starts_with("\x1b[1;4H"),
            "cursor lands on the span start"
        );
    }

    #[test]
    fn diff_cells_into_never_splits_an_escape_sequence() {
        // Only the *color* changes; the raw bytes of the escape differ
        // starting mid-sequence. Byte diffing would emit "8;2;0;255;0m"
        // as visible garbage; cell diffing re-emits a whole escape.
        let prev = parse("\x1b[38;2;255;0;0mAB");
        let next = parse("\x1b[38;2;0;255;0mAB");
        let mut out = String::new();
        diff_cells_into(&mut out, 2, &prev, &next);
        assert!(out.contains("\x1b[38;2;0;255;0mAB"), "got {out:?}");
        // Every emitted escape is complete: no fragment like "8;2;" loose.
        let stripped = out.replace("\x1b[38;2;0;255;0m", "");
        assert!(!stripped.contains('8'), "escape fragment leaked: {out:?}");
    }

    #[test]
    fn diff_cells_into_merges_small_gaps_into_one_cursor_move() {
        // Changes at columns 1 and 3 with one unchanged cell between them
        // (gap of 1 <= SPAN_MERGE_GAP): bridged into a single span.
        let prev = parse("aXcdefgh");
        let next = parse("aYcZefgh");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &prev, &next);
        assert_eq!(
            out.matches("\x1b[1;").count(),
            1,
            "one cursor move: {out:?}"
        );
        assert!(
            out.contains("YcZ"),
            "gap cell re-sent inside the span: {out:?}"
        );
    }

    #[test]
    fn diff_cells_into_separate_wide_gaps_get_separate_moves() {
        let prev = parse("aXcdefghijklmnop"); // change at col 1 and col 12
        let next = parse("aYcdefghijkZmnop");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &prev, &next);
        assert_eq!(
            out.matches("\x1b[1;").count(),
            2,
            "gap wider than SPAN_MERGE_GAP: two moves: {out:?}"
        );
    }

    #[test]
    fn diff_cells_into_clears_a_shrunk_row_tail_once() {
        let prev = parse("hello world");
        let next = parse("hello");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &prev, &next);
        assert_eq!(out, "\x1b[1;6H\x1b[K", "clear right after the new content");
    }

    #[test]
    fn diff_cells_into_resets_before_uncolored_span_starts() {
        // The cursor may be left colored by an earlier write, so an
        // uncolored span must lead with a reset to be safe.
        let prev = parse("a b");
        let next = parse("aXb");
        let mut out = String::new();
        diff_cells_into(&mut out, 1, &prev, &next);
        assert!(out.contains("\x1b[0mX"), "reset before bare glyph: {out:?}");
    }

    #[test]
    fn diff_cells_into_handles_row_appearing_and_vanishing() {
        let mut out = String::new();
        diff_cells_into(&mut out, 3, &[], &parse("ab"));
        assert_eq!(out, "\x1b[3;1H\x1b[0mab");
        let mut out = String::new();
        diff_cells_into(&mut out, 3, &parse("ab"), &[]);
        assert_eq!(out, "\x1b[3;1H\x1b[K");
    }

    #[test]
    fn apply_sgr_ignores_malformed_and_overflowing_params() {
        let mut cur = Some(Rgb::new(1, 1, 1));
        apply_sgr("38;2;999;0;0", &mut cur); // >255: dropped, no pattern left
        assert_eq!(cur, Some(Rgb::new(1, 1, 1)), "malformed leaves color alone");
        apply_sgr("1;2;3;4;5;6", &mut cur); // overflow: ignored entirely
        assert_eq!(cur, Some(Rgb::new(1, 1, 1)));
        apply_sgr("0", &mut cur);
        assert_eq!(cur, None);
    }
}