diff --git a/Cargo.lock b/Cargo.lock index 80a4e28d..be8829ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -469,9 +469,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.5.0" +version = "2.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" [[package]] name = "minimal-lexical" @@ -941,6 +941,7 @@ dependencies = [ "indoc", "lazy_static", "log", + "memchr", "path-slash", "pretty_assertions", "rand", diff --git a/cli/Cargo.toml b/cli/Cargo.toml index 0edd3c3d..e62c443a 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -32,6 +32,7 @@ glob = "0.3.1" html-escape = "0.2.13" indexmap = "2.0.0" lazy_static = "1.4.0" +memchr = "2.6.3" path-slash = "0.2.1" regex = "1.9.1" regex-syntax = "0.7.4" diff --git a/cli/src/parse.rs b/cli/src/parse.rs index 5b1a4b31..30ddd238 100644 --- a/cli/src/parse.rs +++ b/cli/src/parse.rs @@ -370,31 +370,35 @@ fn parse_edit_flag(source_code: &Vec, flag: &str) -> Result { }) } -fn offset_for_position(input: &Vec, position: Point) -> usize { - let mut current_position = Point { row: 0, column: 0 }; - for (i, c) in input.iter().enumerate() { - if *c as char == '\n' { - current_position.row += 1; - current_position.column = 0; - } else { - current_position.column += 1; - } - if current_position > position { - return i; +fn offset_for_position(input: &[u8], position: Point) -> usize { + let mut row = 0; + let mut offset = 0; + let mut iter = memchr::memchr_iter(b'\n', input); + loop { + if let Some(pos) = iter.next() { + if row < position.row { + row += 1; + offset = pos; + continue; + } } + offset += 1; + break; } - return input.len(); + offset + position.column } -fn position_for_offset(input: &Vec, offset: usize) -> Point { +fn position_for_offset(input: &[u8], offset: usize) -> Point { let mut result = Point { row: 0, column: 0 }; - for c in &input[0..offset] { - if *c as char == '\n' { - result.row += 1; - result.column = 0; - } else { - result.column += 1; - } + let mut last = 0; + for pos in memchr::memchr_iter(b'\n', &input[..offset]) { + result.row += 1; + last = pos; } + result.column = if result.row > 0 { + offset - last - 1 + } else { + offset + }; result }