From 03c7c3bea44d2f4d8debe2889474a49e52a2a874 Mon Sep 17 00:00:00 2001 From: Vamsi Avula Date: Sun, 18 Aug 2024 13:53:09 +0530 Subject: [PATCH] normalize_stdout: maintain the elasticity of tabs https://github.com/sachaos/viddy/issues/117#issuecomment-2294925153 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. --- src/bytes.rs | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/bytes.rs b/src/bytes.rs index a2de603..f3bb121 100644 --- a/src/bytes.rs +++ b/src/bytes.rs @@ -1,14 +1,18 @@ +const TAB_SIZE: usize = 4; + pub fn normalize_stdout(b: Vec) -> Vec { - // 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; } @@ -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()); } }