#[derive(Debug, Clone)]
pub struct LineIndex {
starts: Vec<usize>,
line_units: Vec<usize>,
len: usize,
units: Vec<usize>,
ascii: Vec<bool>,
}
const UNITS_STRIDE: usize = 64;
fn utf16_units(byte: u8) -> usize {
usize::from(byte & 0xC0 != 0x80) + usize::from(byte >= 0xF0)
}
impl LineIndex {
pub fn new(src: &str) -> Self {
let mut starts = vec![0usize];
let mut line_units = vec![0usize];
let mut units = Vec::with_capacity(src.len() / UNITS_STRIDE + 2);
let mut ascii = Vec::with_capacity(src.len() / UNITS_STRIDE + 1);
let mut total = 0;
for (i, &b) in src.as_bytes().iter().enumerate() {
if i % UNITS_STRIDE == 0 {
units.push(total);
ascii.push(true);
}
if !b.is_ascii()
&& let Some(block) = ascii.last_mut()
{
*block = false;
}
total += utf16_units(b);
if b == b'\n' {
starts.push(i + 1);
line_units.push(total);
}
}
units.push(total);
Self {
starts,
line_units,
len: src.len(),
units,
ascii,
}
}
fn units_before(&self, bytes: &[u8], at: usize) -> usize {
let block = at / UNITS_STRIDE;
let from = block * UNITS_STRIDE;
let counted = if self.ascii.get(block).copied().unwrap_or(true) {
at - from
} else {
bytes[from..at].iter().map(|&b| utf16_units(b)).sum()
};
self.units[block] + counted
}
pub fn line_col(&self, src: &str, offset: usize) -> (usize, usize) {
let offset = offset.min(self.len);
let line = match self.starts.binary_search(&offset) {
Ok(i) => i,
Err(i) => i - 1,
};
let start = self.starts[line];
let col = if src.len() != self.len {
src.get(start..offset)
.map(|s| s.chars().map(char::len_utf16).sum())
.unwrap_or(0)
} else if src.is_char_boundary(offset) {
self.units_before(src.as_bytes(), offset) - self.line_units[line]
} else {
0
};
(line + 1, col)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_col_counts_lines_from_one() {
let src = "alpha\nbeta\ngamma";
let idx = LineIndex::new(src);
assert_eq!(idx.line_col(src, 0), (1, 0));
assert_eq!(idx.line_col(src, 6), (2, 0));
assert_eq!(idx.line_col(src, 8), (2, 2));
assert_eq!(idx.line_col(src, 11), (3, 0));
}
#[test]
fn line_col_counts_utf16_units_not_bytes() {
let src = "é𝄞x";
let idx = LineIndex::new(src);
assert_eq!(idx.line_col(src, 0), (1, 0));
assert_eq!(idx.line_col(src, 2), (1, 1)); assert_eq!(idx.line_col(src, 6), (1, 3)); }
fn line_col_by_counting(src: &str, offset: usize) -> (usize, usize) {
let offset = offset.min(src.len());
let start = src.as_bytes()[..offset]
.iter()
.rposition(|&b| b == b'\n')
.map_or(0, |i| i + 1);
let line = src.as_bytes()[..start]
.iter()
.filter(|&&b| b == b'\n')
.count();
let col = src
.get(start..offset)
.map(|s| s.chars().map(char::len_utf16).sum())
.unwrap_or(0);
(line + 1, col)
}
#[test]
fn line_col_is_what_counting_from_the_line_start_gives() {
let mut texts = vec![String::new(), "\n".into(), "\n\n".into(), "a".into()];
let pieces = ["a", "é", "€", "𝄞", "\n", "\r\n", " ", "{% x /%}"];
let mut state: u64 = 0x2545_F491_4F6C_DD1D;
for len in [10, 63, 64, 65, 200, 1000] {
let mut s = String::new();
for _ in 0..len {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
s.push_str(pieces[(state % pieces.len() as u64) as usize]);
}
texts.push(s);
}
texts.push("𝄞".repeat(100));
texts.push(format!("{}\n{}", "é".repeat(70), "x".repeat(130)));
texts.push(format!(
"{}é{}𝄞{}",
"x".repeat(63),
"x".repeat(62),
"x".repeat(70)
));
for src in &texts {
let idx = LineIndex::new(src);
for offset in 0..=src.len() + 2 {
assert_eq!(
idx.line_col(src, offset),
line_col_by_counting(src, offset),
"offset {offset} of {src:?}"
);
}
}
}
#[test]
fn line_col_of_another_text_counts_it() {
let idx = LineIndex::new("ab\ncd");
assert_eq!(idx.line_col("éé\nxyz", 2), (1, 1));
assert_eq!(idx.line_col("é", 1), (1, 0));
}
#[test]
fn line_col_on_one_long_line_is_not_quadratic() {
let src = "a {% x /%}".repeat(40_000) + "é";
let idx = LineIndex::new(&src);
let started = std::time::Instant::now();
let mut sum = 0;
for offset in (0..src.len()).step_by(5) {
sum += idx.line_col(&src, offset).1;
}
assert!(sum > 0);
assert!(
started.elapsed() < std::time::Duration::from_secs(2),
"{:?}",
started.elapsed()
);
}
}