use super::*;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Seg {
pub start: usize,
pub line: u32,
pub col_base: u32,
}
pub(crate) struct Line<'a> {
pub text: &'a str,
pub no: u32,
cols: Option<Cow<'a, [u32]>>,
segs: Cow<'a, [Seg]>,
pub single: bool,
}
fn char_cols(text: &str) -> Option<Vec<u32>> {
if text.is_ascii() {
None
} else {
let mut v = Vec::with_capacity(text.len() + 1);
let mut n = 0u32;
for c in text.chars() {
for _ in 0..c.len_utf8() {
v.push(n);
}
n = n.saturating_add(1);
}
v.push(n);
Some(v)
}
}
impl<'a> Line<'a> {
pub fn new(text: &'a str, no: u32) -> Self {
Self {
text,
no,
cols: char_cols(text).map(Cow::Owned),
segs: Cow::Borrowed(&[]),
single: false,
}
}
pub fn joined(text: &'a str, no: u32, segs: Vec<Seg>) -> Self {
Self {
text,
no,
cols: char_cols(text).map(Cow::Owned),
segs: Cow::Owned(segs),
single: false,
}
}
pub fn truncated(&self, end: usize) -> Line<'_> {
Line {
text: &self.text[..end],
no: self.no,
cols: self.cols.as_deref().map(Cow::Borrowed),
segs: Cow::Borrowed(&self.segs),
single: true,
}
}
pub fn segments(&self) -> Vec<Seg> {
if self.segs.is_empty() {
vec![Seg {
start: 0,
line: self.no,
col_base: 0,
}]
} else {
self.segs.to_vec()
}
}
fn char_index(&self, byte: usize) -> u32 {
match &self.cols {
None => byte as u32,
Some(v) => v[byte],
}
}
pub fn pos(&self, byte: usize) -> Pos {
if self.segs.is_empty() {
return Pos {
line: self.no,
col: self.char_index(byte).saturating_add(1),
};
}
let idx = self.segs.partition_point(|s| s.start <= byte).max(1) - 1;
let seg = self.segs[idx];
let col = self
.char_index(byte)
.saturating_sub(self.char_index(seg.start))
.saturating_add(seg.col_base);
Pos {
line: seg.line,
col: col.saturating_add(1),
}
}
}