index-to-position 0.1.0

Convert a string byte index to a line and column position. A Rust port of the index-to-position npm package. Zero dependencies, no_std.
Documentation
  • Coverage
  • 100%
    15 out of 15 items documented3 out of 13 items with examples
  • Size
  • Source code size: 29.28 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 328.9 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 3s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/index-to-position
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

index-to-position

All Contributors

crates.io docs.rs CI license

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] for O(log lines) lookups when resolving many indices into one text
  • Differential-tested against the reference index-to-position implementation

Install

[dependencies]
index-to-position = "0.1"

Usage

use index_to_position::{index_to_position, index_to_position_with, Options, PositionFinder};

let text = "foo\nbar\nbaz";

// Zero-based by default:
let pos = index_to_position(text, 5); // the 'a' in "bar"
assert_eq!((pos.line, pos.column), (1, 1));

// One-based, for display:
let pos = index_to_position_with(text, 5, Options::new().one_based(true));
assert_eq!((pos.line, pos.column), (2, 2));

// Resolve many indices efficiently:
let finder = PositionFinder::new(text);
assert_eq!(finder.position(9).line, 2);

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.