Skip to content

Commit e872f50

Browse files
committed
Auto merge of rust-lang#16217 - hurryabit:simplify-apply-change, r=lnicola
internal: Simplify implementation of apply_document_changes While reading through the code base, I stumbled across a piece of code that I found hard to read despite its simple purpose. This is my attempt at making the code easier to understand for future readers. I won't be offended if this is too minor and not worth your time.
2 parents e1e4626 + b9933fd commit e872f50

File tree

1 file changed

+12
-23
lines changed

1 file changed

+12
-23
lines changed

crates/rust-analyzer/src/lsp/utils.rs

+12-23
Original file line numberDiff line numberDiff line change
@@ -171,30 +171,19 @@ pub(crate) fn apply_document_changes(
171171
file_contents: impl FnOnce() -> String,
172172
mut content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
173173
) -> String {
174-
// Skip to the last full document change, as it invalidates all previous changes anyways.
175-
let mut start = content_changes
176-
.iter()
177-
.rev()
178-
.position(|change| change.range.is_none())
179-
.map(|idx| content_changes.len() - idx - 1)
180-
.unwrap_or(0);
181-
182-
let mut text: String = match content_changes.get_mut(start) {
183-
// peek at the first content change as an optimization
184-
Some(lsp_types::TextDocumentContentChangeEvent { range: None, text, .. }) => {
185-
let text = mem::take(text);
186-
start += 1;
187-
188-
// The only change is a full document update
189-
if start == content_changes.len() {
190-
return text;
174+
// If at least one of the changes is a full document change, use the last
175+
// of them as the starting point and ignore all previous changes.
176+
let (mut text, content_changes) =
177+
match content_changes.iter().rposition(|change| change.range.is_none()) {
178+
Some(idx) => {
179+
let text = mem::take(&mut content_changes[idx].text);
180+
(text, &content_changes[idx + 1..])
191181
}
192-
text
193-
}
194-
Some(_) => file_contents(),
195-
// we received no content changes
196-
None => return file_contents(),
197-
};
182+
None => (file_contents(), &content_changes[..]),
183+
};
184+
if content_changes.is_empty() {
185+
return text;
186+
}
198187

199188
let mut line_index = LineIndex {
200189
// the index will be overwritten in the bottom loop's first iteration

0 commit comments

Comments
 (0)