Class: Bitmask

Inherits:
Object
  • Object
show all
Defined in:
lib/bitmask.rb,
lib/bitmask/version.rb

Overview

Bitmask represents a set of boolean values as an Integer.

Examples:

masks = {
        :cat  => 0b0001,
        :dog  => 0b0010,
        :fish => 0b0100
      }

bitmask = Bitmask.new(masks, {:cat => true})
bitmask.to_i            # => 1
bitmask.get :cat        # => true
bitmask.get :dog        # => false
bitmask.set :dog, true
bitmask.get :dog        # => true
bitmask.to_i            # => 3
bitmask.to_h            # => { :cat => true, :dog => true, :fish => false }

bitmask = Bitmask.new(masks, 0b101)
bitmask.to_h            # => { :cat => true, :dog => false, :fish => true }
bitmask.to_i            # => 5
bitmask.to_i.to_s(2)    # => "101"

Bitmask.new(masks, 5) == Bitmask.new(masks, { :cat => true, :dog => false, :fish => true }) # => true

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(masks, arg) ⇒ Bitmask

create an object with which to manipulate an integer as a set of boolean values

arguments

masks

a Hash where the key is the boolean attribute and the value is the bitmask.

{ :some_attribute => 0b0001, :another_attribute => 0b0010 }
arg

can be a Hash or Integer



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/bitmask.rb', line 41

def initialize(masks, arg)
  @masks = masks
  case arg
  when Hash
    @data = 0
    arg.each do |attr, value|
      set attr, value
    end
  else
    @data = arg.to_i
  end
end

Instance Attribute Details

#masksObject (readonly)

Returns the value of attribute masks.



54
55
56
# File 'lib/bitmask.rb', line 54

def masks
  @masks
end

Instance Method Details

#==(other) ⇒ Object



31
32
33
# File 'lib/bitmask.rb', line 31

def ==(other)
  other.masks == @masks && other.to_i == self.to_i
end

#each(&blk) ⇒ Object



64
65
66
# File 'lib/bitmask.rb', line 64

def each(&blk)
  to_h.each(&blk)
end

#get(attr) ⇒ Object

returns boolean value



73
74
75
# File 'lib/bitmask.rb', line 73

def get(attr)
  (@data & @masks[attr]) == @masks[attr]
end

#set(attr, value) ⇒ Object

expects a boolean value

Raises:

  • (ArgumentError)


78
79
80
81
82
83
84
85
86
# File 'lib/bitmask.rb', line 78

def set(attr, value)
  raise ArgumentError, "unknown attribute: #{attr}" unless @masks[attr]
  case value
  when true
    @data |=  @masks[attr]
  when false
    @data &= ~@masks[attr]
  end
end

#set_array(array) ⇒ Object



88
89
90
91
92
# File 'lib/bitmask.rb', line 88

def set_array(array)
  @masks.each do |attr, value|
    set attr, array.include?(attr)
  end
end

#to_aObject



60
61
62
# File 'lib/bitmask.rb', line 60

def to_a
  @masks.keys.select { |k| get k }
end

#to_hObject



68
69
70
# File 'lib/bitmask.rb', line 68

def to_h
  @masks.keys.inject({}) { |h, k| h[k] = get k; h }
end

#to_iObject



56
57
58
# File 'lib/bitmask.rb', line 56

def to_i
  @data
end