Skip to content
Browse files

Native filter returns the number of bits set to 1.

  • Loading branch information...
1 parent 6ab061e commit 942c15b35ac1cb1dd1774bd57039a0434edc94d6 @apohllo apohllo committed Mar 7, 2012
Showing with 29 additions and 1 deletion.
  1. +13 −0 ext/cbloomfilter/cbloomfilter.c
  2. +5 −0 lib/bloomfilter/native.rb
  3. +11 −1 spec/native_spec.rb
View
13 ext/cbloomfilter/cbloomfilter.c
@@ -176,6 +176,18 @@ static VALUE bf_num_set(VALUE self) {
return INT2FIX(bf->num_set);
}
+static VALUE bf_num_bit(VALUE self){
+ struct BloomFilter *bf;
+ int i,j,count = 0;
+ Data_Get_Struct(self, struct BloomFilter, bf);
+ for (i = 0; i < bf->bytes; i++) {
+ for (j = 0; j < 8; j++) {
+ count += (bf->ptr[i] >> j) & 1;
+ }
+ }
+ return INT2FIX(count);
+}
+
static VALUE bf_insert(VALUE self, VALUE key) {
VALUE skey;
int index, seed;
@@ -341,6 +353,7 @@ void Init_cbloomfilter(void) {
rb_define_method(cBloomFilter, "b", bf_b, 0);
rb_define_method(cBloomFilter, "r", bf_r, 0);
rb_define_method(cBloomFilter, "num_set", bf_num_set, 0);
+ rb_define_method(cBloomFilter, "num_bit", bf_num_bit, 0);
rb_define_method(cBloomFilter, "insert", bf_insert, 1);
rb_define_method(cBloomFilter, "delete", bf_delete, 1);
rb_define_method(cBloomFilter, "include?", bf_include, -1);
View
5 lib/bloomfilter/native.rb
@@ -36,6 +36,11 @@ def clear; @bf.clear; end
def size; @bf.num_set; end
def merge!(o); @bf.merge!(o.bf); end
+ # Returns the number of bits that are set to 1 in the filter.
+ def bits_count
+ @bf.num_bit
+ end
+
def bitmap
@bf.bitmap
end
View
12 spec/native_spec.rb
@@ -42,6 +42,16 @@
bf.include?("abcd").should be_false
bf.include?("test", "test1", '12345').should be_true
end
+
+ it "should return the number of bits set to 1" do
+ bf = Native.new(:hashes => 4)
+ bf.insert("test")
+ bf.bits_count.should == 4
+
+ bf = Native.new(:hashes => 1)
+ bf.insert("test")
+ bf.bits_count.should == 1
+ end
end
context "behave like counting bloom filter" do
@@ -76,4 +86,4 @@
bf.include?('baz').should be_false
end
end
-end
+end

0 comments on commit 942c15b

Please sign in to comment.
Something went wrong with that request. Please try again.