Skip to content

Commit

Permalink
Merge pull request #89 from omerfirmak/master
Browse files Browse the repository at this point in the history
Implement binary.BinaryMarshaler/binary.BinaryUnmarshaler interfaces
lemire authored May 2, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
2 parents a7ec2b7 + db6d979 commit d6783e6
Showing 2 changed files with 57 additions and 0 deletions.
19 changes: 19 additions & 0 deletions bloom.go
Original file line number Diff line number Diff line change
@@ -399,6 +399,25 @@ func (f *BloomFilter) GobDecode(data []byte) error {
return err
}

// MarshalBinary implements binary.BinaryMarshaler interface.
func (f *BloomFilter) MarshalBinary() ([]byte, error) {
var buf bytes.Buffer
_, err := f.WriteTo(&buf)
if err != nil {
return nil, err
}

return buf.Bytes(), nil
}

// UnmarshalBinary implements binary.BinaryUnmarshaler interface.
func (f *BloomFilter) UnmarshalBinary(data []byte) error {
buf := bytes.NewBuffer(data)
_, err := f.ReadFrom(buf)

return err
}

// Equal tests for the equality of two Bloom filters
func (f *BloomFilter) Equal(g *BloomFilter) bool {
return f.m == g.m && f.k == g.k && f.b.Equal(g.b)
38 changes: 38 additions & 0 deletions bloom_test.go
Original file line number Diff line number Diff line change
@@ -646,3 +646,41 @@ func TestFPP(t *testing.T) {
t.Errorf("Excessive fpp")
}
}

func TestEncodeDecodeBinary(t *testing.T) {
f := New(1000, 4)
f.Add([]byte("one"))
f.Add([]byte("two"))
f.Add([]byte("three"))
data, err := f.MarshalBinary()
if err != nil {
t.Fatal(err.Error())
}

var g BloomFilter
err = g.UnmarshalBinary(data)
if err != nil {
t.Fatal(err.Error())
}
if g.m != f.m {
t.Error("invalid m value")
}
if g.k != f.k {
t.Error("invalid k value")
}
if g.b == nil {
t.Fatal("bitset is nil")
}
if !g.b.Equal(f.b) {
t.Error("bitsets are not equal")
}
if !g.Test([]byte("three")) {
t.Errorf("missing value 'three'")
}
if !g.Test([]byte("two")) {
t.Errorf("missing value 'two'")
}
if !g.Test([]byte("one")) {
t.Errorf("missing value 'one'")
}
}

0 comments on commit d6783e6

Please sign in to comment.