use std::str::Chars;
use ruff_text_size::{TextLen, TextSize};
pub const EOF_CHAR: char = '\0';
#[derive(Debug, Clone)]
pub struct Cursor<'a> {
chars: Chars<'a>,
source_length: TextSize,
}
impl<'a> Cursor<'a> {
pub fn new(source: &'a str) -> Self {
Self {
source_length: source.text_len(),
chars: source.chars(),
}
}
pub fn offset(&self) -> TextSize {
self.source_length - self.text_len()
}
pub fn chars(&self) -> Chars<'a> {
self.chars.clone()
}
pub fn as_bytes(&self) -> &'a [u8] {
self.as_str().as_bytes()
}
pub fn as_str(&self) -> &'a str {
self.chars.as_str()
}
pub fn first(&self) -> char {
self.chars.clone().next().unwrap_or(EOF_CHAR)
}
pub fn second(&self) -> char {
let mut chars = self.chars.clone();
chars.next();
chars.next().unwrap_or(EOF_CHAR)
}
pub fn last(&self) -> char {
self.chars.clone().next_back().unwrap_or(EOF_CHAR)
}
pub fn text_len(&self) -> TextSize {
self.chars.as_str().text_len()
}
pub fn token_len(&self) -> TextSize {
self.source_length - self.text_len()
}
pub fn start_token(&mut self) {
self.source_length = self.text_len();
}
pub fn is_eof(&self) -> bool {
self.chars.as_str().is_empty()
}
pub fn bump(&mut self) -> Option<char> {
self.chars.next()
}
pub fn bump_back(&mut self) -> Option<char> {
self.chars.next_back()
}
pub fn eat_char(&mut self, c: char) -> bool {
if self.first() == c {
self.bump();
true
} else {
false
}
}
pub fn eat_char2(&mut self, c1: char, c2: char) -> bool {
let mut chars = self.chars.clone();
if chars.next() == Some(c1) && chars.next() == Some(c2) {
self.bump();
self.bump();
true
} else {
false
}
}
pub fn eat_char3(&mut self, c1: char, c2: char, c3: char) -> bool {
let mut chars = self.chars.clone();
if chars.next() == Some(c1) && chars.next() == Some(c2) && chars.next() == Some(c3) {
self.bump();
self.bump();
self.bump();
true
} else {
false
}
}
pub fn eat_char_back(&mut self, c: char) -> bool {
if self.last() == c {
self.bump_back();
true
} else {
false
}
}
pub fn eat_if(&mut self, mut predicate: impl FnMut(char) -> bool) -> bool {
if predicate(self.first()) && !self.is_eof() {
self.bump();
true
} else {
false
}
}
pub fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
while predicate(self.first()) && !self.is_eof() {
self.bump();
}
}
pub fn eat_back_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
while predicate(self.last()) && !self.is_eof() {
self.bump_back();
}
}
pub fn skip_bytes(&mut self, count: usize) {
self.chars = self.chars.as_str()[count..].chars();
}
}