Class: Int32

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

Overview

simulate 32 bit integer with overflow

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(val) ⇒ Int32

Returns a new instance of Int32.



6
7
8
9
10
11
12
# File 'lib/sign/int32.rb', line 6

def initialize(val)
  self.val = if val.is_a?(Int32)
               val.val
             else
               val
             end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object (private)



59
60
61
62
# File 'lib/sign/int32.rb', line 59

def method_missing(meth, *args, &block)
  return super unless respond_to_missing?(meth)
  Int32.new(self.class.force_overflow_signed(val.send(meth, *args, &block)))
end

Instance Attribute Details

#valObject

Returns the value of attribute val.



5
6
7
# File 'lib/sign/int32.rb', line 5

def val
  @val
end

Class Method Details

.force_overflow_signed(i) ⇒ Object



22
23
24
# File 'lib/sign/int32.rb', line 22

def self.force_overflow_signed(i)
  force_overflow_unsigned(i + 2**31) - 2**31
end

.force_overflow_unsigned(i) ⇒ Object



26
27
28
# File 'lib/sign/int32.rb', line 26

def self.force_overflow_unsigned(i)
  i % 2**32 # or equivalently: i & 0xffffffff
end

Instance Method Details

#==(other) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/sign/int32.rb', line 14

def ==(other)
  to_i == if other.is_a?(Int32)
            other.to_i
          else
            other
          end
end

#dupObject



39
40
41
# File 'lib/sign/int32.rb', line 39

def dup
  Int32.new(val)
end

#r_shift_pos(other) ⇒ Object



30
31
32
33
# File 'lib/sign/int32.rb', line 30

def r_shift_pos(other)
  other_val = other.is_a?(Int32) ? other.val : other
  Int32.new(self.class.force_overflow_unsigned(val) >> other_val)
end

#to_iObject



35
36
37
# File 'lib/sign/int32.rb', line 35

def to_i
  self.class.force_overflow_signed(val)
end