line-span
This crate features utilities for finding the start, end, and range of lines from a byte index. Further also being able to find the next and previous line, from an arbitrary byte index.
Usage
Add this to your Cargo.toml
:
[]
= "0.1"
Releases
Release notes are available in the repo at CHANGELOG.md.
Current Line:
find_line_start
to find the start of the current line.find_line_end
to find the end of the current line.find_line_range
to find the start and end current line.
Next Line:
find_next_line_start
to find the start of the next line.find_next_line_end
to find the end of the next line.find_next_line_range
to find the start and end of the next line.
Previous Line:
find_prev_line_start
to find the start of the previous line.find_prev_line_end
to find the end of the previous line.find_prev_line_range
to find both start and end of the previous line.
Utilities:
str_to_range
to get the range of a substring in a string.str_to_range_unchecked
unchecked version ofstr_to_range
.
LineSpan
and LineSpanIter
The crate includes the LineSpanIter
iterator. It is functionally equivalent to str::lines
,
with the addition that it includes the ability to get the start and end byte indices of each line.
An LineSpanIter
can be created by calling line_spans
, implemented in the LineSpans
trait. The crate implements the LineSpans
trait for str
and String
.
Note, LineSpan
implements Deref
to &str
, so in general,
swapping lines
to line_spans
would not cause many issues.
use LineSpans;
let text = "foo\nbar\r\nbaz";
for span in text.line_spans
This will output the following:
0.. 3: "foo"
4.. 7: "bar"
9..12: "baz"
Current Line, Previous Line, and Next Line
use ;
let text = "foo\nbar\r\nbaz";
// ^
let i = 5; // 'a' in "bar"
let curr_range = find_line_range;
let next_range = find_next_line_range.unwrap;
let prev_range = find_prev_line_range.unwrap;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;