/rust/registry/src/index.crates.io-6f17d22bba15001f/nu-ansi-term-0.46.0/src/util.rs
Line | Count | Source (jump to first uncovered line) |
1 | | use crate::display::{AnsiString, AnsiStrings}; |
2 | | use std::ops::Deref; |
3 | | |
4 | | /// Return a substring of the given AnsiStrings sequence, while keeping the formatting. |
5 | 0 | pub fn sub_string<'a>( |
6 | 0 | start: usize, |
7 | 0 | len: usize, |
8 | 0 | strs: &AnsiStrings<'a>, |
9 | 0 | ) -> Vec<AnsiString<'static>> { |
10 | 0 | let mut vec = Vec::new(); |
11 | 0 | let mut pos = start; |
12 | 0 | let mut len_rem = len; |
13 | | |
14 | 0 | for i in strs.0.iter() { |
15 | 0 | let frag_len = i.string.len(); |
16 | 0 | if pos >= frag_len { |
17 | 0 | pos -= frag_len; |
18 | 0 | continue; |
19 | 0 | } |
20 | 0 | if len_rem == 0 { |
21 | 0 | break; |
22 | 0 | } |
23 | 0 |
|
24 | 0 | let end = pos + len_rem; |
25 | 0 | let pos_end = if end >= frag_len { frag_len } else { end }; |
26 | | |
27 | 0 | vec.push(i.style_ref().paint(String::from(&i.string[pos..pos_end]))); |
28 | 0 |
|
29 | 0 | if end <= frag_len { |
30 | 0 | break; |
31 | 0 | } |
32 | 0 |
|
33 | 0 | len_rem -= pos_end - pos; |
34 | 0 | pos = 0; |
35 | | } |
36 | | |
37 | 0 | vec |
38 | 0 | } |
39 | | |
40 | | /// Return a concatenated copy of `strs` without the formatting, as an allocated `String`. |
41 | 0 | pub fn unstyle(strs: &AnsiStrings) -> String { |
42 | 0 | let mut s = String::new(); |
43 | | |
44 | 0 | for i in strs.0.iter() { |
45 | 0 | s += i.string.deref(); |
46 | 0 | } |
47 | | |
48 | 0 | s |
49 | 0 | } |
50 | | |
51 | | /// Return the unstyled length of AnsiStrings. This is equaivalent to `unstyle(strs).len()`. |
52 | 0 | pub fn unstyled_len(strs: &AnsiStrings) -> usize { |
53 | 0 | let mut l = 0; |
54 | 0 | for i in strs.0.iter() { |
55 | 0 | l += i.string.len(); |
56 | 0 | } |
57 | 0 | l |
58 | 0 | } |
59 | | |
60 | | #[cfg(test)] |
61 | | mod test { |
62 | | use super::*; |
63 | | use crate::Color::*; |
64 | | |
65 | | #[test] |
66 | | fn test() { |
67 | | let l = [ |
68 | | Black.paint("first"), |
69 | | Red.paint("-second"), |
70 | | White.paint("-third"), |
71 | | ]; |
72 | | let a = AnsiStrings(&l); |
73 | | assert_eq!(unstyle(&a), "first-second-third"); |
74 | | assert_eq!(unstyled_len(&a), 18); |
75 | | |
76 | | let l2 = [Black.paint("st"), Red.paint("-second"), White.paint("-t")]; |
77 | | assert_eq!(sub_string(3, 11, &a), l2); |
78 | | } |
79 | | } |