-
Notifications
You must be signed in to change notification settings - Fork 0
/
ansi_preserving_slice.rs
63 lines (54 loc) · 1.5 KB
/
ansi_preserving_slice.rs
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
use console;
use std::cmp::min;
use itertools::Itertools;
/// Return string formed from a byte slice starting at byte position `start`, where the index skips
/// bytes in ANSI escape sequences.
pub fn ansi_preserving_slice(s: &str, start: usize) -> String {
console::AnsiCodeIterator::new(s)
.scan(0, |i, (s, is_ansi)| {
let s = if *i > start {
s
} else if is_ansi {
s
} else if s.is_empty() {
s
} else {
&s[min(s.len(), start - *i)..]
};
if !is_ansi {
*i += s.len();
}
Some(s)
})
.join("")
}
#[cfg(test)]
mod tests {
use crate::ansi::ansi_preserving_slice;
#[test]
fn test_ansi_preserving_slice_1() {
assert_eq!(ansi_preserving_slice("", 0), "");
}
#[test]
fn test_ansi_preserving_slice_2() {
assert_eq!(ansi_preserving_slice("a", 0), "a");
}
#[test]
fn test_ansi_preserving_slice_3() {
assert_eq!(ansi_preserving_slice("a", 1), "");
}
#[test]
fn test_ansi_preserving_slice_4() {
assert_eq!(
ansi_preserving_slice("\x1b[1;35m-2222.2222.2222.2222\x1b[0m", 1),
"\x1b[1;35m2222.2222.2222.2222\x1b[0m"
);
}
#[test]
fn test_ansi_preserving_slice_5() {
assert_eq!(
ansi_preserving_slice("\x1b[1;35m-2222.2222.2222.2222\x1b[0m", 15),
"\x1b[1;35m.2222\x1b[0m"
);
}
}