atuin-common 18.19.0

common library for atuin
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
//! Extension trait for truncating a string to a budget (display columns or
//! bytes) with an ellipsis.

use std::borrow::Cow;
use std::fmt;

use unicode_segmentation::UnicodeSegmentation;

use super::Measure;
use super::align::{AlignExt, Alignment};

/// Which side of the string to elide when it does not fit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pos {
    /// Keep the tail, elide the head: `…orld`.
    Start,
    /// Keep both ends, elide the middle: `he…ld`.
    Middle,
    /// Keep the head, elide the tail: `hello…`.
    End,
}

/// The marker spliced in where content was dropped: [`Indicator::ASCII`]
/// (`...`), [`Indicator::UNICODE`] (`…`), or any custom string via
/// [`Indicator::new`] (e.g. `[output truncated]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, derive_more::AsRef)]
pub struct Indicator<'a>(#[as_ref(str)] &'a str);

impl<'a> Indicator<'a> {
    /// Three ASCII periods `...` (3 columns, 3 bytes).
    pub const ASCII: Self = Self("...");
    /// The single Unicode ellipsis `…` (U+2026): 1 column, 3 bytes.
    pub const UNICODE: Self = Self("");

    /// Wrap an arbitrary marker string.
    pub const fn new(marker: &'a str) -> Self {
        Self(marker)
    }
}

impl Default for Indicator<'_> {
    /// The Unicode ellipsis `…`.
    fn default() -> Self {
        Self::UNICODE
    }
}

pub trait EllipsizeExt: AsRef<str> {
    /// Truncate this string to fit within `budget`, splicing in `indicator` on
    /// `side` if any content had to be dropped. Returns a lazy [`Ellipsized`]
    /// view - no allocation until you ask for an owned string.
    fn ellipsize<'a>(
        &'a self,
        budget: Measure,
        side: Pos,
        indicator: Indicator<'a>,
    ) -> Ellipsized<'a> {
        let s = self.as_ref();
        let amount = budget.amount();
        let len = s.len();
        let cost = |seg: &str| budget.cost(seg);

        if cost(s) <= amount {
            return Ellipsized::contiguous(s, 0);
        }

        // Not enough room for the indicator itself: hard-truncate to a bare, unmarked slice.
        let indicator_cost = cost(indicator.as_ref());
        if amount < indicator_cost {
            return match side {
                Pos::Start => {
                    let start = suffix_boundary(s, amount, cost);
                    Ellipsized::contiguous(&s[start..], start)
                }
                Pos::Middle | Pos::End => {
                    Ellipsized::contiguous(&s[..prefix_boundary(s, amount, cost)], 0)
                }
            };
        }

        let content = amount - indicator_cost;
        match side {
            Pos::End => Ellipsized::spliced(s, prefix_boundary(s, content, cost), len, indicator),
            Pos::Start => Ellipsized::spliced(s, 0, suffix_boundary(s, content, cost), indicator),
            Pos::Middle => {
                let end = prefix_boundary(s, content.div_ceil(2), cost);
                let start = suffix_boundary(s, content / 2, cost).max(end);
                Ellipsized::spliced(s, end, start, indicator)
            }
        }
    }

    /// Fit `self` to `budget`: ellipsize it on `side` with `indicator` when it exceeds the budget,
    /// otherwise pad it with spaces, aligned per `align`.
    fn pad_ellipsize<'a>(
        &'a self,
        budget: Measure,
        side: Pos,
        indicator: Indicator<'a>,
        align: Alignment,
    ) -> Cow<'a, str>
    where
        Self: Sized,
    {
        if budget.cost(self.as_ref()) > budget.amount() {
            self.ellipsize(budget, side, indicator).into()
        } else {
            self.pad_to(budget, align)
        }
    }
}

impl<T: AsRef<str>> EllipsizeExt for T {}

/// A budget-truncated view of a source string - either a single contiguous
/// slice (it fit, or there was no room even for the indicator) or a head +
/// indicator + tail with content elided between them.
///
/// Cheap `Copy`. `Display` writes the pieces straight to the formatter.
#[derive(Debug, Clone, Copy)]
pub struct Ellipsized<'a>(Repr<'a>);

#[derive(Debug, Clone, Copy)]
enum Repr<'a> {
    /// The whole result is one contiguous slice of the source; `source_offset`
    /// is the slice's byte offset in the source.
    Contiguous { text: &'a str, source_offset: usize },
    /// A head slice, an indicator, and a tail slice - always with a marker.
    Spliced {
        head: &'a str,
        indicator: Indicator<'a>,
        tail: &'a str,
        /// Byte offset of `tail` in the source, for [`Ellipsized::source_index`].
        tail_source_offset: usize,
    },
}

impl<'a> Ellipsized<'a> {
    fn contiguous(text: &'a str, source_offset: usize) -> Self {
        Self(Repr::Contiguous {
            text,
            source_offset,
        })
    }

    fn spliced(
        source: &'a str,
        head_end: usize,
        tail_start: usize,
        indicator: Indicator<'a>,
    ) -> Self {
        Self(Repr::Spliced {
            head: &source[..head_end],
            tail: &source[tail_start..],
            tail_source_offset: tail_start,
            indicator,
        })
    }

    /// Map a byte offset in the output back to its byte offset in the source,
    /// or `None` if it lands on the spliced indicator.
    pub fn source_index(self, output_byte: usize) -> Option<usize> {
        match self.0 {
            Repr::Contiguous { source_offset, .. } => Some(output_byte + source_offset),
            Repr::Spliced {
                head,
                indicator,
                tail_source_offset,
                ..
            } => {
                let indicator_len = indicator.as_ref().len();
                if output_byte < head.len() {
                    Some(output_byte)
                } else if output_byte >= head.len() + indicator_len {
                    Some(output_byte - head.len() - indicator_len + tail_source_offset)
                } else {
                    None
                }
            }
        }
    }
}

impl fmt::Display for Ellipsized<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Repr::Contiguous { text, .. } => f.write_str(text),
            Repr::Spliced {
                head,
                indicator,
                tail,
                ..
            } => {
                f.write_str(head)?;
                f.write_str(indicator.as_ref())?;
                f.write_str(tail)
            }
        }
    }
}

impl<'a> From<Ellipsized<'a>> for Cow<'a, str> {
    /// Borrowed for a contiguous slice; owned only when an indicator is spliced.
    fn from(ellipsized: Ellipsized<'a>) -> Self {
        match ellipsized.0 {
            Repr::Contiguous { text, .. } => Cow::Borrowed(text),
            Repr::Spliced { .. } => Cow::Owned(ellipsized.to_string()),
        }
    }
}

impl PartialEq<str> for Ellipsized<'_> {
    /// Compares against the concatenated output without allocating.
    fn eq(&self, other: &str) -> bool {
        match self.0 {
            Repr::Contiguous { text, .. } => text == other,
            Repr::Spliced {
                head,
                indicator,
                tail,
                ..
            } => [head, indicator.as_ref(), tail]
                .into_iter()
                .try_fold(other, |rest, piece| rest.strip_prefix(piece))
                .is_some_and(str::is_empty),
        }
    }
}

impl PartialEq<&str> for Ellipsized<'_> {
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}

/// Total byte length of the longest leading run of `graphemes` whose summed
/// `cost` is at most `max`.
fn fitting_bytes<'a>(
    graphemes: impl Iterator<Item = &'a str>,
    max: usize,
    cost: impl Fn(&str) -> usize,
) -> usize {
    let mut used = 0;
    let mut bytes = 0;
    for seg in graphemes {
        let seg_cost = cost(seg);
        if used + seg_cost > max {
            break;
        }
        used += seg_cost;
        bytes += seg.len();
    }
    bytes
}

/// Byte end index of the longest prefix of `s` whose summed per-grapheme cost is
/// at most `max`.
fn prefix_boundary(s: &str, max: usize, cost: impl Fn(&str) -> usize) -> usize {
    fitting_bytes(s.graphemes(true), max, cost)
}

/// Byte start index of the longest suffix of `s` whose summed per-grapheme cost
/// is at most `max`.
fn suffix_boundary(s: &str, max: usize, cost: impl Fn(&str) -> usize) -> usize {
    s.len() - fitting_bytes(s.graphemes(true).rev(), max, cost)
}

#[cfg(test)]
mod tests {
    use super::{EllipsizeExt, Indicator, Measure, Pos};
    use crate::string::align::Alignment;
    use pretty_assertions::assert_eq;
    use proptest::prelude::*;
    use rstest::rstest;
    use unicode_width::UnicodeWidthStr;

    fn amount(b: Measure) -> usize {
        match b {
            Measure::Bytes(n) => n,
            Measure::Columns(n) => n,
        }
    }

    fn cost(b: Measure, s: &str) -> usize {
        match b {
            Measure::Bytes(_) => s.len(),
            Measure::Columns(_) => UnicodeWidthStr::width(s),
        }
    }

    #[rstest]
    #[case::ascii_fits_under_column_budget(
        "hello",
        Measure::Columns(10),
        Pos::End,
        Indicator::ASCII,
        "hello"
    )]
    #[case::ascii_exactly_fits_column_budget(
        "hello",
        Measure::Columns(5),
        Pos::End,
        Indicator::ASCII,
        "hello"
    )]
    #[case::ascii_truncates_end_with_ascii_indicator(
        "hello world",
        Measure::Columns(8),
        Pos::End,
        Indicator::ASCII,
        "hello..."
    )]
    #[case::ascii_truncates_start_with_ascii_indicator(
        "hello world",
        Measure::Columns(8),
        Pos::Start,
        Indicator::ASCII,
        "...world"
    )]
    #[case::ascii_truncates_middle_with_ascii_indicator(
        "hello world",
        Measure::Columns(7),
        Pos::Middle,
        Indicator::ASCII,
        "he...ld"
    )]
    #[case::ascii_truncates_end_with_unicode_indicator(
        "hello world",
        Measure::Columns(6),
        Pos::End,
        Indicator::UNICODE,
        "hello…"
    )]
    #[case::ascii_truncates_start_with_unicode_indicator(
        "hello world",
        Measure::Columns(6),
        Pos::Start,
        Indicator::UNICODE,
        "…world"
    )]
    #[case::cjk_truncates_under_column_budget(
        "你好世界",
        Measure::Columns(5),
        Pos::End,
        Indicator::ASCII,
        "你..."
    )]
    #[case::cjk_truncates_to_indicator_only_under_tiny_column_budget(
        "你好世界",
        Measure::Columns(4),
        Pos::End,
        Indicator::ASCII,
        "..."
    )]
    #[case::cjk_exactly_fits_column_budget(
        "你好世界",
        Measure::Columns(8),
        Pos::End,
        Indicator::ASCII,
        "你好世界"
    )]
    #[case::emoji_truncates_end_under_column_budget_with_unicode_indicator(
        "🐢🦀🐢🦀",
        Measure::Columns(5),
        Pos::End,
        Indicator::UNICODE,
        "🐢🦀…"
    )]
    #[case::emoji_exactly_fits_column_budget(
        "🐢🦀🐢🦀",
        Measure::Columns(8),
        Pos::End,
        Indicator::UNICODE,
        "🐢🦀🐢🦀"
    )]
    #[case::ascii_hard_truncates_end_when_budget_below_indicator_cost(
        "hello",
        Measure::Columns(2),
        Pos::End,
        Indicator::ASCII,
        "he"
    )]
    #[case::ascii_hard_truncates_start_when_budget_below_indicator_cost(
        "hello",
        Measure::Columns(2),
        Pos::Start,
        Indicator::ASCII,
        "lo"
    )]
    #[case::ascii_zero_budget_yields_empty_string(
        "hello",
        Measure::Columns(0),
        Pos::End,
        Indicator::ASCII,
        ""
    )]
    #[case::empty_input_yields_empty_string(
        "",
        Measure::Columns(5),
        Pos::End,
        Indicator::ASCII,
        ""
    )]
    #[case::ascii_truncates_end_under_byte_budget(
        "hello world",
        Measure::Bytes(8),
        Pos::End,
        Indicator::ASCII,
        "hello..."
    )]
    #[case::ascii_truncates_end_under_byte_budget_with_unicode_indicator(
        "hello world",
        Measure::Bytes(8),
        Pos::End,
        Indicator::UNICODE,
        "hello…"
    )]
    #[case::accented_truncates_end_under_byte_budget(
        "café",
        Measure::Bytes(4),
        Pos::End,
        Indicator::ASCII,
        "c..."
    )]
    #[case::accented_exactly_fits_byte_budget(
        "café",
        Measure::Bytes(5),
        Pos::End,
        Indicator::ASCII,
        "café"
    )]
    #[case::cjk_truncates_to_indicator_only_under_byte_budget(
        "你好",
        Measure::Bytes(5),
        Pos::End,
        Indicator::ASCII,
        "..."
    )]
    fn truncates_per_table(
        #[case] input: &str,
        #[case] budget: Measure,
        #[case] side: Pos,
        #[case] ellipsis: Indicator<'static>,
        #[case] expected: &str,
    ) {
        assert_eq!(input.ellipsize(budget, side, ellipsis), *expected);
    }

    #[rstest]
    #[case::start_pads_when_shorter("hi", Measure::Columns(5), Pos::End, Alignment::Start, "hi   ")]
    #[case::unchanged_when_exact_budget(
        "hello",
        Measure::Columns(5),
        Pos::End,
        Alignment::Start,
        "hello"
    )]
    #[case::ellipsizes_end_when_too_wide(
        "hello world",
        Measure::Columns(6),
        Pos::End,
        Alignment::Start,
        "hello…"
    )]
    #[case::ellipsizes_start_when_too_wide(
        "hello world",
        Measure::Columns(6),
        Pos::Start,
        Alignment::Start,
        "…world"
    )]
    #[case::empty_pads_to_budget("", Measure::Columns(3), Pos::End, Alignment::Start, "   ")]
    #[case::wide_glyph_exact_column_budget(
        "",
        Measure::Columns(2),
        Pos::End,
        Alignment::Start,
        ""
    )]
    #[case::wide_glyph_pads_by_display_columns(
        "",
        Measure::Columns(3),
        Pos::End,
        Alignment::Start,
        ""
    )]
    #[case::pads_by_bytes_under_byte_budget(
        "",
        Measure::Bytes(4),
        Pos::End,
        Alignment::Start,
        ""
    )]
    #[case::end_align_left_pads("hi", Measure::Columns(5), Pos::End, Alignment::End, "   hi")]
    #[case::center_even_split("hi", Measure::Columns(6), Pos::End, Alignment::Center, "  hi  ")]
    #[case::center_odd_extra_on_right(
        "hi",
        Measure::Columns(5),
        Pos::End,
        Alignment::Center,
        " hi  "
    )]
    #[case::align_ignored_when_elided(
        "hello world",
        Measure::Columns(6),
        Pos::End,
        Alignment::End,
        "hello…"
    )]
    fn pad_ellipsize_table(
        #[case] input: &str,
        #[case] budget: Measure,
        #[case] side: Pos,
        #[case] align: Alignment,
        #[case] expected: &str,
    ) {
        assert_eq!(
            input
                .pad_ellipsize(budget, side, Indicator::UNICODE, align)
                .as_ref(),
            expected
        );
    }

    #[test]
    fn pad_ellipsize_borrows_only_when_no_alloc_needed() {
        // Exact fit: no padding, no elision -> borrowed.
        assert!(matches!(
            "hello".pad_ellipsize(
                Measure::Columns(5),
                Pos::End,
                Indicator::UNICODE,
                Alignment::Start
            ),
            std::borrow::Cow::Borrowed(_)
        ));
        // Padding needed -> owned.
        assert!(matches!(
            "hi".pad_ellipsize(
                Measure::Columns(5),
                Pos::End,
                Indicator::UNICODE,
                Alignment::Start
            ),
            std::borrow::Cow::Owned(_)
        ));
    }

    fn any_pos() -> impl Strategy<Value = Pos> {
        prop_oneof![Just(Pos::Start), Just(Pos::Middle), Just(Pos::End)]
    }

    fn any_indicator() -> impl Strategy<Value = Indicator<'static>> {
        prop_oneof![Just(Indicator::ASCII), Just(Indicator::UNICODE)]
    }

    fn any_budget() -> impl Strategy<Value = Measure> {
        prop_oneof![
            (0usize..40).prop_map(Measure::Bytes),
            (0usize..40).prop_map(Measure::Columns),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(2048))]

        #[test]
        fn never_overflows(
            s in r"(?s).*",
            budget in any_budget(),
            side in any_pos(),
            ellipsis in any_indicator(),
        ) {
            let out = s.ellipsize(budget, side, ellipsis).to_string();
            prop_assert!(cost(budget, out.as_ref()) <= amount(budget));
        }

        #[test]
        fn borrowed_when_it_fits(
            s in r"(?s).*",
            budget in any_budget(),
            side in any_pos(),
            ellipsis in any_indicator(),
        ) {
            if cost(budget, &s) <= amount(budget) {
                let result = s.ellipsize(budget, side, ellipsis);
                prop_assert!(matches!(
                    std::borrow::Cow::from(result),
                    std::borrow::Cow::Borrowed(_)
                ));
                prop_assert!(result == s.as_str());
            }
        }

        #[test]
        fn never_grows(
            s in r"(?s).*",
            budget in any_budget(),
            side in any_pos(),
            ellipsis in any_indicator(),
        ) {
            let out = s.ellipsize(budget, side, ellipsis).to_string();
            prop_assert!(cost(budget, out.as_ref()) <= cost(budget, &s));
        }

        #[test]
        fn valid_byte_cut(
            s in r"(?s).*",
            n in 0usize..40,
            side in any_pos(),
            ellipsis in any_indicator(),
        ) {
            let out = s.ellipsize(Measure::Bytes(n), side, ellipsis).to_string();
            prop_assert!(out.len() <= n);
        }

        #[test]
        fn ellipsis_present_when_needed(
            s in r"(?s).*",
            budget in any_budget(),
            side in any_pos(),
            ellipsis in any_indicator(),
        ) {
            let glyph = ellipsis.as_ref();
            let ellipsis_cost = cost(budget, glyph);
            if cost(budget, &s) > amount(budget) && amount(budget) >= ellipsis_cost {
                let out = s.ellipsize(budget, side, ellipsis).to_string();
                prop_assert!(out.contains(glyph));
            }
        }

        #[test]
        fn source_index_round_trips(
            s in r"(?s).*",
            budget in any_budget(),
            side in any_pos(),
            indicator in any_indicator(),
        ) {
            let e = s.ellipsize(budget, side, indicator);
            let out = e.to_string();
            for (i, ch) in out.char_indices() {
                if let Some(j) = e.source_index(i) {
                    prop_assert_eq!(s[j..].chars().next(), Some(ch));
                }
            }
        }
    }

    #[test]
    fn source_index_middle_maps_head_gap_tail() {
        let e = "hello world".ellipsize(Measure::Columns(7), Pos::Middle, Indicator::ASCII);
        assert_eq!(e.to_string(), "he...ld");
        assert_eq!(e.source_index(0), Some(0));
        assert_eq!(e.source_index(1), Some(1));
        assert_eq!(e.source_index(2), None);
        assert_eq!(e.source_index(4), None);
        assert_eq!(e.source_index(5), Some(9));
        assert_eq!(e.source_index(6), Some(10));
    }

    #[test]
    fn source_index_fits_is_identity() {
        let e = "hi".ellipsize(Measure::Columns(10), Pos::Middle, Indicator::ASCII);
        assert!(matches!(
            std::borrow::Cow::from(e),
            std::borrow::Cow::Borrowed(_)
        ));
        assert_eq!(e.source_index(0), Some(0));
        assert_eq!(e.source_index(1), Some(1));
    }

    #[test]
    fn display_writes_without_allocating_via_cow() {
        let e = "hello world".ellipsize(Measure::Columns(8), Pos::End, Indicator::ASCII);
        assert_eq!(e.to_string(), "hello...");
        assert!(matches!(
            std::borrow::Cow::from(e),
            std::borrow::Cow::Owned(_)
        ));

        let fits = "hi".ellipsize(Measure::Columns(8), Pos::End, Indicator::ASCII);
        assert!(matches!(
            std::borrow::Cow::from(fits),
            std::borrow::Cow::Borrowed(_)
        ));
    }
}