inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
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
//! Port of [`cli-truncate@6`](https://github.com/sindresorhus/cli-truncate) to Rust.
//!
//! Truncates a string to a given number of terminal columns, inserting a
//! truncation character (default `…`) and preserving ANSI styling around the
//! cut via [`slice_ansi`](crate::text::slice_ansi). Width is measured with
//! [`string_width`].
//!
//! # Known divergences from JS
//!
//! - **Index model (astral + prefer-on-space).** `getIndexOfNearestSpace` and
//!   the leading/trailing SGR span scanners index the raw string by *char*
//!   (Unicode scalar) rather than JS's UTF-16 code units; this is exact for all
//!   BMP input but diverges when non-BMP (astral) text reaches a
//!   `prefer_truncation_on_space` path, because the width-derived index resolves
//!   to different positions in the two models. Evidence: for `"🦄🦄 🦄🦄"` with
//!   `columns=5`, `wantedIndex = columns-1 = 4`; JS UTF-16 index 4 is the space
//!   (each emoji occupies two code units: indices 0-1, 2-3; space at 4), so JS
//!   takes `sliceAnsi(s, 0, 4)` = `"🦄🦄"` → `"🦄🦄…"`; Rust scalar index 4 is
//!   the fifth scalar (second trailing unicorn, not the space), so
//!   `getIndexOfNearestSpace` searches left and finds the space at scalar index 2,
//!   yielding `slice_ansi(s, 0, 2)` = `"🦄"` → `"🦄…"` (pinned by
//!   `prefer_space_end_astral_divergence` test). The divergence affects all
//!   three positions (`Start`, `Middle`, `End`) — any prefer-on-space path
//!   that walks astral text, not just `End` (confirmed by the M0 oracle run).
//! - **Colon-delimited SGR width** and **generic OSC control-string width**
//!   previously diverged from Node due to the pre-re-port `ANSI_RE` missing
//!   colon-parameter coverage and generic OSC strings; both were resolved by
//!   the string-width@8.2.1 re-port (ccfcfb3 + 2c97272), which re-derived
//!   `ANSI_RE` from ansi-regex@6.2.2. Both probes now match Node exactly.
//! - **Type checks.** JS throws `TypeError` for non-string / non-number inputs;
//!   Rust's type system makes those unrepresentable, so there is no error path.
//! - **`.trim()`.** JS `String#trim` strips the Unicode White_Space set; this
//!   port uses [`str::trim`] (Unicode `White_Space`), which matches for all
//!   whitespace this is used with.

use crate::text::slice_ansi::slice_ansi;
use crate::text::string_width::string_width;

/// Where to remove characters when truncating.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TruncatePosition {
    /// Truncate at the start: `"…ld"`.
    Start,
    /// Truncate in the middle: `"he…ld"`.
    Middle,
    /// Truncate at the end (default): `"he…"`.
    End,
}

/// Options for [`cli_truncate_with`]. Defaults match cli-truncate@6.
#[derive(Debug, Clone)]
pub struct TruncateOptions {
    /// Where to truncate. Default [`TruncatePosition::End`].
    pub position: TruncatePosition,
    /// Add a space between the text and the truncation character. Default `false`.
    pub space: bool,
    /// Prefer truncating at a nearby space over a hard cut. Default `false`.
    pub prefer_truncation_on_space: bool,
    /// The truncation character. Default `"…"`.
    pub truncation_character: String,
}

impl Default for TruncateOptions {
    fn default() -> Self {
        Self {
            position: TruncatePosition::End,
            space: false,
            prefer_truncation_on_space: false,
            truncation_character: "\u{2026}".to_owned(),
        }
    }
}

/// `getIndexOfNearestSpace(string, wantedIndex, shouldSearchRight)`.
///
/// Indexes `string` by char (JS uses UTF-16 code units; identical for BMP).
/// `wanted_index` may be out of bounds — `char_at` returns `None`, matching JS
/// `charAt` returning `''` for out-of-range indexes (never equal to `' '`).
fn get_index_of_nearest_space(chars: &[char], wanted_index: isize, search_right: bool) -> isize {
    if char_at(chars, wanted_index) == Some(' ') {
        return wanted_index;
    }

    let direction: isize = if search_right { 1 } else { -1 };

    for index in 0..=3 {
        let final_index = wanted_index + index * direction;
        if char_at(chars, final_index) == Some(' ') {
            return final_index;
        }
    }

    wanted_index
}

/// `string.charAt(index)` as a `char`: `None` for out-of-range (JS `''`).
fn char_at(chars: &[char], index: isize) -> Option<char> {
    if index < 0 {
        return None;
    }
    chars.get(index as usize).copied()
}

const ANSI_ESC: u32 = 27;
const ANSI_LEFT_BRACKET: u32 = 91;
const ANSI_LETTER_M: u32 = 109;

/// `isSgrParameter(code)`: `0`–`9` or `;` (codes 48–57 or 59).
fn is_sgr_parameter(code: u32) -> bool {
    (48..=57).contains(&code) || code == 59
}

/// `leadingSgrSpanEndIndex(string)`: char index just past a run of leading SGR
/// sequences (`ESC [ params m`).
fn leading_sgr_span_end_index(chars: &[char]) -> usize {
    let cp = |i: usize| chars.get(i).map(|c| *c as u32);
    let len = chars.len();
    let mut index = 0;

    while index + 2 < len && cp(index) == Some(ANSI_ESC) && cp(index + 1) == Some(ANSI_LEFT_BRACKET)
    {
        let mut j = index + 2;
        while j < len && cp(j).is_some_and(is_sgr_parameter) {
            j += 1;
        }

        if j < len && cp(j) == Some(ANSI_LETTER_M) {
            index = j + 1;
            continue;
        }

        break;
    }

    index
}

/// `trailingSgrSpanStartIndex(string)`: char index where a run of trailing SGR
/// sequences begins.
fn trailing_sgr_span_start_index(chars: &[char]) -> usize {
    let cp = |i: usize| chars.get(i).map(|c| *c as u32);
    let mut start = chars.len();

    while start > 1 && cp(start - 1) == Some(ANSI_LETTER_M) {
        // j walks left over SGR parameter bytes; it may go below 0, so use isize.
        let mut j: isize = start as isize - 2;
        while j >= 0 && cp(j as usize).is_some_and(is_sgr_parameter) {
            j -= 1;
        }

        if j >= 1
            && cp((j - 1) as usize) == Some(ANSI_ESC)
            && cp(j as usize) == Some(ANSI_LEFT_BRACKET)
        {
            start = (j - 1) as usize;
            continue;
        }

        break;
    }

    start
}

/// `appendWithInheritedStyleFromEnd(visible, suffix)`: insert `suffix` before
/// any trailing SGR span so the inserted character inherits the visible style.
fn append_with_inherited_style_from_end(visible: &str, suffix: &str) -> String {
    let chars: Vec<char> = visible.chars().collect();
    let start = trailing_sgr_span_start_index(&chars);
    if start == chars.len() {
        return format!("{visible}{suffix}");
    }

    let before: String = chars[..start].iter().collect();
    let after: String = chars[start..].iter().collect();
    format!("{before}{suffix}{after}")
}

/// `prependWithInheritedStyleFromStart(prefix, visible)`: insert `prefix` after
/// any leading SGR span.
fn prepend_with_inherited_style_from_start(prefix: &str, visible: &str) -> String {
    let chars: Vec<char> = visible.chars().collect();
    let end = leading_sgr_span_end_index(&chars);
    if end == 0 {
        return format!("{prefix}{visible}");
    }

    let before: String = chars[..end].iter().collect();
    let after: String = chars[end..].iter().collect();
    format!("{before}{prefix}{after}")
}

/// Truncates `text` to `columns` columns using default [`TruncateOptions`].
///
/// # Examples
///
/// ```
/// use inkferro_core::text::cli_truncate::cli_truncate;
///
/// assert_eq!(cli_truncate("unicorn", 4), "uni\u{2026}");
/// assert_eq!(cli_truncate("hello", 10), "hello");
/// ```
pub fn cli_truncate(text: &str, columns: usize) -> String {
    cli_truncate_with(text, columns, &TruncateOptions::default())
}

/// Truncates `text` to `columns` columns using the given [`TruncateOptions`].
///
/// `opts` is taken by reference so callers can reuse a single options struct
/// across many calls without transferring ownership.
pub fn cli_truncate_with(text: &str, columns: usize, opts: &TruncateOptions) -> String {
    if columns < 1 {
        return String::new();
    }

    let length = string_width(text);

    if length <= columns {
        return text.to_owned();
    }

    if columns == 1 {
        return opts.truncation_character.clone();
    }

    // text indexed by char for getIndexOfNearestSpace (BMP-faithful to UTF-16).
    let text_chars: Vec<char> = text.chars().collect();

    match opts.position {
        TruncatePosition::Start => truncate_start(text, &text_chars, columns, length, opts),
        TruncatePosition::Middle => truncate_middle(text, &text_chars, columns, length, opts),
        TruncatePosition::End => truncate_end(text, &text_chars, columns, opts),
    }
}

/// `position === 'start'` branch.
fn truncate_start(
    text: &str,
    text_chars: &[char],
    columns: usize,
    length: usize,
    opts: &TruncateOptions,
) -> String {
    if opts.prefer_truncation_on_space {
        // getIndexOfNearestSpace(text, length - columns + 1, true)
        let wanted = length as isize - columns as isize + 1;
        let nearest_space = get_index_of_nearest_space(text_chars, wanted, true);
        let right = slice_ansi(text, clamp_index(nearest_space), Some(length))
            .trim()
            .to_owned();
        return prepend_with_inherited_style_from_start(&opts.truncation_character, &right);
    }

    let truncation_character = if opts.space {
        format!("{} ", opts.truncation_character)
    } else {
        opts.truncation_character.clone()
    };

    // length - columns + stringWidth(tc) — may go negative in JS (→ slice
    // start 0). Compute signed, clamp to 0.
    let start = length as isize - columns as isize + string_width(&truncation_character) as isize;
    let right = slice_ansi(text, clamp_index(start), Some(length));
    prepend_with_inherited_style_from_start(&truncation_character, &right)
}

/// `position === 'middle'` branch.
fn truncate_middle(
    text: &str,
    text_chars: &[char],
    columns: usize,
    length: usize,
    opts: &TruncateOptions,
) -> String {
    let truncation_character = if opts.space {
        format!(" {} ", opts.truncation_character)
    } else {
        opts.truncation_character.clone()
    };

    let half = columns / 2;

    if opts.prefer_truncation_on_space {
        let space_near_first = get_index_of_nearest_space(text_chars, half as isize, false);
        let wanted_second = length as isize - (columns as isize - half as isize) + 1;
        let space_near_second = get_index_of_nearest_space(text_chars, wanted_second, true);
        let left = slice_ansi(text, 0, Some(clamp_index(space_near_first)));
        let right = slice_ansi(text, clamp_index(space_near_second), Some(length))
            .trim()
            .to_owned();
        return format!("{left}{truncation_character}{right}");
    }

    let left = slice_ansi(text, 0, Some(half));
    // length - (columns - half) + stringWidth(tc) — may go negative in JS.
    let right_start = length as isize - (columns as isize - half as isize)
        + string_width(&truncation_character) as isize;
    let right = slice_ansi(text, clamp_index(right_start), Some(length));
    format!("{left}{truncation_character}{right}")
}

/// `position === 'end'` branch.
fn truncate_end(text: &str, text_chars: &[char], columns: usize, opts: &TruncateOptions) -> String {
    if opts.prefer_truncation_on_space {
        let nearest_space = get_index_of_nearest_space(text_chars, columns as isize - 1, false);
        let left = slice_ansi(text, 0, Some(clamp_index(nearest_space)));
        return append_with_inherited_style_from_end(&left, &opts.truncation_character);
    }

    let truncation_character = if opts.space {
        format!(" {}", opts.truncation_character)
    } else {
        opts.truncation_character.clone()
    };

    // columns - stringWidth(tc) — may go negative in JS, where sliceAnsi with a
    // negative end yields "". Compute signed, clamp to 0 (which yields "").
    let end = columns as isize - string_width(&truncation_character) as isize;
    let left = slice_ansi(text, 0, Some(clamp_index(end)));
    append_with_inherited_style_from_end(&left, &truncation_character)
}

/// Clamp a possibly-negative `getIndexOfNearestSpace` result to a `usize` slice
/// index. JS `sliceAnsi(text, negative, …)` treats `start < 0` like `0` (the
/// position loop never reaches a negative target), so clamping to 0 matches.
fn clamp_index(index: isize) -> usize {
    index.max(0) as usize
}

#[cfg(test)]
mod tests {
    //! Parity tests for [`cli_truncate`], pinned against cli-truncate@6 in Node.
    //! Each `// node:` comment cites the verified JS output for the assertion.

    use super::*;

    fn start() -> TruncateOptions {
        TruncateOptions {
            position: TruncatePosition::Start,
            ..Default::default()
        }
    }
    fn middle() -> TruncateOptions {
        TruncateOptions {
            position: TruncatePosition::Middle,
            ..Default::default()
        }
    }
    fn with_space(mut o: TruncateOptions) -> TruncateOptions {
        o.space = true;
        o
    }
    fn with_prefer(mut o: TruncateOptions) -> TruncateOptions {
        o.prefer_truncation_on_space = true;
        o
    }

    // ── 1. No truncation needed (length <= columns) ──────────────────────────
    // node: cliTruncate("the quick brown fox", 20) === "the quick brown fox"
    #[test]
    fn no_truncation() {
        assert_eq!(
            cli_truncate("the quick brown fox", 20),
            "the quick brown fox"
        );
    }

    // ── 2. columns < 1 → "" ──────────────────────────────────────────────────
    // node: cliTruncate("unicorn", 0) === ""
    #[test]
    fn columns_zero() {
        assert_eq!(cli_truncate("unicorn", 0), "");
    }

    // ── 3. columns == 1 → "…" ────────────────────────────────────────────────
    // node: cliTruncate("unicorn", 1) === "…"
    #[test]
    fn columns_one() {
        assert_eq!(cli_truncate("unicorn", 1), "\u{2026}");
    }

    // ── 4. End position basic + with space ───────────────────────────────────
    // node: cliTruncate("unicorn", 4) === "uni…"
    #[test]
    fn end_basic() {
        assert_eq!(cli_truncate("unicorn", 4), "uni\u{2026}");
    }

    // node: cliTruncate("unicorn", 5, {space: true}) === "uni …"
    #[test]
    fn end_with_space() {
        assert_eq!(
            cli_truncate_with("unicorn", 5, &with_space(TruncateOptions::default())),
            "uni \u{2026}"
        );
    }

    // ── 5. Start position basic + with space ─────────────────────────────────
    // node: cliTruncate("the quick brown fox", 10, {position: 'start'}) === "…brown fox"
    #[test]
    fn start_basic() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &start()),
            "\u{2026}brown fox"
        );
    }

    // node: cliTruncate("the quick brown fox", 10, {position:'start', space:true})
    //   === "… rown fox"
    #[test]
    fn start_with_space() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &with_space(start())),
            "\u{2026} rown fox"
        );
    }

    // ── 6. Middle position basic + with space ────────────────────────────────
    // node: cliTruncate("the quick brown fox", 10, {position:'middle'}) === "the q… fox"
    #[test]
    fn middle_basic() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &middle()),
            "the q\u{2026} fox"
        );
    }

    // node: cliTruncate("the quick brown fox", 10, {position:'middle', space:true})
    //   === "the q … ox"
    #[test]
    fn middle_with_space() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &with_space(middle())),
            "the q \u{2026} ox"
        );
    }

    // ── 7. preferTruncationOnSpace for each position ─────────────────────────
    // node: cliTruncate("the quick brown fox", 10, {position:'end', preferTruncationOnSpace:true})
    //   === "the quick…"
    #[test]
    fn prefer_space_end() {
        assert_eq!(
            cli_truncate_with(
                "the quick brown fox",
                10,
                &with_prefer(TruncateOptions::default())
            ),
            "the quick\u{2026}"
        );
    }

    // node: ...{position:'start', preferTruncationOnSpace:true} === "…brown fox"
    #[test]
    fn prefer_space_start() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &with_prefer(start())),
            "\u{2026}brown fox"
        );
    }

    // node: ...{position:'middle', preferTruncationOnSpace:true} === "the…fox"
    #[test]
    fn prefer_space_middle() {
        assert_eq!(
            cli_truncate_with("the quick brown fox", 10, &with_prefer(middle())),
            "the\u{2026}fox"
        );
    }

    // ── 8. ANSI-colored end-truncate: char BEFORE trailing SGR span ──────────
    // node: cliTruncate("\x1b[31municorn\x1b[39m", 4) === "\x1b[31muni…\x1b[39m"
    #[test]
    fn ansi_end_truncate() {
        assert_eq!(
            cli_truncate("\x1b[31municorn\x1b[39m", 4),
            "\x1b[31muni\u{2026}\x1b[39m"
        );
    }

    // ── 9. ANSI-colored start-truncate: char AFTER leading SGR span ──────────
    // node: cliTruncate("\x1b[31municorn\x1b[39m", 4, {position:'start'})
    //   === "\x1b[31m…orn\x1b[39m"
    #[test]
    fn ansi_start_truncate() {
        assert_eq!(
            cli_truncate_with("\x1b[31municorn\x1b[39m", 4, &start()),
            "\x1b[31m\u{2026}orn\x1b[39m"
        );
    }

    // ── 10. CJK truncation (width-2 accounting) ──────────────────────────────
    // node: cliTruncate("古池や蛙飛び込む水の音", 10) === "古池や蛙…"
    #[test]
    fn cjk_truncation() {
        assert_eq!(
            cli_truncate("古池や蛙飛び込む水の音", 10),
            "古池や蛙\u{2026}"
        );
    }

    // ── 11. Custom truncation_character ──────────────────────────────────────
    // node: cliTruncate("unicorn", 5, {truncationCharacter: '.'}) === "unic."
    #[test]
    fn custom_truncation_character() {
        let opts = TruncateOptions {
            truncation_character: ".".to_owned(),
            ..Default::default()
        };
        assert_eq!(cli_truncate_with("unicorn", 5, &opts), "unic.");
    }

    // ── 12. Emoji truncation ─────────────────────────────────────────────────
    // node: cliTruncate("😀😁😂😃😄", 4) === "😀…"  (each emoji is width 2)
    #[test]
    fn emoji_truncation() {
        assert_eq!(cli_truncate("😀😁😂😃😄", 4), "😀\u{2026}");
    }

    // ── Extra pinned cases ───────────────────────────────────────────────────
    // node: cliTruncate("hello world", 8) === "hello w…"
    #[test]
    fn end_plain() {
        assert_eq!(cli_truncate("hello world", 8), "hello w\u{2026}");
    }

    // node: cliTruncate("hello world", 8, {position:'start'}) === "…o world"
    #[test]
    fn start_plain() {
        assert_eq!(
            cli_truncate_with("hello world", 8, &start()),
            "\u{2026}o world"
        );
    }

    // node: cliTruncate("hello world", 8, {position:'middle'}) === "hell…rld"
    #[test]
    fn middle_plain() {
        assert_eq!(
            cli_truncate_with("hello world", 8, &middle()),
            "hell\u{2026}rld"
        );
    }

    // Default options match documented JS defaults.
    #[test]
    fn default_options() {
        let d = TruncateOptions::default();
        assert_eq!(d.position, TruncatePosition::End);
        assert!(!d.space);
        assert!(!d.prefer_truncation_on_space);
        assert_eq!(d.truncation_character, "\u{2026}");
    }

    // ── 13. Astral + preferTruncationOnSpace divergence (documented in module docs) ─
    // DIVERGENCE (documented in module docs): JS indexes by UTF-16 code unit.
    // node: cli-truncate@6 returns "🦄🦄…" — Rust scalar indexing yields "🦄…".
    // For "🦄🦄 🦄🦄" columns=5: wantedIndex=4. JS UTF-16[4] = ' ' (space is at
    // index 4 because each emoji takes two code units 0-1 and 2-3); JS slices
    // width-4 → "🦄🦄" → "🦄🦄…". Rust scalar[4] = '🦄' (fifth scalar, second
    // trailing unicorn); searches left, finds space at scalar[2], slices
    // width-2 → "🦄" → "🦄…".
    #[test]
    fn prefer_space_end_astral_divergence() {
        // DIVERGENCE (documented in module docs): JS indexes by UTF-16 code unit.
        // node: cli-truncate@6 returns "🦄🦄…" — Rust scalar indexing yields "🦄…".
        assert_eq!(
            cli_truncate_with("🦄🦄 🦄🦄", 5, &with_prefer(TruncateOptions::default())),
            "🦄\u{2026}"
        );
    }

    // ── Adversarial: truncation-character width / cut-math boundaries ─────────

    fn tc(s: &str) -> TruncateOptions {
        TruncateOptions {
            truncation_character: s.to_owned(),
            ..Default::default()
        }
    }

    // A middle-truncate of CJK with space:true keeps a real trailing space — a
    // future "trim stray trailing whitespace" cleanup would silently break parity.
    // node: cliTruncate("古池や蛙飛び", 8, {position:'middle', space:true}) === "古池 … "
    #[test]
    fn truncate_end_cjk_middle_space_keeps_trailing_space() {
        let opts = with_space(middle());
        assert_eq!(
            cli_truncate_with("古池や蛙飛び", 8, &opts),
            "古池 \u{2026} "
        );
    }

    // truncation_character wider than columns: Node returns the bare truncation
    // char (width 3) even though columns is 2 — `columns - width(tc)` goes
    // negative, clamps the source slice to empty, leaving just the char. A
    // "more sensible" clamp/cap would diverge.
    // node: cliTruncate("abcdef", 2, {truncationCharacter:'...'}) === "..."
    #[test]
    fn truncate_end_overlong_truncation_char_exceeds_columns() {
        assert_eq!(cli_truncate_with("abcdef", 2, &tc("...")), "...");
    }

    // A width-2 truncation char with columns==2 yields just the char (no source
    // text). Mishandling the wide-char width accounting would drop or duplicate.
    // node: cliTruncate("abcdef", 2, {truncationCharacter:'古'}) === "古"
    #[test]
    fn truncate_end_wide_truncation_char_col_two() {
        assert_eq!(cli_truncate_with("abcdef", 2, &tc("")), "");
    }

    // Empty truncation char (visible width 0) is a degenerate boundary; an
    // off-by-one in the `columns - width(tc)` / `length - columns + width(tc)`
    // math would shift the cut. Pins all three positions.
    // node: cliTruncate("unicorn", 4, {truncationCharacter:''}) === 'unic' / 'corn' / 'unrn'
    #[test]
    fn truncate_empty_truncation_char_all_positions() {
        assert_eq!(cli_truncate_with("unicorn", 4, &tc("")), "unic"); // End
        let mut start_empty = start();
        start_empty.truncation_character = String::new();
        assert_eq!(cli_truncate_with("unicorn", 4, &start_empty), "corn");
        let mut mid_empty = middle();
        mid_empty.truncation_character = String::new();
        assert_eq!(cli_truncate_with("unicorn", 4, &mid_empty), "unrn");
    }

    // An ANSI-wrapped '.' as the truncation char has visible width 1 (ANSI
    // stripped by string_width). If tc width were measured by byte/char length
    // instead, the cut would shift.
    // node: cliTruncate("unicorn", 4, {truncationCharacter:'\x1b[31m.\x1b[39m'}) === "uni\x1b[31m.\x1b[39m"
    #[test]
    fn truncate_end_ansi_inside_truncation_char_measured_by_visible_width() {
        assert_eq!(
            cli_truncate_with("unicorn", 4, &tc("\x1b[31m.\x1b[39m")),
            "uni\x1b[31m.\x1b[39m"
        );
    }

    // prefer_truncation_on_space with NO space in range must fall back to a hard
    // cut (getIndexOfNearestSpace returns wantedIndex unchanged). A regression in
    // the ±3 search loop or the fallback would shift or drop the cut. All three
    // positions on space-free input.
    // node: cliTruncate("abcdefghij", 5, {preferTruncationOnSpace:true}) === 'abcd…' / '…ghij' / 'ab…ij'
    #[test]
    fn truncate_prefer_on_space_no_space_present_hard_cut() {
        assert_eq!(
            cli_truncate_with("abcdefghij", 5, &with_prefer(TruncateOptions::default())),
            "abcd\u{2026}"
        );
        assert_eq!(
            cli_truncate_with("abcdefghij", 5, &with_prefer(start())),
            "\u{2026}ghij"
        );
        assert_eq!(
            cli_truncate_with("abcdefghij", 5, &with_prefer(middle())),
            "ab\u{2026}ij"
        );
    }

    // Astral text WITHOUT a space does NOT diverge from Node under prefer (unlike
    // the documented astral+space divergence above). Guards the boundary of the
    // known class-1 divergence: a future "fix" that scalar-shifts all astral
    // prefer paths could wrongly break these matching cases.
    // node: cliTruncate("🦄🦄🦄🦄🦄", 5, {preferTruncationOnSpace:true}) === '🦄🦄…' / '…🦄🦄' / '🦄…🦄'
    #[test]
    fn truncate_astral_no_space_prefer_matches_node_all_positions() {
        assert_eq!(
            cli_truncate_with("🦄🦄🦄🦄🦄", 5, &with_prefer(TruncateOptions::default())),
            "🦄🦄\u{2026}"
        );
        assert_eq!(
            cli_truncate_with("🦄🦄🦄🦄🦄", 5, &with_prefer(start())),
            "\u{2026}🦄🦄"
        );
        assert_eq!(
            cli_truncate_with("🦄🦄🦄🦄🦄", 5, &with_prefer(middle())),
            "🦄\u{2026}🦄"
        );
    }
}