diff --git a/port.rb b/port.rb index cc533f4..5581300 100644 --- a/port.rb +++ b/port.rb @@ -7,12 +7,22 @@ class Port # @return [Integer] the current value of the port attr_reader :val + # @!attribute [r] width + # @return [Integer] the width of the port + attr_reader :width + # Returns a new instance of Port - # @param name [String] The string name of the port - def initialize(name="") + # @overload set(width) + # @param width [Integer] The width of the port + # @overload set(width, name) + # @param width [Integer] The width of the port + # @param name [String] The name of the port + def initialize(width, name="") @connected=[] @propagating=false @val=0 + @width=width + @maxval = (2**@width)-1 @strname=name end @@ -22,7 +32,11 @@ class Port def setval(val) # Prevent infinite loops when the connected port calls back when propagating. if !@propagating - @val=val + if val<=@maxval + @val=val + else + raise ArgumentError,"#{val} is over maximum of #{@maxval}" + end @propagating=true propagate() @propagating=false @@ -74,10 +88,3 @@ class Port end end - -a=Port.new("a") -b=Port.new("b") -c=Port.new("c") -a.connect(b) -b.connect(c) -a.setval(10) diff --git a/spec/port_spec.rb b/spec/port_spec.rb index 24a96f6..35789ea 100644 --- a/spec/port_spec.rb +++ b/spec/port_spec.rb @@ -2,15 +2,16 @@ require_relative "../port.rb" describe Port do it "should set the port's value when we call setval" do - a=Port.new + a=Port.new(4) a.setval(1) expect(a).to eq 1 end + it "should propagate values when we call setval" do - a=Port.new - b=Port.new - c=Port.new - d=Port.new + a=Port.new(4) + b=Port.new(4) + c=Port.new(4) + d=Port.new(4) #connect A-B and C-D a.connect(b) @@ -36,4 +37,9 @@ describe Port do expect(c).to eq 4 expect(d).to eq 4 end + + it "should not allow value to go over max allowed by width" do + a=Port.new(4) + expect {a.setval(16)}.to raise_error ArgumentError + end end