Sha256: bff42641a66619277f6db516115d954796a8fe1c75a84f8df9aca6c33cba12a8

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

class BloomFilter
  class BitVector
    attr_reader :size
    IS_RUBY_19 = RUBY_VERSION >= '1.9'
    
    def initialize(bits, from_str = nil)
      @bytes = Array.new((bits.to_f / 8).ceil, 0)
      @size = bits
      
      if from_str
        from_str.size.times do |i|
          @bytes[i] = IS_RUBY_19 ? from_str[i].ord : from_str[i]
        end
      end
    end
    
    def [](index)
      (@bytes[index.to_i / 8] >> (index % 8)) & 0b1
    end
    
    def []=(index, value)
      new_value = value && value != 0 ? 1 : 0
      current_value = self[index]
      if current_value != new_value
        if new_value == 0
          @bytes[index.to_i / 8] -= 1 << (index % 8)
        else
          @bytes[index.to_i / 8] += 1 << (index % 8)
        end
      end
    end
    
    def to_s
      str = ""
      @bytes.each { |byte| str << byte.chr }
      str
    end
    
    def eql?(o)
      return false unless o.size == self.size
      self.size.times do |i|
        return false unless self[i] == o[i]
      end
      true
    end
    alias_method :==, :eql?
    
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
bloom_filter-0.6.6 lib/bloom_filter/bit_vector.rb
bloom_filter-0.6.5 lib/bloom_filter/bit_vector.rb
bloom_filter-0.6.4 lib/bloom_filter/bit_vector.rb
bloom_filter-0.6.3 lib/bloom_filter/bit_vector.rb