index-to-position
Convert a string index to a line and column position.
Turn a byte offset into a string — such as a parser or lexer error offset — into a
human-readable line:column. A Rust port of the
index-to-position npm package.
- Zero dependencies,
#![no_std] - Zero- or one-based line/column (independently configurable)
- [
PositionFinder] forO(log lines)lookups when resolving many indices into one text - Differential-tested against the reference
index-to-positionimplementation
Install
[]
= "0.1"
Usage
use ;
let text = "foo\nbar\nbaz";
// Zero-based by default:
let pos = index_to_position; // the 'a' in "bar"
assert_eq!;
// One-based, for display:
let pos = index_to_position_with;
assert_eq!;
// Resolve many indices efficiently:
let finder = new;
assert_eq!;
Indices are byte offsets
Unlike the JavaScript original (which uses UTF-16 code unit offsets), this crate works with
byte offsets — the idiomatic Rust string index, as produced by str slicing and most
parsers. Lines and columns are counted in bytes. For ASCII text the two are identical; only
\n is treated as a line break (a \r is an ordinary column character, matching the
reference).
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of MIT or Apache-2.0 at your option.