Class: Expressir::Express::LineMap

Inherits:
Object
  • Object
show all
Defined in:
lib/expressir/express/line_map.rb

Overview

Maps byte positions in a source string to 1-based line numbers.

Single source of truth for byte→line lookup across the remark pipeline (RemarkScanner and RemarkAttacher both rely on it). Builds an offset table once and answers queries in O(log n) via binary search.

Constant Summary collapse

NEWLINE =

Newline byte (ASCII 0x0A).

"\n"

Instance Method Summary collapse

Constructor Details

#initialize(source_bytes) ⇒ LineMap

Returns a new instance of LineMap.

Parameters:

  • source_bytes (String)

    BINARY / ASCII-8BIT encoded source.



15
16
17
# File 'lib/expressir/express/line_map.rb', line 15

def initialize(source_bytes)
  @offsets = build_offsets(source_bytes)
end

Instance Method Details

#line_number(byte_pos) ⇒ Integer

Returns the 1-based line number that contains the given byte position. Returns 1 for position 0 (or any position before the first newline). Returns the last line number for positions past the final newline.

Parameters:

  • byte_pos (Integer, nil)

Returns:

  • (Integer)

    1-based line number; nil input yields 1.



25
26
27
28
29
30
# File 'lib/expressir/express/line_map.rb', line 25

def line_number(byte_pos)
  return 1 if byte_pos.nil? || byte_pos <= 0

  idx = @offsets.bsearch_index { |offset| offset > byte_pos }
  idx || @offsets.size
end