Class: BitField

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/bitfield.rb

Overview

NAME: BitField

   AUTHOR: Peter Cooper
  LICENSE: MIT ( http://www.opensource.org/licenses/mit-license.php )
COPYRIGHT: (c) 2007 Peter Cooper (http://www.petercooper.co.uk/)

Constant Summary collapse

ELEMENT_WIDTH =
32

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ BitField

Returns a new instance of BitField.



13
14
15
16
# File 'lib/bitfield.rb', line 13

def initialize(size)
  @size = size
  @field = Array.new(((size - 1) / ELEMENT_WIDTH) + 1, 0)
end

Instance Attribute Details

#fieldObject

Returns the value of attribute field.



8
9
10
# File 'lib/bitfield.rb', line 8

def field
  @field
end

#sizeObject (readonly)

Returns the value of attribute size.



7
8
9
# File 'lib/bitfield.rb', line 7

def size
  @size
end

Instance Method Details

#&(other) ⇒ Object

Returns the bitwise intersection with another BitField - pads smaller with 0s



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

def &(other)
  if self.size < other.size
    return other & self
  end

  skip =  self.size - other.size
  result = BitField.new(self.size)
  prefix = [0] * skip
  rest = (self.field[skip..-1]).zip(other.field).map do |left, right|
    left & right
  end
  result.field = prefix + rest
  return result
end

#[](position) ⇒ Object

Read a bit (1/0)



24
25
26
# File 'lib/bitfield.rb', line 24

def [](position)
  @field[position / ELEMENT_WIDTH] & 1 << (position % ELEMENT_WIDTH) > 0 ? 1 : 0
end

#[]=(position, value) ⇒ Object

Set a bit (1/0)



19
20
21
# File 'lib/bitfield.rb', line 19

def []=(position, value)
  value == 1 ? @field[position / ELEMENT_WIDTH] |= 1 << (position % ELEMENT_WIDTH) : @field[position / ELEMENT_WIDTH] ^= 1 << (position % ELEMENT_WIDTH)
end

#each(&block) ⇒ Object

Iterate over each bit



29
30
31
# File 'lib/bitfield.rb', line 29

def each(&block)
  @size.times { |position| yield self[position] }
end

#to_sObject

Returns the field as a string like “0101010100111100,” etc.



34
35
36
# File 'lib/bitfield.rb', line 34

def to_s
  inject("") { |a, b| a + b.to_s }
end

#total_setObject

Returns the total number of bits that are set (The technique used here is about 6 times faster than using each or inject direct on the bitfield)



57
58
59
# File 'lib/bitfield.rb', line 57

def total_set
  @field.inject(0) { |a, byte| a += byte & 1 and byte >>= 1 until byte == 0; a }
end