Class: Kaiseki::Stream

Inherits:
Object show all
Defined in:
lib/stream.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ Stream

Returns a new instance of Stream.



5
6
7
8
9
10
11
12
13
14
# File 'lib/stream.rb', line 5

def initialize string
  if string.is_a? File
    @string = string.to_a.join
  else
    @string = string.to_s
  end
  @pos = 0
  @newlines = []
  index_lines
end

Instance Attribute Details

#posObject (readonly)

Returns the value of attribute pos.



3
4
5
# File 'lib/stream.rb', line 3

def pos
  @pos
end

Instance Method Details

#columnObject



77
78
79
# File 'lib/stream.rb', line 77

def column
  @pos - @newlines[self.line][0]
end

#getcObject



16
17
18
19
20
21
22
23
# File 'lib/stream.rb', line 16

def getc
  if @pos < @string.length
    @pos += 1
    @string[@pos - 1]
  else
    nil
  end
end

#goto(pos) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/stream.rb', line 35

def goto pos
  if pos < 0
    @pos = 0
  elsif pos > @string.length
    @pos = @string.length
  end
end

#lengthObject Also known as: size



67
68
69
# File 'lib/stream.rb', line 67

def length
  @string.length
end

#lineObject



73
74
75
# File 'lib/stream.rb', line 73

def line
  bsearch @pos, 0, @newlines.length
end

#lock(&block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/stream.rb', line 43

def lock &block
  safe_pos = @pos
  begin
    catch :PredicateSuccess do
      return block.call
    end
    @pos = safe_pos
    throw :SkipSuccess
  rescue ParseError => e
    @pos = safe_pos
    e.line ||= self.line
    e.column ||= self.column
    raise e
  end
end

#match(regexp) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/stream.rb', line 25

def match regexp
  match = @string[@pos..-1].match /\A#{regexp}/
  if match
    @pos += match.to_s.length
    match
  else
    nil
  end
end

#to_sObject



59
60
61
# File 'lib/stream.rb', line 59

def to_s
  @string.dup
end

#to_streamObject



63
64
65
# File 'lib/stream.rb', line 63

def to_stream
  self
end