use crate::ast::Span;
use tower_lsp::lsp_types::{Position, Range};
pub fn utf8_to_utf16_col(line_text: &str, utf8_column: u32) -> u32 {
let utf8_col = utf8_column as usize;
if utf8_col >= line_text.len() {
return line_text.chars().map(char_utf16_len).sum();
}
line_text[..utf8_col].chars().map(char_utf16_len).sum()
}
pub fn utf16_to_utf8_col(line_text: &str, utf16_column: u32) -> u32 {
let mut utf16_count = 0u32;
let mut utf8_offset = 0u32;
for ch in line_text.chars() {
if utf16_count >= utf16_column {
break;
}
utf16_count += char_utf16_len(ch);
utf8_offset += ch.len_utf8() as u32;
}
utf8_offset
}
#[inline]
fn char_utf16_len(ch: char) -> u32 {
if ch as u32 > 0xFFFF { 2 } else { 1 }
}
pub fn span_to_range(span: &Span, source: &str) -> Range {
let lines: Vec<&str> = source.lines().collect();
let start_col = if (span.start.line as usize) < lines.len() {
utf8_to_utf16_col(lines[span.start.line as usize], span.start.column)
} else {
span.start.column
};
let end_col = if (span.end.line as usize) < lines.len() {
utf8_to_utf16_col(lines[span.end.line as usize], span.end.column)
} else {
span.end.column
};
Range {
start: Position { line: span.start.line, character: start_col },
end: Position { line: span.end.line, character: end_col },
}
}
pub fn position_to_utf8_col(line_text: &str, position: &Position) -> u32 {
utf16_to_utf8_col(line_text, position.character)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ascii_conversion() {
let line = "hello world";
assert_eq!(utf8_to_utf16_col(line, 5), 5);
assert_eq!(utf16_to_utf8_col(line, 5), 5);
}
#[test]
fn test_multibyte_utf8() {
let line = "hello\u{1F600}world";
assert_eq!(utf8_to_utf16_col(line, 5), 5);
assert_eq!(utf8_to_utf16_col(line, 9), 7);
assert_eq!(utf16_to_utf8_col(line, 5), 5);
assert_eq!(utf16_to_utf8_col(line, 7), 9);
}
#[test]
fn test_bmp_characters() {
let line = "cafe\u{0301}"; assert_eq!(utf8_to_utf16_col(line, 4), 4);
assert_eq!(utf8_to_utf16_col(line, 6), 5);
}
#[test]
fn test_empty_line() {
let line = "";
assert_eq!(utf8_to_utf16_col(line, 0), 0);
assert_eq!(utf16_to_utf8_col(line, 0), 0);
}
#[test]
fn test_column_beyond_line() {
let line = "short";
assert_eq!(utf8_to_utf16_col(line, 100), 5);
}
}