class StringScanner
attr_reader :pos
def initialize(string, _dup = false)
@string = string.to_s
@pos = 0
@match = nil
@prev = 0
end
def string
@string
end
def string=(str)
@string = str.to_s
reset
str
end
def pos=(n)
n += @string.length if n < 0
@pos = n.clamp(0, @string.length)
end
alias pointer pos
alias pointer= pos=
def reset
@pos = 0
@match = nil
self
end
def terminate
@pos = @string.length
@match = nil
self
end
alias clear terminate
def eos?
@pos >= @string.length
end
def rest
@string[@pos..] || ""
end
def rest_size
rest.length
end
alias rest_length rest_size
def matched
@match && @match[0]
end
def matched?
!@match.nil?
end
def matched_size
@match ? @match[0].length : nil
end
def pre_match
@match ? @string[0, @prev] : nil
end
def post_match
@match ? @string[@pos..] : nil
end
def [](n)
@match && @match[n]
end
def scan(pattern)
do_scan(pattern, true, true)
end
def skip(pattern)
m = do_scan(pattern, true, true)
m&.length
end
def check(pattern)
do_scan(pattern, false, true)
end
def match?(pattern)
m = do_scan(pattern, false, true)
m&.length
end
def scan_until(pattern)
do_scan(pattern, true, false)
end
def check_until(pattern)
do_scan(pattern, false, false)
end
def getch
return nil if eos?
ch = @string[@pos]
@prev = @pos
@pos += 1
@match = [ch]
ch
end
def peek(len)
@string[@pos, len] || ""
end
alias peep peek
def unscan
raise "unscan failed: previous match record not exist" if @match.nil?
@pos = @prev
@match = nil
self
end
def beginning_of_line?
@pos == 0 || @string[@pos - 1] == "\n"
end
alias bol? beginning_of_line?
def inspect
"#<StringScanner #{eos? ? "fin" : "#{@pos}/#{@string.length}"}>"
end
private
def do_scan(pattern, advance, anchored)
pattern = Regexp.new(Regexp.escape(pattern)) if pattern.is_a?(String)
target = @string[@pos..] || ""
m = pattern.match(target)
return nil if m.nil?
pre = m.pre_match
return nil if anchored && !pre.empty?
consumed_to = pre.length + m[0].length
result = anchored ? m[0] : target[0, consumed_to]
@prev = @pos
@match = m
@pos += consumed_to if advance
result
end
end
class StringScanner
class Error < StandardError; end
end