Class: Moon::RleProgram

Inherits:
Object show all
Defined in:
lib/moon/packages/data_bags/rle.rb

Overview

RunLengthEncoded Program

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRleProgram

Returns a new instance of RleProgram.


6
7
8
9
10
11
12
13
# File 'lib/moon/packages/data_bags/rle.rb', line 6

def initialize
  @instructions = []
  @poll = nil
  if block_given?
    yield self
    flush
  end
end

Instance Attribute Details

#instructionsObject (readonly)

Returns the value of attribute instructions


4
5
6
# File 'lib/moon/packages/data_bags/rle.rb', line 4

def instructions
  @instructions
end

Instance Method Details

#clearObject

Clear all existing instructions and reset the poll


16
17
18
19
# File 'lib/moon/packages/data_bags/rle.rb', line 16

def clear
  @instructions = []
  @poll = nil
end

#encode(data) ⇒ Object


39
40
41
42
43
44
45
# File 'lib/moon/packages/data_bags/rle.rb', line 39

def encode(data)
  clear
  data.each do |d|
    yield d ? put(d) : skip
  end
  flush
end

#flushObject


32
33
34
35
36
37
# File 'lib/moon/packages/data_bags/rle.rb', line 32

def flush
  if @poll
    @instructions << @poll
    @poll = nil
  end
end

#put(d) ⇒ Object


22
23
24
25
# File 'lib/moon/packages/data_bags/rle.rb', line 22

def put(d)
  flush
  @instructions << [:put, d]
end

#runObject


47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/moon/packages/data_bags/rle.rb', line 47

def run
  i = 0
  @instructions.each do |inst|
    op, value = *inst
    case op
    when :skip
      i += value
    when :put
      yield value, i
      i += 1
    end
  end
end

#skipObject


27
28
29
30
# File 'lib/moon/packages/data_bags/rle.rb', line 27

def skip
  @poll ||= [:skip, 0]
  @poll[1] += 1
end