Skip to content

Commit 76e6106

Browse files
jgarzikclaude
andcommitted
vi: Optimize char_index_at_byte to single-pass iteration
Avoid iterating twice when byte_offset is past string end. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent d226a17 commit 76e6106

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

editors/vi/buffer/line.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@
55
/// Returns the index of the first character whose byte offset is >= the given byte offset,
66
/// or the total character count if byte_offset is past the end.
77
pub fn char_index_at_byte(content: &str, byte_offset: usize) -> usize {
8-
content
9-
.char_indices()
10-
.enumerate()
11-
.find(|(_, (b, _))| *b >= byte_offset)
12-
.map(|(i, _)| i)
13-
.unwrap_or_else(|| content.chars().count())
8+
let mut char_index = 0usize;
9+
for (b, _) in content.char_indices() {
10+
if b >= byte_offset {
11+
return char_index;
12+
}
13+
char_index += 1;
14+
}
15+
char_index
1416
}
1517

1618
/// A single line in the edit buffer.

0 commit comments

Comments
 (0)