Class: JsonBloomfilter::BitArray
- Inherits:
-
Object
- Object
- JsonBloomfilter::BitArray
- Includes:
- Enumerable
- Defined in:
- lib/json-bloomfilter/bitarray.rb
Constant Summary collapse
- ELEMENT_WIDTH =
32
Instance Attribute Summary collapse
-
#field ⇒ Object
readonly
Returns the value of attribute field.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
-
#[]=(position, value) ⇒ Object
Set a bit (1/0).
- #add(position) ⇒ Object
-
#each(&block) ⇒ Object
Iterate over each bit.
-
#get(position) ⇒ Object
Read a bit (1/0).
-
#initialize(size, field = nil) ⇒ BitArray
constructor
A new instance of BitArray.
- #remove(position) ⇒ Object
-
#to_s ⇒ Object
Returns the field as a string like “0101010100111100,” etc.
Constructor Details
#initialize(size, field = nil) ⇒ BitArray
Returns a new instance of BitArray.
9 10 11 12 |
# File 'lib/json-bloomfilter/bitarray.rb', line 9 def initialize(size, field = nil) @size = size @field = field || Array.new(((size - 1) / ELEMENT_WIDTH) + 1, 0) end |
Instance Attribute Details
#field ⇒ Object (readonly)
Returns the value of attribute field.
4 5 6 |
# File 'lib/json-bloomfilter/bitarray.rb', line 4 def field @field end |
#size ⇒ Object (readonly)
Returns the value of attribute size.
3 4 5 |
# File 'lib/json-bloomfilter/bitarray.rb', line 3 def size @size end |
Instance Method Details
#[]=(position, value) ⇒ Object
Set a bit (1/0)
23 24 25 26 27 28 29 30 |
# File 'lib/json-bloomfilter/bitarray.rb', line 23 def []=(position, value) raise ArgumentError.new("Position out of bound (#{position} for max #{@size})") if position >= @size if value == 1 @field[position / ELEMENT_WIDTH] |= 1 << (position % ELEMENT_WIDTH) elsif (@field[position / ELEMENT_WIDTH]) & (1 << (position % ELEMENT_WIDTH)) != 0 @field[position / ELEMENT_WIDTH] ^= 1 << (position % ELEMENT_WIDTH) end end |
#add(position) ⇒ Object
14 15 16 |
# File 'lib/json-bloomfilter/bitarray.rb', line 14 def add position self[position] = 1 end |
#each(&block) ⇒ Object
Iterate over each bit
39 40 41 |
# File 'lib/json-bloomfilter/bitarray.rb', line 39 def each(&block) @size.times { |position| yield self.get(position) } end |
#get(position) ⇒ Object
Read a bit (1/0)
33 34 35 36 |
# File 'lib/json-bloomfilter/bitarray.rb', line 33 def get position raise ArgumentError.new("Position out of bound (#{position} for max #{@size})") if position >= @size @field[position / ELEMENT_WIDTH] & 1 << (position % ELEMENT_WIDTH) > 0 ? 1 : 0 end |
#remove(position) ⇒ Object
18 19 20 |
# File 'lib/json-bloomfilter/bitarray.rb', line 18 def remove position self[position] = 0 end |
#to_s ⇒ Object
Returns the field as a string like “0101010100111100,” etc.
44 45 46 |
# File 'lib/json-bloomfilter/bitarray.rb', line 44 def to_s inject("") { |a, b| a + b.to_s } end |