Skip to content

Commit

Permalink
Printer: Reserve buffer upfront (#6550)
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser authored Aug 14, 2023
1 parent 9584f61 commit 910dbbd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
16 changes: 8 additions & 8 deletions crates/ruff_formatter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,20 +319,20 @@ where
Context: FormatContext,
{
pub fn print(&self) -> PrintResult<Printed> {
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<Printed> {
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)
}
}

Expand Down
11 changes: 10 additions & 1 deletion crates/ruff_formatter/src/printer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl<'a> Printer<'a> {
Self {
source_code,
options,
state: PrinterState::default(),
state: PrinterState::with_capacity(source_code.as_str().len()),
}
}

Expand Down Expand Up @@ -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)]
Expand Down

0 comments on commit 910dbbd

Please sign in to comment.