Skip to content

Commit

Permalink
Fix incorrect line width problem
Browse files Browse the repository at this point in the history
  • Loading branch information
Wenqing Zong authored and WenqingZong committed Apr 1, 2024
1 parent f7374a4 commit 8537cd9
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ license = "MIT OR Apache-2.0"
clippy = []

[dependencies]
regex = "1.10.4"
smallvec = "1.11.2"
textwrap = "0.16.0"
unicode-width = "0.1.11"
Expand Down
12 changes: 11 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use regex::Regex;
use smallvec::*;
use std::io::{Result, Write};
use textwrap::fill;
Expand Down Expand Up @@ -84,8 +85,11 @@ where
// Final output is stored here
let mut write_buffer = SmallVec::<[u8; BUFSIZE]>::new();

// Pre process to merge continuous whitespaces into one space character
let input = merge_white_spaces(input);

// Let textwrap work its magic
let wrapped = fill(input, max_width);
let wrapped = fill(input.as_str(), max_width);

let lines: Vec<&str> = wrapped.lines().collect();

Expand Down Expand Up @@ -147,3 +151,9 @@ fn longest_line(lines: &[&str]) -> usize {
.max()
.unwrap_or(0)
}

/// Merge continues white spaces into one space character while preserving newline characters.
fn merge_white_spaces(input: &str) -> String {
let re = Regex::new(r"([^\S\r\n])+").unwrap();
re.replace_all(input, " ").to_string()
}
55 changes: 55 additions & 0 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,58 @@ fn multibyte_string() -> Result<(), ()> {
assert_eq!(&expected[1..], actual);
Ok(())
}

#[test]
fn string_with_continues_white_spaces() -> Result<(), ()> {
#[cfg(not(feature = "clippy"))]
let expected = r#"
__________________________________
/ A string with many white spaces \
| |
| |
\ And many newline characters /
----------------------------------
\
\
_~^~^~_
\) / o o \ (/
'_ - _'
/ '-----' \
"#;
#[cfg(feature = "clippy")]
let expected = r#"
__________________________________
/ A string with many white spaces \
| |
| |
\ And many newline characters /
----------------------------------
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
"#;

let input = " A string with many white spaces
And many newline characters";
let width = DEFAULT_WIDTH;

let mut vec = Vec::new();

say(input, width, &mut vec).unwrap();

let actual = std::str::from_utf8(&vec).unwrap();

assert_eq!(&expected[1..], actual);

Ok(())
}

0 comments on commit 8537cd9

Please sign in to comment.