magic_string/position_index

UTF-8 byte offset -> (line, UTF-16 column) conversion.

Source Map v3 columns count UTF-16 code units, not bytes, so for any non-ASCII source a byte offset is not a column. Build a PositionIndex once with new, then lookup each offset. Line and column are 0-based.

Types

A 0-based (line, column) position. column is a count of UTF-16 code units from the start of the line, per the Source Map v3 spec.

pub type Position {
  Position(line: Int, column: Int)
}

Constructors

  • Position(line: Int, column: Int)

Precomputed line index for one source. line_starts holds the byte offset of the first byte of each line (ascending, always starting with 0). source and byte_len are kept so columns can be measured in UTF-16 units over a byte range without re-encoding the whole file.

pub opaque type PositionIndex

Values

pub fn line_count(index: PositionIndex) -> Int

Number of lines in the indexed source (always at least 1).

pub fn lookup(index: PositionIndex, byte_offset: Int) -> Position

Convert a byte offset into a 0-based (line, UTF-16 column) position. Offsets are clamped into [0, byte_len], so an end-exclusive span boundary at end-of-file resolves to the position just past the last byte.

pub fn new(source: String) -> PositionIndex

Build a PositionIndex for source. A line begins at byte 0 and after each \n (0x0A) byte; a \r\n sequence is split by its \n, so the carriage return is the last byte of the preceding line. Scanning for the 0x0A byte is UTF-8 safe because 0x0A never appears inside a multibyte sequence.

Search Document