Skip to content

Commit

Permalink
Merge pull request #1160 from iex-rs/efficient-position
Browse files Browse the repository at this point in the history
Optimize position search in error path
  • Loading branch information
dtolnay authored Jul 28, 2024
2 parents 40dd7f5 + b1edc7d commit b0d678c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ rust-version = "1.56"
[dependencies]
indexmap = { version = "2.2.3", optional = true }
itoa = "1.0"
memchr = { version = "2", default-features = false }
ryu = "1.0"
serde = { version = "1.0.194", default-features = false }

Expand Down Expand Up @@ -45,7 +46,7 @@ features = ["raw_value"]
[features]
default = ["std"]

std = ["serde/std"]
std = ["memchr/std", "serde/std"]

# Provide integration for heap-allocated collections without depending on the
# rest of the Rust standard library.
Expand Down
19 changes: 7 additions & 12 deletions src/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,19 +415,14 @@ impl<'a> SliceRead<'a> {
}

fn position_of_index(&self, i: usize) -> Position {
let mut position = Position { line: 1, column: 0 };
for ch in &self.slice[..i] {
match *ch {
b'\n' => {
position.line += 1;
position.column = 0;
}
_ => {
position.column += 1;
}
}
let start_of_line = match memchr::memrchr(b'\n', &self.slice[..i]) {
Some(position) => position + 1,
None => 0,
};
Position {
line: 1 + memchr::memchr_iter(b'\n', &self.slice[..start_of_line]).count(),
column: i - start_of_line,
}
position
}

/// The big optimization here over IoRead is that if the string contains no
Expand Down

0 comments on commit b0d678c

Please sign in to comment.