text: Assert text anchor offset validity on construction (#38441)

Attempt to aid debugging some utf8 indexing issues

Release Notes:

- N/A

Co-authored-by: Mikayla Maki <mikayla@zed.dev>
This commit is contained in:
Lukas Wirth
2025-09-22 11:20:46 +00:00
committed by GitHub
co-authored by Mikayla Maki
parent 79620454d0
commit a2c71d3d20
5 changed files with 195 additions and 6 deletions
+21
View File
@@ -2400,6 +2400,17 @@ impl BufferSnapshot {
} else if bias == Bias::Right && offset == self.len() {
Anchor::MAX
} else {
if !self.visible_text.is_char_boundary(offset) {
// find the character
let char_start = self.visible_text.floor_char_boundary(offset);
// `char_start` must be less than len and a char boundary
let ch = self.visible_text.chars_at(char_start).next().unwrap();
let char_range = char_start..char_start + ch.len_utf8();
panic!(
"byte index {} is not a char boundary; it is inside {:?} (bytes {:?})",
offset, ch, char_range,
);
}
let mut fragment_cursor = self.fragments.cursor::<usize>(&None);
fragment_cursor.seek(&offset, bias);
let fragment = fragment_cursor.item().unwrap();
@@ -3065,6 +3076,16 @@ impl operation_queue::Operation for Operation {
pub trait ToOffset {
fn to_offset(&self, snapshot: &BufferSnapshot) -> usize;
fn to_next_offset(&self, snapshot: &BufferSnapshot) -> usize {
snapshot
.visible_text
.ceil_char_boundary(self.to_offset(snapshot) + 1)
}
fn to_previous_offset(&self, snapshot: &BufferSnapshot) -> usize {
snapshot
.visible_text
.floor_char_boundary(self.to_offset(snapshot).saturating_sub(1))
}
}
impl ToOffset for Point {