123456789_123456789_123456789_123456789_123456789_

Class: Prism::Translation::Ripper::LineAndColumnCache

Do not use. This class is for internal use only.
Relationships & Source Files
Inherits: Object
Defined in: lib/prism/translation/ripper.rb

Overview

Provides optimized access to line and column information. ::Prism::Translation::Ripper bounds are mostly accessed in a linear fashion, so we can try a linear scan first and fall back to binary search.

Constant Summary

Class Method Summary

Instance Method Summary

Constructor Details

.new(source) ⇒ LineAndColumnCache

: (Source source) -> void

[ GitHub ]

  
# File 'lib/prism/translation/ripper.rb', line 458

def initialize(source)
  @source = source
  @offsets = source.offsets
  @hint = 0
end

Instance Method Details

#line_and_column(byte_offset)

: (Integer byte_offset) -> [Integer, Integer]

[ GitHub ]

  
# File 'lib/prism/translation/ripper.rb', line 465

def line_and_column(byte_offset)
  @hint = new_hint(byte_offset) || @source.find_line(byte_offset)
  return [@hint + @source.start_line, byte_offset - @offsets[@hint]]
end

#new_hint(byte_offset) (private)

[ GitHub ]

  
# File 'lib/prism/translation/ripper.rb', line 472

def new_hint(byte_offset)
  if @offsets[@hint] <= byte_offset
    # Same line?
    if (@hint + 1 >= @offsets.size || @offsets[@hint + 1] > byte_offset)
      return @hint
    end

    # Scan forwards
    limit = [@hint + WINDOW + 1, @offsets.size].min
    idx = @hint + 1
    while idx < limit
      if @offsets[idx] > byte_offset
        return idx - 1
      end
      if @offsets[idx] == byte_offset
        return idx
      end
      idx += 1
    end
  else
    # Scan backwards
    limit = @hint > WINDOW ? @hint - WINDOW : 0
    idx = @hint
    while idx >= limit + 1
      if @offsets[idx - 1] <= byte_offset
        return idx - 1
      end
      idx -= 1
    end
  end

  nil
end