| 1 | use unicode_segmentation::UnicodeSegmentation; |
| 2 | |
| 3 | #[derive(Debug, Clone)] |
| 4 | pub struct TabCfg { |
| 5 | replacement: String, |
| 6 | } |
| 7 | |
| 8 | impl TabCfg { |
| 9 | pub fn new(width: usize) -> Self { |
| 10 | TabCfg { |
| 11 | replacement: " ".repeat(width), |
| 12 | } |
| 13 | } |
| 14 | pub fn width(&self) -> usize { |
| 15 | self.replacement.len() |
| 16 | } |
| 17 | pub fn replace(&self) -> bool { |
| 18 | !self.replacement.is_empty() |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | /// Expand tabs as spaces. |
| 23 | pub fn expand(line: &str, tab_cfg: &TabCfg) -> String { |
| 24 | if tab_cfg.replace() && line.as_bytes().contains(&b'\t') { |
| 25 | itertools::join(line.split('\t'), &tab_cfg.replacement) |
| 26 | } else { |
| 27 | line.to_string() |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Remove `prefix` chars from `line`, then call `tabs::expand()`. |
| 32 | pub fn remove_prefix_and_expand(prefix: usize, line: &str, tab_cfg: &TabCfg) -> String { |
| 33 | let line_bytes = line.as_bytes(); |
| 34 | // The to-be-removed prefixes are almost always ascii +/- (or ++/ +/.. for merges) for |
| 35 | // which grapheme clusters are not required. |
| 36 | if line_bytes.len() >= prefix && line_bytes[..prefix].is_ascii() { |
| 37 | // Safety: slicing into the utf-8 line-str is ok, upto `prefix` only ascii was present. |
| 38 | expand(&line[prefix..], tab_cfg) |
| 39 | } else { |
| 40 | let cut_line = line.graphemes(true).skip(prefix).collect::<String>(); |
| 41 | expand(&cut_line, tab_cfg) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | #[cfg(test)] |
| 46 | pub mod tests { |
| 47 | use super::*; |
| 48 | |
| 49 | #[test] |
| 50 | fn test_remove_prefix_and_expand() { |
| 51 | let line = "+-foo\tbar"; |
| 52 | let result = remove_prefix_and_expand(2, line, &TabCfg::new(3)); |
| 53 | assert_eq!(result, "foo bar"); |
| 54 | let result = remove_prefix_and_expand(2, line, &TabCfg::new(0)); |
| 55 | assert_eq!(result, "foo\tbar"); |
| 56 | |
| 57 | let utf8_prefix = "-│-foo\tbar"; |
| 58 | let n = 3; |
| 59 | let result = remove_prefix_and_expand(n, utf8_prefix, &TabCfg::new(1)); |
| 60 | assert_eq!(result, "foo bar"); |
| 61 | // ensure non-ascii chars were removed: |
| 62 | assert!(utf8_prefix.len() - result.len() > n); |
| 63 | } |
| 64 | } |