pub struct LineColLookup<'source> { /* private fields */ }
Expand description
Pre-cached line/column lookup table for a string slice.
Implementations§
Source§impl<'source> LineColLookup<'source>
impl<'source> LineColLookup<'source>
Sourcepub fn new(src: &'source str) -> Self
pub fn new(src: &'source str) -> Self
Creates a new line/col lookup table. The src
parameter provides the input string used to calculate lines and columns.
Internally, this scans src
and caches the starting positions of all lines. This means this is an O(n) operation.
Sourcepub fn get(&self, index: usize) -> (usize, usize)
pub fn get(&self, index: usize) -> (usize, usize)
Looks up the 1-based line and column numbers of the specified byte index.
Returns a tuple with the line number first, then column number.
§Example
use line_col::*;
let text = "One\nTwo";
let lookup = LineColLookup::new(text);
assert_eq!(lookup.get(0), (1, 1)); // 'O' (line 1, col 1)
assert_eq!(lookup.get(1), (1, 2)); // 'n' (line 1, col 2)
assert_eq!(lookup.get(2), (1, 3)); // 'e' (line 1, col 3)
assert_eq!(lookup.get(4), (2, 1)); // 'T' (line 2, col 1)
assert_eq!(lookup.get(5), (2, 2)); // 'w' (line 2, col 2)
assert_eq!(lookup.get(6), (2, 3)); // 'o' (line 2, col 3)
assert_eq!(lookup.get(7), (2, 4)); // <end> (line 2, col 4)
§Panics
Panics if index
is greater than the length of the input &str
.
§Notes
This function uses a binary search to locate the line on which index
resides.
This means that it runs in approximately O(log n) time.
Sourcepub fn get_by_cluster(&self, index: usize) -> (usize, usize)
pub fn get_by_cluster(&self, index: usize) -> (usize, usize)
Looks up the 1-based line and column numbers of the specified byte index. The column number correlates to the number of grapheme clusters up to and at the specified index.
Returns a tuple with the line number first, then column number.
§Panics
Panics if index
is greater than the length of the input &str
.
§Notes
This function uses a binary search to locate the line on which index
resides.
This means that it runs in approximately O(log n) time.