Class: Base::Program

Inherits:
Object
  • Object
show all
Defined in:
lib/base/program.rb

Constant Summary collapse

DecodeError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeProgram

Returns a new instance of Program.



8
9
10
11
# File 'lib/base/program.rb', line 8

def initialize
  @start_location = 0
  @memory = []
end

Instance Attribute Details

#memoryObject (readonly)

Returns the value of attribute memory.



5
6
7
# File 'lib/base/program.rb', line 5

def memory
  @memory
end

#start_locationObject

Returns the value of attribute start_location.



6
7
8
# File 'lib/base/program.rb', line 6

def start_location
  @start_location
end

Instance Method Details

#decode(data) ⇒ Object

Raises:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/base/program.rb', line 26

def decode(data)
  raise DecodeError, "invalid header signature" unless data[0..4] == "BASE\2"

  bytecode = []
  carry = 0
  value = 0
  data[5..-1].each_byte do |byte|
    if byte & 128 == 128
      value |= (byte & 127) << carry
      carry += 7
    else
      bytecode << ((byte << carry) | value)
      carry = value = 0
    end
  end

  raise DecodeError, "unexpected end of bytecode" unless carry == 0

  @start_location = bytecode[0]
  @memory = bytecode[1..-1]
  true
end

#encodeObject



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/base/program.rb', line 13

def encode
  bytecode = ['B'.ord, 'A'.ord, 'S'.ord, 'E'.ord, 2, start_location] + memory

  bytecode.flat_map do |value|
    bytes = []
    while value >= 128
      bytes << ((value & 127) | 128).chr
      value >>= 7
    end
    bytes + [value.chr]
  end.join
end