From 7a83b65fbeed85a51975fc31d3c292ff192fb2ef Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Sun, 29 Jan 2023 22:40:27 -0500 Subject: [PATCH] Pre-allocate output contents during autofix application (#2340) --- src/autofix/mod.rs | 4 ++-- src/source_code/locator.rs | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/autofix/mod.rs b/src/autofix/mod.rs index 1f77cbccdc..e1edce1f2d 100644 --- a/src/autofix/mod.rs +++ b/src/autofix/mod.rs @@ -27,7 +27,7 @@ fn apply_fixes<'a>( fixes: impl Iterator, locator: &'a Locator<'a>, ) -> (String, usize) { - let mut output = String::new(); + let mut output = String::with_capacity(locator.len()); let mut last_pos: Location = Location::new(1, 0); let mut applied: BTreeSet<&Fix> = BTreeSet::default(); let mut num_fixed: usize = 0; @@ -68,7 +68,7 @@ fn apply_fixes<'a>( /// Apply a single fix. pub(crate) fn apply_fix(fix: &Fix, locator: &Locator) -> String { - let mut output = String::new(); + let mut output = String::with_capacity(locator.len()); // Add all contents from `last_pos` to `fix.location`. let slice = locator.slice_source_code_range(&Range::new(Location::new(1, 0), fix.location)); diff --git a/src/source_code/locator.rs b/src/source_code/locator.rs index 0401e6468e..575b13fa31 100644 --- a/src/source_code/locator.rs +++ b/src/source_code/locator.rs @@ -139,6 +139,14 @@ impl<'a> Locator<'a> { &self.contents[inner_end..outer_end], ) } + + pub fn len(&self) -> usize { + self.contents.len() + } + + pub fn is_empty(&self) -> bool { + self.contents.is_empty() + } } #[cfg(test)]