diff --git a/crates/ruff_formatter/src/lib.rs b/crates/ruff_formatter/src/lib.rs index 729d48849a2ae..e98d998ef3687 100644 --- a/crates/ruff_formatter/src/lib.rs +++ b/crates/ruff_formatter/src/lib.rs @@ -319,20 +319,20 @@ where Context: FormatContext, { pub fn print(&self) -> PrintResult { - let source_code = self.context.source_code(); - let print_options = self.context.options().as_print_options(); - let printed = Printer::new(source_code, print_options).print(&self.document)?; - - Ok(printed) + let printer = self.create_printer(); + printer.print(&self.document) } pub fn print_with_indent(&self, indent: u16) -> PrintResult { + let printer = self.create_printer(); + printer.print_with_indent(&self.document, indent) + } + + fn create_printer(&self) -> Printer { let source_code = self.context.source_code(); let print_options = self.context.options().as_print_options(); - let printed = - Printer::new(source_code, print_options).print_with_indent(&self.document, indent)?; - Ok(printed) + Printer::new(source_code, print_options) } } diff --git a/crates/ruff_formatter/src/printer/mod.rs b/crates/ruff_formatter/src/printer/mod.rs index b518ce76fe548..f65eb6fdf3791 100644 --- a/crates/ruff_formatter/src/printer/mod.rs +++ b/crates/ruff_formatter/src/printer/mod.rs @@ -40,7 +40,7 @@ impl<'a> Printer<'a> { Self { source_code, options, - state: PrinterState::default(), + state: PrinterState::with_capacity(source_code.as_str().len()), } } @@ -757,6 +757,15 @@ struct PrinterState<'a> { fits_queue: Vec<&'a [FormatElement]>, } +impl<'a> PrinterState<'a> { + fn with_capacity(capacity: usize) -> Self { + Self { + buffer: String::with_capacity(capacity), + ..Self::default() + } + } +} + /// Tracks the mode in which groups with ids are printed. Stores the groups at `group.id()` index. /// This is based on the assumption that the group ids for a single document are dense. #[derive(Debug, Default)]