Skip to content

Commit

Permalink
perf(sourcemap): improve perf of search_original_line_and_column
Browse files Browse the repository at this point in the history
  • Loading branch information
camc314 committed Dec 15, 2024
1 parent 02b653c commit c123b76
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions crates/oxc_codegen/src/sourcemap_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ pub struct SourcemapBuilder {
sourcemap_builder: oxc_sourcemap::SourceMapBuilder,
generated_line: u32,
generated_column: u32,
last_line_lookup: usize,
}

impl SourcemapBuilder {
Expand All @@ -88,6 +89,7 @@ impl SourcemapBuilder {
sourcemap_builder,
generated_line: 0,
generated_column: 0,
last_line_lookup: 0,
}
}

Expand Down Expand Up @@ -131,12 +133,29 @@ impl SourcemapBuilder {

#[allow(clippy::cast_possible_truncation)]
fn search_original_line_and_column(&mut self, position: u32) -> (u32, u32) {
let result = self
.line_offset_tables
.lines
.partition_point(|table| table.byte_offset_to_start_of_line <= position);
let original_line = if result > 0 { result - 1 } else { 0 };
let line = &self.line_offset_tables.lines[original_line];
let lines = &self.line_offset_tables.lines;
let mut idx = self.last_line_lookup;

// Ensure we have a valid starting point
// If position < lines[idx].byte_offset_to_start_of_line, fallback to a full binary search.
if position < lines[idx].byte_offset_to_start_of_line {
#[cold]
fn fallback_binary_search(lines: &[Line], position: u32) -> usize {
let mut i =
lines.partition_point(|line| line.byte_offset_to_start_of_line <= position);
i = i.saturating_sub(1);
i
}
idx = fallback_binary_search(lines, position);
} else {
while idx + 1 < lines.len() && lines[idx + 1].byte_offset_to_start_of_line <= position {
idx += 1;
}
}

self.last_line_lookup = idx;

let line = &lines[idx];
let mut original_column = position - line.byte_offset_to_start_of_line;
if let Some(column_offsets_id) = line.column_offsets_id {
let column_offsets = &self.line_offset_tables.column_offsets[column_offsets_id];
Expand All @@ -145,7 +164,7 @@ impl SourcemapBuilder {
[(original_column - column_offsets.byte_offset_to_first) as usize];
}
}
(original_line as u32, original_column)
(idx as u32, original_column)
}

#[allow(clippy::cast_possible_truncation)]
Expand Down

0 comments on commit c123b76

Please sign in to comment.