Skip to content

Commit

Permalink
normalize_stdout: maintain the elasticity of tabs
Browse files Browse the repository at this point in the history
#117 (comment)

viddy currently breaks alignment for commands like `echo '1\t2\n\t3'` as
it always adds 4 spaces, this fixes that. One workaround for this is to
plumb the command via `expand` (`echo '1\t2\n\t3' | expand`).

Go version has the same issue, so this is not a regression.
  • Loading branch information
avamsi committed Aug 18, 2024
1 parent e319cbc commit 03c7c3b
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 03c7c3b

Please sign in to comment.