Convert an LSP `Position` (line, character) to a byte offset in `content`. Characters are counted as UTF-16 code units per the LSP specification. If the position is past the end of the file, the content length is returned.
(content: &str, position: Position)
| 350 | /// If the position is past the end of the file, the content length is |
| 351 | /// returned. |
| 352 | pub(crate) fn position_to_byte_offset(content: &str, position: Position) -> usize { |
| 353 | let mut line = 0u32; |
| 354 | let mut col = 0u32; |
| 355 | for (i, ch) in content.char_indices() { |
| 356 | if line == position.line && col == position.character { |
| 357 | return i; |
| 358 | } |
| 359 | if ch == '\n' { |
| 360 | if line == position.line { |
| 361 | // Position is past the end of this line — clamp to newline. |
| 362 | return i; |
| 363 | } |
| 364 | line += 1; |
| 365 | col = 0; |
| 366 | } else { |
| 367 | col += ch.len_utf16() as u32; |
| 368 | } |
| 369 | } |
| 370 | // Position at end of content. |
| 371 | content.len() |
| 372 | } |
| 373 | |
| 374 | /// Convert a UTF-16 column offset to a byte offset within a single line. |
| 375 | /// |
no outgoing calls
no test coverage detected