Class: Trenni::Location

Inherits:
Object
  • Object
show all
Defined in:
lib/trenni/scanner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, offset) ⇒ Location

Returns a new instance of Location.

Raises:

  • (ArgumentError)

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/trenni/scanner.rb', line 58

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).


89
90
91
# File 'lib/trenni/scanner.rb', line 89

def line_index
  @line_index
end

#line_rangeObject (readonly)

The byte offset to the start of that line.


97
98
99
# File 'lib/trenni/scanner.rb', line 97

def line_range
  @line_range
end

#line_textObject (readonly)

Returns the value of attribute line_text


104
105
106
# File 'lib/trenni/scanner.rb', line 104

def line_text
  @line_text
end

Instance Method Details

#line_numberObject

The line index, but base-1.


92
93
94
# File 'lib/trenni/scanner.rb', line 92

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.


100
101
102
# File 'lib/trenni/scanner.rb', line 100

def line_offset
	@offset - @line_range.min
end

#to_iObject


80
81
82
# File 'lib/trenni/scanner.rb', line 80

def to_i
	@offset
end

#to_sObject


84
85
86
# File 'lib/trenni/scanner.rb', line 84

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