Skip to content

Commit b0d678c

Browse files
authored
Merge pull request #1160 from iex-rs/efficient-position
Optimize position search in error path
2 parents 40dd7f5 + b1edc7d commit b0d678c

File tree

2 files changed

+9
-13
lines changed

2 files changed

+9
-13
lines changed

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ rust-version = "1.56"
1414
[dependencies]
1515
indexmap = { version = "2.2.3", optional = true }
1616
itoa = "1.0"
17+
memchr = { version = "2", default-features = false }
1718
ryu = "1.0"
1819
serde = { version = "1.0.194", default-features = false }
1920

@@ -45,7 +46,7 @@ features = ["raw_value"]
4546
[features]
4647
default = ["std"]
4748

48-
std = ["serde/std"]
49+
std = ["memchr/std", "serde/std"]
4950

5051
# Provide integration for heap-allocated collections without depending on the
5152
# rest of the Rust standard library.

src/read.rs

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -415,19 +415,14 @@ impl<'a> SliceRead<'a> {
415415
}
416416

417417
fn position_of_index(&self, i: usize) -> Position {
418-
let mut position = Position { line: 1, column: 0 };
419-
for ch in &self.slice[..i] {
420-
match *ch {
421-
b'\n' => {
422-
position.line += 1;
423-
position.column = 0;
424-
}
425-
_ => {
426-
position.column += 1;
427-
}
428-
}
418+
let start_of_line = match memchr::memrchr(b'\n', &self.slice[..i]) {
419+
Some(position) => position + 1,
420+
None => 0,
421+
};
422+
Position {
423+
line: 1 + memchr::memchr_iter(b'\n', &self.slice[..start_of_line]).count(),
424+
column: i - start_of_line,
429425
}
430-
position
431426
}
432427

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

0 commit comments

Comments
 (0)