Skip to content

Commit

Permalink
optimise line_col using the bytecount crate
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshuaBatty committed Jan 8, 2024
1 parent bd06ad5 commit 98a3a4d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
1 change: 1 addition & 0 deletions sway-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ license.workspace = true
repository.workspace = true

[dependencies]
bytecount = "0.6"
fuel-asm = { workspace = true }
fuel-crypto = { workspace = true }
fuel-tx = { workspace = true }
Expand Down
19 changes: 13 additions & 6 deletions sway-types/src/span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,24 @@ impl<'a> Position<'a> {
input.get(pos..).map(|_| Position { input, pos })
}

#[inline]
pub fn line_col(&self) -> (usize, usize) {
if self.pos > self.input.len() {
panic!("position out of bounds");
}

let slice = &self.input[..self.pos];
let lines = slice.split('\n').collect::<Vec<_>>();
let line_count = lines.len();
let last_line_len = lines.last().unwrap_or(&"").chars().count() + 1;
(line_count, last_line_len)
// This is performance critical, so we use bytecount instead of a naive implementation.
let newlines_up_to_pos = bytecount::count(&self.input.as_bytes()[..self.pos], b'\n');
let line = newlines_up_to_pos + 1;

// Find the last newline character before the position
let last_newline_pos = match self.input[..self.pos].rfind('\n') {
Some(pos) => pos + 1, // Start after the newline
None => 0, // If no newline, start is at the beginning
};

// Column number should start from 1, not 0
let col = self.pos - last_newline_pos + 1;
(line, col)
}
}

Expand Down

0 comments on commit 98a3a4d

Please sign in to comment.