Sha256: 0498637f4eb1fe8fea8dfc463e9615e4aa989c384f48741e8a617ddcf195c809

Contents?: true

Size: 1.28 KB

Versions: 9

Compression:

Stored size: 1.28 KB

Contents

class JsonBloomfilter
  class BitArray
    attr_reader :size
    attr_reader :field
    include Enumerable

    ELEMENT_WIDTH = 32

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

    def add position
      self[position] = 1
    end

    def remove position
      self[position] = 0
    end

    # Set a bit (1/0)
    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

    # Read a bit (1/0)
    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

    # Iterate over each bit
    def each(&block)
      @size.times { |position| yield self.get(position) }
    end

    # Returns the field as a string like "0101010100111100," etc.
    def to_s
      inject("") { |a, b| a + b.to_s }
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
json-bloomfilter-0.1.5 lib/json-bloomfilter/bitarray.rb
json-bloomfilter-0.1.4 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.1.3 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.1.2 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.1.1 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.1.0 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.0.6 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.0.5 lib/json/bloomfilter/bitarray.rb
json-bloomfilter-0.0.4 lib/json/bloomfilter/bitarray.rb