Skip to content

Commit

Permalink
Merge pull request #126 from avamsi/jj_nmwsmvxtxuky
Browse files Browse the repository at this point in the history
normalize_stdout: maintain the elasticity of tabs
  • Loading branch information
sachaos authored Aug 18, 2024
2 parents e319cbc + 03c7c3b commit dba2dd6
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/bytes.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
const TAB_SIZE: usize = 4;

pub fn normalize_stdout(b: Vec<u8>) -> Vec<u8> {
// To fix '\t' width issue replace '\t' with ' '
// Naively replace tabs ('\t') with at most `TAB_SIZE` spaces (' ') while
// maintaining the alignment / elasticity (see tests below).
let mut b = b;
let mut i = 0;
while i < b.len() {
if b[i] == b'\t' {
b[i] = b' ';
b.insert(i, b' ');
b.insert(i, b' ');
b.insert(i, b' ');
i += 4;
let r = TAB_SIZE - (i % TAB_SIZE);
for _ in 1..r {
b.insert(i, b' ');
}
i += r - 1;
} else {
i += 1;
}
Expand All @@ -21,8 +25,10 @@ mod test {

#[test]
fn test_normalize_stdout() {
let b = b"hello\tworld".to_vec();
let b = normalize_stdout(b);
assert_eq!(b, b"hello world".to_vec());
assert_eq!(normalize_stdout(b"\t12345".to_vec()), b" 12345".to_vec());
assert_eq!(normalize_stdout(b"1\t2345".to_vec()), b"1 2345".to_vec());
assert_eq!(normalize_stdout(b"12\t345".to_vec()), b"12 345".to_vec());
assert_eq!(normalize_stdout(b"123\t45".to_vec()), b"123 45".to_vec());
assert_eq!(normalize_stdout(b"1234\t5".to_vec()), b"1234 5".to_vec());
}
}

0 comments on commit dba2dd6

Please sign in to comment.