Skip to main content

parsec_css/
position.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Line and column for a byte offset. Spans are byte offsets because
5//! they're free to keep; lines are counted only when you ask.
6
7/// The start of every line in a text, for turning offsets into lines and
8/// columns. CR LF, CR, LF and form feed each end a line, as CSS counts.
9///
10/// ```
11/// use parsec_css::LineIndex;
12///
13/// let css = "a {\r\n  color: réd;\n}";
14/// let lines = LineIndex::new(css);
15/// let at = css.find("réd").unwrap();
16/// assert_eq!(lines.line_column(css, at), (2, 10));
17/// assert_eq!(lines.line_column(css, css.len()), (3, 2));
18/// ```
19#[derive(Clone, Debug)]
20pub struct LineIndex {
21    starts: Vec<usize>,
22}
23
24impl LineIndex {
25    pub fn new(text: &str) -> LineIndex {
26        let b = text.as_bytes();
27        let mut starts = vec![0];
28        let mut i = 0;
29        while i < b.len() {
30            match b[i] {
31                b'\r' if b.get(i + 1) == Some(&b'\n') => {
32                    i += 1;
33                    starts.push(i + 1);
34                }
35                b'\n' | b'\r' | b'\x0c' => starts.push(i + 1),
36                _ => {}
37            }
38            i += 1;
39        }
40        LineIndex { starts }
41    }
42
43    /// The 1-based line and column of `offset` in `text`, the string this
44    /// index was made from. Columns count code points.
45    pub fn line_column(&self, text: &str, offset: usize) -> (usize, usize) {
46        let line = self.starts.partition_point(|&s| s <= offset) - 1;
47        let column = text[self.starts[line]..offset].chars().count() + 1;
48        (line + 1, column)
49    }
50}