From e3a4a036574da637367a7f99e6de0edc1b93c764 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 16:52:29 +0900 Subject: [PATCH 1/6] Use str::repeat --- src/config/config_type.rs | 5 +---- src/macros.rs | 13 ++++--------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 14c2dcbb8db..7c4298dcf1c 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -236,10 +236,7 @@ macro_rules! create_config { use std::cmp; let max = 0; $( let max = cmp::max(max, stringify!($i).len()+1); )+ - let mut space_str = String::with_capacity(max); - for _ in 0..max { - space_str.push(' '); - } + let space_str = " ".repeat(max); writeln!(out, "Configuration Options:").unwrap(); $( if $stb || include_unstable { diff --git a/src/macros.rs b/src/macros.rs index 18df24b45c8..088b3e4490f 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -540,17 +540,12 @@ fn register_metavariable( name: &str, dollar_count: usize, ) { - let mut new_name = String::new(); - let mut old_name = String::new(); + let mut new_name = "$".repeat(dollar_count - 1); + let mut old_name = "$".repeat(dollar_count); - old_name.push('$'); - for _ in 0..(dollar_count - 1) { - new_name.push('$'); - old_name.push('$'); - } new_name.push('z'); - new_name.push_str(&name); - old_name.push_str(&name); + new_name.push_str(name); + old_name.push_str(name); result.push_str(&new_name); map.insert(old_name, new_name); From a2d9b6d1b11ba318d309a9c5512b3b7974091ccb Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 16:59:50 +0900 Subject: [PATCH 2/6] Remove redundant scopes --- src/config/file_lines.rs | 22 ++++++++++------------ src/config/mod.rs | 18 ++++++++---------- src/formatting.rs | 6 +----- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/config/file_lines.rs b/src/config/file_lines.rs index c085a0b5deb..67d2355c938 100644 --- a/src/config/file_lines.rs +++ b/src/config/file_lines.rs @@ -156,20 +156,18 @@ fn normalize_ranges(ranges: &mut HashMap>) { for ranges in ranges.values_mut() { ranges.sort(); let mut result = vec![]; - { - let mut iter = ranges.iter_mut().peekable(); - while let Some(next) = iter.next() { - let mut next = *next; - while let Some(&&mut peek) = iter.peek() { - if let Some(merged) = next.merge(peek) { - iter.next().unwrap(); - next = merged; - } else { - break; - } + let mut iter = ranges.iter_mut().peekable(); + while let Some(next) = iter.next() { + let mut next = *next; + while let Some(&&mut peek) = iter.peek() { + if let Some(merged) = next.merge(peek) { + iter.next().unwrap(); + next = merged; + } else { + break; } - result.push(next) } + result.push(next) } *ranges = result; } diff --git a/src/config/mod.rs b/src/config/mod.rs index 0790a3be2a6..4a4647a5663 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -257,16 +257,14 @@ impl Config { let parsed: ::toml::Value = toml .parse() .map_err(|e| format!("Could not parse TOML: {}", e))?; - let mut err: String = String::new(); - { - let table = parsed - .as_table() - .ok_or(String::from("Parsed config was not table"))?; - for key in table.keys() { - if !Config::is_valid_name(key) { - let msg = &format!("Warning: Unknown configuration option `{}`\n", key); - err.push_str(msg) - } + let mut err = String::new(); + let table = parsed + .as_table() + .ok_or(String::from("Parsed config was not table"))?; + for key in table.keys() { + if !Config::is_valid_name(key) { + let msg = &format!("Warning: Unknown configuration option `{}`\n", key); + err.push_str(msg) } } match parsed.try_into() { diff --git a/src/formatting.rs b/src/formatting.rs index b14a7b798c7..ccf60b242be 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -48,11 +48,7 @@ impl<'b, T: Write + 'b> Session<'b, T> { let format_result = format_project(input, config, self); format_result.map(|report| { - { - let new_errors = &report.internal.borrow().1; - - self.errors.add(new_errors); - } + self.errors.add(&report.internal.borrow().1); report }) }) From 6e288fdae02c3794b4626bc66c79c5b221d2f117 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 17:27:56 +0900 Subject: [PATCH 3/6] Remove a write of empty string --- src/imports.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/imports.rs b/src/imports.rs index a87d100ca9b..aa2459f7f86 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -225,7 +225,7 @@ impl fmt::Display for UseTree { write!(f, "::")?; } } - write!(f, "") + Ok(()) } } From 8e4c20da80eb31b57abcb695d76cc8720c95e395 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 17:30:39 +0900 Subject: [PATCH 4/6] Write seperator beforehand --- src/imports.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/imports.rs b/src/imports.rs index aa2459f7f86..b0ead7a87b9 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -205,11 +205,10 @@ impl fmt::Display for UseSegment { UseSegment::List(ref list) => { write!(f, "{{")?; for (i, item) in list.iter().enumerate() { - let is_last = i == list.len() - 1; - write!(f, "{}", item)?; - if !is_last { + if i != 0 { write!(f, ", ")?; } + write!(f, "{}", item)?; } write!(f, "}}") } @@ -219,11 +218,10 @@ impl fmt::Display for UseSegment { impl fmt::Display for UseTree { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for (i, segment) in self.path.iter().enumerate() { - let is_last = i == self.path.len() - 1; - write!(f, "{}", segment)?; - if !is_last { + if i != 0 { write!(f, "::")?; } + write!(f, "{}", segment)?; } Ok(()) } From ff0683d66690cef6348226bf1e84c693ad6f6006 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 17:54:29 +0900 Subject: [PATCH 5/6] Simplify iterators --- src/chains.rs | 2 +- src/expr.rs | 4 ++-- src/lists.rs | 9 ++------- src/overflow.rs | 13 +++++++++---- src/vertical.rs | 14 ++++++++------ 5 files changed, 22 insertions(+), 20 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 3d928623aac..832cae898ef 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -550,7 +550,7 @@ impl<'a> ChainFormatterShared<'a> { let almost_total = if extendable { prev_last_line_width } else { - self.rewrites.iter().fold(0, |a, b| a + b.len()) + self.rewrites.iter().map(|a| a.len()).sum() } + last.tries; let one_line_budget = if self.child_count == 1 { shape.width diff --git a/src/expr.rs b/src/expr.rs index 90cbba334f1..11a7767d37c 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1,6 +1,7 @@ use std::borrow::Cow; use std::cmp::min; +use itertools::Itertools; use syntax::parse::token::DelimToken; use syntax::source_map::{BytePos, SourceMap, Span}; use syntax::{ast, ptr}; @@ -1246,8 +1247,7 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> if !context.config.format_strings() { if string_lit .lines() - .rev() - .skip(1) + .dropping_back(1) .all(|line| line.ends_with('\\')) { let new_indent = shape.visual_indent(1).indent; diff --git a/src/lists.rs b/src/lists.rs index 14b799622c9..63cabc3c354 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -577,13 +577,8 @@ pub fn extract_pre_comment(pre_snippet: &str) -> (Option, ListItemCommen let has_block_comment = trimmed_pre_snippet.ends_with("*/"); let has_single_line_comment = trimmed_pre_snippet.starts_with("//"); if has_block_comment { - let comment_end = pre_snippet.chars().rev().position(|c| c == '/').unwrap(); - if pre_snippet - .chars() - .rev() - .take(comment_end + 1) - .any(|c| c == '\n') - { + let comment_end = pre_snippet.rfind(|c| c == '/').unwrap(); + if pre_snippet[comment_end..].contains('\n') { ( Some(trimmed_pre_snippet.to_owned()), ListItemCommentStyle::DifferentLine, diff --git a/src/overflow.rs b/src/overflow.rs index ac425b591aa..17e04b2e7a4 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -2,6 +2,7 @@ use std::cmp::min; +use itertools::Itertools; use syntax::parse::token::DelimToken; use syntax::source_map::Span; use syntax::{ast, ptr}; @@ -711,10 +712,14 @@ fn last_item_shape( if items.len() == 1 && !lists.get(0)?.is_nested_call() { return Some(shape); } - let offset = items.iter().rev().skip(1).fold(0, |acc, i| { - // 2 = ", " - acc + 2 + i.inner_as_ref().len() - }); + let offset = items + .iter() + .dropping_back(1) + .map(|i| { + // 2 = ", " + 2 + i.inner_as_ref().len() + }) + .sum(); Shape { width: min(args_max_width, shape.width), ..shape diff --git a/src/vertical.rs b/src/vertical.rs index 9dca1d600f3..a7977a64e6c 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -2,6 +2,7 @@ use std::cmp; +use itertools::Itertools; use syntax::ast; use syntax::source_map::{BytePos, Span}; @@ -190,11 +191,8 @@ fn struct_field_prefix_max_min_width( } }) }) - .fold(Some((0, ::std::usize::MAX)), |acc, len| match (acc, len) { - (Some((max_len, min_len)), Some(len)) => { - Some((cmp::max(max_len, len), cmp::min(min_len, len))) - } - _ => None, + .fold_options((0, ::std::usize::MAX), |(max_len, min_len), len| { + (cmp::max(max_len, len), cmp::min(min_len, len)) }) .unwrap_or((0, 0)) } @@ -274,7 +272,11 @@ fn group_aligned_items( .skip(1) .collect::>() .join("\n"); - let spacings = if snippet.lines().rev().skip(1).any(|l| l.trim().is_empty()) { + let spacings = if snippet + .lines() + .dropping_back(1) + .any(|l| l.trim().is_empty()) + { "\n" } else { "" From 9fda93777965f0023d055c947e8f2dc301dbc62f Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Fri, 29 Mar 2019 19:17:50 +0900 Subject: [PATCH 6/6] Remove redundant & --- src/comment.rs | 4 ++-- src/expr.rs | 2 +- src/items.rs | 8 ++++---- src/test/mod.rs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 83ec810381e..87c6b65865b 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -591,7 +591,7 @@ impl<'a> CommentRewrite<'a> { ) { Some(s) => self.result.push_str(&Self::join_block( &s, - &format!("{}{}", &self.comment_line_separator, ib.line_start), + &format!("{}{}", self.comment_line_separator, ib.line_start), )), None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), @@ -634,7 +634,7 @@ impl<'a> CommentRewrite<'a> { ) { Some(s) => self.result.push_str(&Self::join_block( &s, - &format!("{}{}", &self.comment_line_separator, ib.line_start), + &format!("{}{}", self.comment_line_separator, ib.line_start), )), None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), diff --git a/src/expr.rs b/src/expr.rs index 11a7767d37c..8d241dff1f9 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1459,7 +1459,7 @@ fn rewrite_paren( let subexpr_str = subexpr.rewrite(context, sub_shape)?; let fits_single_line = !pre_comment.contains("//") && !post_comment.contains("//"); if fits_single_line { - Some(format!("({}{}{})", pre_comment, &subexpr_str, post_comment)) + Some(format!("({}{}{})", pre_comment, subexpr_str, post_comment)) } else { rewrite_paren_in_multi_line(context, subexpr, shape, pre_span, post_span) } diff --git a/src/items.rs b/src/items.rs index 8cd6010f72f..1647ecfcc3b 100644 --- a/src/items.rs +++ b/src/items.rs @@ -730,7 +730,7 @@ pub fn format_impl( if generics.where_clause.predicates.len() == 1 { result.push_str(","); } - result.push_str(&format!("{}{{{}}}", &sep, &sep)); + result.push_str(&format!("{}{{{}}}", sep, sep)); } else { result.push_str(" {}"); } @@ -912,7 +912,7 @@ fn rewrite_trait_ref( let shape = Shape::indented(offset + used_space, context.config); if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) { if !trait_ref_str.contains('\n') { - return Some(format!(" {}{}", polarity_str, &trait_ref_str)); + return Some(format!(" {}{}", polarity_str, trait_ref_str)); } } // We could not make enough space for trait_ref, so put it on new line. @@ -921,9 +921,9 @@ fn rewrite_trait_ref( let trait_ref_str = trait_ref.rewrite(context, shape)?; Some(format!( "{}{}{}", - &offset.to_string_with_newline(context.config), + offset.to_string_with_newline(context.config), polarity_str, - &trait_ref_str + trait_ref_str )) } diff --git a/src/test/mod.rs b/src/test/mod.rs index fc25d27b531..dc297a52dfb 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -609,11 +609,11 @@ fn handle_result( for (file_name, fmt_text) in result { // If file is in tests/source, compare to file with same name in tests/target. let target = get_target(&file_name, target); - let open_error = format!("couldn't open target {:?}", &target); + let open_error = format!("couldn't open target {:?}", target); let mut f = fs::File::open(&target).expect(&open_error); let mut text = String::new(); - let read_error = format!("failed reading target {:?}", &target); + let read_error = format!("failed reading target {:?}", target); f.read_to_string(&mut text).expect(&read_error); // Ignore LF and CRLF difference for Windows.