pub struct LineIndex { /* private fields */ }Expand description
Line starts of one source text, to turn UTF-8 byte offsets (the unit
of every crate::Span) into line/column positions in UTF-8 bytes,
chars, or UTF-16 code units.
Built once in O(n); each lookup is O(log n) (binary searches over the
line starts and the multi-byte characters), whatever the line length.
Line breaks are \n, \r\n, and a lone \r (YAML 1.2.2 §5.4). An
offset past the end, or inside a multi-byte character, has no position
(None); nothing here panics.
use oneyaml_core::{ColumnUnit, LineCol, LineIndex};
let src = "a: 1\nb: \u{e9}\u{1F600}x\n";
let idx = LineIndex::new(src);
let x = src.find('x').unwrap();
assert_eq!(idx.line_col(x, ColumnUnit::Utf8), Some(LineCol::new(1, 9)));
assert_eq!(idx.line_col(x, ColumnUnit::Char), Some(LineCol::new(1, 5)));
assert_eq!(idx.line_col(x, ColumnUnit::Utf16), Some(LineCol::new(1, 6)));
assert_eq!(idx.line_col(x - 1, ColumnUnit::Char), None); // inside the emoji
assert_eq!(idx.line_col(src.len() + 1, ColumnUnit::Char), None);
// A text ending in a line break has an empty last line.
assert_eq!(idx.line_count(), 3);
assert_eq!(idx.line_start(1), Some(5));
assert_eq!(idx.line_start(3), None);Implementations§
Source§impl LineIndex
impl LineIndex
Sourcepub fn line_count(&self) -> usize
pub fn line_count(&self) -> usize
The number of lines (a text ending in a line break has an empty last line).
Sourcepub fn line_start(&self, line: usize) -> Option<usize>
pub fn line_start(&self, line: usize) -> Option<usize>
The byte offset where 0-based line line starts.
Sourcepub fn line_col(&self, offset: usize, unit: ColumnUnit) -> Option<LineCol>
pub fn line_col(&self, offset: usize, unit: ColumnUnit) -> Option<LineCol>
The position of byte offset, its column counted in unit;
None past the end or inside a multi-byte character. O(log n).
Sourcepub fn span(&self, span: Span, unit: ColumnUnit) -> Option<(LineCol, LineCol)>
pub fn span(&self, span: Span, unit: ColumnUnit) -> Option<(LineCol, LineCol)>
The positions of a span’s start and end (see
LineIndex::line_col).