From 2d6e3481851903d6415206b8212b7ed571cfc618 Mon Sep 17 00:00:00 2001 From: Antonio Scandurra Date: Sat, 29 Jan 2022 09:52:38 +0100 Subject: [PATCH] Prevent anchors from escaping their excerpt's range when resolving them This could happen if an anchor was created on an excerpt with a larger range. Then, if the excerpt was removed and added back at the same position and with the same buffer but a smaller range, resolving the anchor could overshoot the excerpt's boundaries. --- crates/editor/src/multi_buffer.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/editor/src/multi_buffer.rs b/crates/editor/src/multi_buffer.rs index 4cedfa80d2703f3987bf92aac080db2d98733f48..17d7019a8ddd84121e936ca1bf8d9073ade62579 100644 --- a/crates/editor/src/multi_buffer.rs +++ b/crates/editor/src/multi_buffer.rs @@ -1366,7 +1366,11 @@ impl MultiBufferSnapshot { if let Some(excerpt) = cursor.item() { if excerpt.id == anchor.excerpt_id && excerpt.buffer_id == anchor.buffer_id { let excerpt_buffer_start = excerpt.range.start.summary::(&excerpt.buffer); - let buffer_position = anchor.text_anchor.summary::(&excerpt.buffer); + let excerpt_buffer_end = excerpt.range.end.summary::(&excerpt.buffer); + let buffer_position = cmp::min( + excerpt_buffer_end, + anchor.text_anchor.summary::(&excerpt.buffer), + ); if buffer_position > excerpt_buffer_start { position.add_assign(&(buffer_position - excerpt_buffer_start)); } @@ -1404,11 +1408,13 @@ impl MultiBufferSnapshot { if let Some(excerpt) = cursor.item() { if excerpt.id == *excerpt_id && excerpt.buffer_id == buffer_id { let excerpt_buffer_start = excerpt.range.start.summary::(&excerpt.buffer); + let excerpt_buffer_end = excerpt.range.end.summary::(&excerpt.buffer); summaries.extend( excerpt .buffer .summaries_for_anchors::(excerpt_anchors) .map(move |summary| { + let summary = cmp::min(excerpt_buffer_end.clone(), summary); let mut position = position.clone(); let excerpt_buffer_start = excerpt_buffer_start.clone(); if summary > excerpt_buffer_start { @@ -3048,6 +3054,7 @@ mod tests { .iter() .zip(snapshot.summaries_for_anchors::(&anchors)) { + assert!(resolved_offset <= snapshot.len()); assert_eq!( snapshot.summary_for_anchor::(anchor), resolved_offset