use rhai::{InputStream, Position};
pub struct StrStream<'a> {
src: &'a str,
cursor: usize,
}
impl<'a> StrStream<'a> {
pub fn new(src: &'a str) -> Self {
Self { src, cursor: 0 }
}
pub fn byte_offset(&self) -> usize {
self.cursor
}
pub fn src(&self) -> &'a str {
self.src
}
fn remainder(&self) -> &'a str {
&self.src[self.cursor..]
}
}
impl InputStream for StrStream<'_> {
fn unget(&mut self, ch: char) {
let width = ch.len_utf8();
debug_assert!(
self.src[..self.cursor].ends_with(ch),
"unget({ch:?}) does not match the character before the cursor at {}",
self.cursor
);
self.cursor -= width;
}
fn get_next(&mut self) -> Option<char> {
let ch = self.remainder().chars().next()?;
self.cursor += ch.len_utf8();
Some(ch)
}
fn peek_next(&mut self) -> Option<char> {
self.remainder().chars().next()
}
}
pub struct LineIndex {
starts: Vec<usize>,
}
impl LineIndex {
pub fn new(src: &str) -> Self {
let mut starts = vec![0];
starts.extend(src.match_indices('\n').map(|(i, _)| i + 1));
Self { starts }
}
pub fn line_start(&self, line: usize) -> Option<usize> {
line.checked_sub(1)
.and_then(|i| self.starts.get(i))
.copied()
}
pub fn utf16_col(&self, text: &str, line: u32, char_col: u32) -> u32 {
let Some(start) = self.line_start(line as usize + 1) else {
return char_col;
};
text[start..]
.chars()
.take_while(|&c| c != '\n')
.take(char_col as usize)
.map(|c| c.len_utf16() as u32)
.sum()
}
pub fn char_col(&self, text: &str, line: u32, utf16_col: u32) -> u32 {
let Some(start) = self.line_start(line as usize + 1) else {
return utf16_col;
};
let mut remaining = utf16_col;
let mut chars = 0;
for ch in text[start..].chars().take_while(|&c| c != '\n') {
let width = ch.len_utf16() as u32;
if remaining < width {
break;
}
remaining -= width;
chars += 1;
}
chars
}
pub fn line_col_of(&self, src: &str, offset: usize) -> (u32, u32) {
let line = self.starts.partition_point(|&start| start <= offset) - 1;
let col = src[self.starts[line]..offset].chars().count();
(line as u32, col as u32)
}
pub fn byte_offset_of(&self, src: &str, pos: Position) -> Option<usize> {
let (line, col) = (pos.line()?, pos.position()?);
let start = self.line_start(line)?;
let line_text = &src[start..];
let mut offset = start;
for ch in line_text.chars().take(col - 1) {
if ch == '\n' {
return None;
}
offset += ch.len_utf8();
}
Some(offset)
}
}