Class: Base::Program
- Inherits:
-
Object
- Object
- Base::Program
- Defined in:
- lib/base/program.rb
Constant Summary collapse
- DecodeError =
Class.new(StandardError)
Instance Attribute Summary collapse
-
#memory ⇒ Object
readonly
Returns the value of attribute memory.
-
#start_location ⇒ Object
Returns the value of attribute start_location.
Instance Method Summary collapse
- #decode(data) ⇒ Object
- #encode ⇒ Object
-
#initialize ⇒ Program
constructor
A new instance of Program.
Constructor Details
#initialize ⇒ Program
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
#memory ⇒ Object (readonly)
Returns the value of attribute memory.
5 6 7 |
# File 'lib/base/program.rb', line 5 def memory @memory end |
#start_location ⇒ Object
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
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 |
#encode ⇒ Object
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 |