Simplify wrap_str()
@@ -390,39 +390,37 @@ macro_rules! skip_out_of_file_lines_range_visitor {
}
}
-// Wraps string-like values in an Option. Returns Some when the string adheres
-// to the Rewrite constraints defined for the Rewrite trait and else otherwise.
+// Wraps String in an Option. Returns Some when the string adheres to the
+// Rewrite constraints defined for the Rewrite trait and else otherwise.
pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
- {
- let snippet = s.as_ref();
-
- if !snippet.is_empty() {
- if !snippet.contains('\n') && snippet.len() > shape.width {
- return None;
+ if is_valid_str(&s, max_width, shape) {
+ Some(s)
} else {
- let mut lines = snippet.lines();
-
- if lines.next().unwrap().len() > shape.width {
- return None;
+ None
+ }
}
+fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
+ if !snippet.is_empty() {
+ // First line must fits with `shape.width`.
+ if first_line_width(snippet) > shape.width {
+ return false;
+ }
+ // If the snippet does not include newline, we are done.
+ if first_line_width(snippet) == snippet.len() {
+ return true;
+ }
// The other lines must fit within the maximum width.
- if lines.any(|line| line.len() > max_width) {
- return None;
+ if snippet.lines().skip(1).any(|line| line.len() > max_width) {
+ return false;
}
-
- // `width` is the maximum length of the last line, excluding
- // indentation.
// A special check for the last line, since the caller may
// place trailing characters on this line.
- if snippet.lines().rev().next().unwrap().len() > shape.used_width() + shape.width {
- return None;
+ if last_line_width(snippet) > shape.used_width() + shape.width {
+ return false;
}
}
- }
- }
-
- Some(s)
+ true
}
#[inline]
