Class: RubyLabs::MARSLab::Memory

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

Overview

Memory

An object of the Memory class is a 1-D array of the specified size. Items in a Memory are Word objects.

According to the Core War standard, memory should be initialized with DAT #0 instructions before each contest. For efficiency, newly (re)initialized Memory objects have nil at each location, but nil is treated the same as DAT #0.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ Memory

Create a new Memory of the specified size.



598
599
600
# File 'lib/marslab.rb', line 598

def initialize(size)
  @array = Array.new(size)
end

Instance Attribute Details

#arrayObject (readonly)

Returns the value of attribute array.



594
595
596
# File 'lib/marslab.rb', line 594

def array
  @array
end

Instance Method Details

#dump(loc, n) ⇒ Object

Print the n words in memory starting at loc.



610
611
612
613
614
615
# File 'lib/marslab.rb', line 610

def dump(loc, n)
  (loc...(loc+n)).each do |x|
    addr = x % @array.size
    printf "%04d: %s\n", addr, self.fetch(addr) 
  end
end

#fetch(loc) ⇒ Object

Return the Word object stored in location loc in this Memory object.



625
626
627
# File 'lib/marslab.rb', line 625

def fetch(loc)
  return ( @array[loc] || Word.new("DAT", "#0", "#0", nil) )
end

#fetch_field(loc, field) ⇒ Object

Same as fetch, but return only the designated field of the Word stored at location loc.



637
638
639
640
# File 'lib/marslab.rb', line 637

def fetch_field(loc, field)
  instr = self.fetch(loc)
  return field == :a ? instr.a : instr.b
end

#sizeObject

Return the size (number of words that can be stored) of this Memory object.



619
620
621
# File 'lib/marslab.rb', line 619

def size
  return @array.size
end

#store(loc, val) ⇒ Object

Store object val in location loc.



631
632
633
# File 'lib/marslab.rb', line 631

def store(loc, val)
  @array[loc] = val.clone
end

#store_field(loc, val, field) ⇒ Object

Same as store, but overwrite only the designated field of the Word in location loc.



644
645
646
647
648
649
650
# File 'lib/marslab.rb', line 644

def store_field(loc, val, field)
  instr = self.fetch(loc)
  part = (field == :a) ? instr.a : instr.b
  mode = @@modes.include?(part[0]) ? part[0].chr : ""
  part.replace(mode + val.to_s)
  self.store(loc, instr)
end

#to_sObject

Create a string describing this Memory object.



604
605
606
# File 'lib/marslab.rb', line 604

def to_s
  sprintf "Memory [0..#{@array.size-1}]"
end