#text #streaming #line #lines #line-end

no-std line-span

Find line ranges and jump between next and previous lines

4 releases

0.1.3 Aug 25, 2021
0.1.2 Feb 21, 2020
0.1.1 Feb 16, 2020
0.1.0 Feb 10, 2020

#352 in Text processing

Download history 168/week @ 2022-11-27 168/week @ 2022-12-04 160/week @ 2022-12-11 163/week @ 2022-12-18 178/week @ 2022-12-25 211/week @ 2023-01-01 283/week @ 2023-01-08 183/week @ 2023-01-15 302/week @ 2023-01-22 335/week @ 2023-01-29 252/week @ 2023-02-05 221/week @ 2023-02-12 539/week @ 2023-02-19 331/week @ 2023-02-26 336/week @ 2023-03-05 250/week @ 2023-03-12

1,477 downloads per month
Used in 13 crates (3 directly)

MIT license

297 lines


Build Status Build Status Latest Version Docs License

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.


Add this to your Cargo.toml:

line-span = "0.1"


Release notes are available in the repo at CHANGELOG.md.

Current Line:

Next Line:

Previous Line:


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. Additionally, it also includes the ability to get the end including and excluding the line ending (\n or \r\n).

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 line_span::LineSpans;

let text = "foo\nbar\r\nbaz";

for span in text.line_spans() {
        "{:>2?}: {:?} {:?}",

This will output the following:

0.. 3: "foo" "foo\n"
4.. 7: "bar" "bar\r\n"
9..12: "baz" "baz"

Current Line, Previous Line, and Next Line

use line_span::{find_line_range, find_next_line_range, find_prev_line_range};

let text = "foo\nbar\r\nbaz";
//                ^
let i = 5; // 'a' in "bar"

let curr_range = find_line_range(text, i);
let next_range = find_next_line_range(text, i).unwrap();
let prev_range = find_prev_line_range(text, i).unwrap();

assert_eq!(curr_range, 4..7);
assert_eq!(&text[curr_range], "bar");

assert_eq!(prev_range, 0..3);
assert_eq!(&text[prev_range], "foo");

assert_eq!(next_range, 9..12);
assert_eq!(&text[next_range], "baz");

Range of Substring in String

Use str_to_range (or str_to_range_unchecked) to get the range of a substring in a string.

let string1 = "Foo Bar Baz";
let string2 = "Hello World";

let substring = &string1[4..7]; // "Bar"

// Returns `Some` as `substring` is a part of `string1`
assert_eq!(str_to_range(string1, substring), Some(4..7));

// Returns `None` as `substring` is not a part of `string2`
assert_eq!(str_to_range(string2, substring), None);

No runtime deps


  • alloc