Class: XRB::Location

Inherits:
Object
  • Object
show all
Defined in:
lib/xrb/error.rb

Overview

A byte offset resolved to a line within an input string.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, offset) ⇒ Location

Initialize a location for a byte offset within an input string.

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/xrb/error.rb', line 48

def initialize(input, offset)
  raise ArgumentError.new("Offset #{index} is past end of input #{input.bytesize}") if offset > input.bytesize
  
  @offset = offset
  @line_index = 0
  line_offset = next_line_offset = 0
  
  input.each_line do |line|
    line_offset = next_line_offset
    next_line_offset += line.bytesize
    
    # Is our input offset within this line?
    if next_line_offset >= offset
      @line_text = line.chomp
      @line_range = line_offset...next_line_offset
      break
    else
      @line_index += 1
    end
  end
end

Instance Attribute Details

#line_indexObject (readonly)

The line that contains the @offset (base 0 indexing).



83
84
85
# File 'lib/xrb/error.rb', line 83

def line_index
  @line_index
end

#line_rangeObject (readonly)

The byte offset to the start of that line.



91
92
93
# File 'lib/xrb/error.rb', line 91

def line_range
  @line_range
end

#line_textObject (readonly)

Returns the value of attribute line_text.



98
99
100
# File 'lib/xrb/error.rb', line 98

def line_text
  @line_text
end

Instance Method Details

#line_numberObject

The line index, but base-1.



86
87
88
# File 'lib/xrb/error.rb', line 86

def line_number
  @line_index + 1
end

#line_offsetObject

The number of bytes from the start of the line to the given offset in the input.



94
95
96
# File 'lib/xrb/error.rb', line 94

def line_offset
  @offset - @line_range.min
end

#to_iObject

Convert the location to its absolute byte offset.



72
73
74
# File 'lib/xrb/error.rb', line 72

def to_i
  @offset
end

#to_sObject

Format the location as a one-based line number and zero-based line offset.



78
79
80
# File 'lib/xrb/error.rb', line 78

def to_s
  "[#{self.line_number}:#{self.line_offset}]"
end