Optimize lsp_pos_to_pos (#1423)

lines().count() is slow compared to len_lines()
pull/1293/head
Kirawi 3 years ago committed by GitHub
parent 4da050b4bb
commit ea095ca5fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -66,39 +66,26 @@ pub mod util {
pos: lsp::Position, pos: lsp::Position,
offset_encoding: OffsetEncoding, offset_encoding: OffsetEncoding,
) -> Option<usize> { ) -> Option<usize> {
let max_line = doc.lines().count().saturating_sub(1);
let pos_line = pos.line as usize; let pos_line = pos.line as usize;
let pos_line = if pos_line > max_line { if pos_line > doc.len_lines() - 1 {
return None; return None;
} else { }
pos_line
};
match offset_encoding { match offset_encoding {
OffsetEncoding::Utf8 => { OffsetEncoding::Utf8 => {
let max_char = doc
.line_to_char(max_line)
.checked_add(doc.line(max_line).len_chars())?;
let line = doc.line_to_char(pos_line); let line = doc.line_to_char(pos_line);
let pos = line.checked_add(pos.character as usize)?; let pos = line.checked_add(pos.character as usize)?;
if pos <= max_char { if pos <= doc.len_chars() {
Some(pos) Some(pos)
} else { } else {
None None
} }
} }
OffsetEncoding::Utf16 => { OffsetEncoding::Utf16 => {
let max_char = doc
.line_to_char(max_line)
.checked_add(doc.line(max_line).len_chars())?;
let max_cu = doc.char_to_utf16_cu(max_char);
let line = doc.line_to_char(pos_line); let line = doc.line_to_char(pos_line);
let line_start = doc.char_to_utf16_cu(line); let line_start = doc.char_to_utf16_cu(line);
let pos = line_start.checked_add(pos.character as usize)?; let pos = line_start.checked_add(pos.character as usize)?;
if pos <= max_cu { doc.try_utf16_cu_to_char(pos).ok()
Some(doc.utf16_cu_to_char(pos))
} else {
None
}
} }
} }
} }

Loading…
Cancel
Save