Skip to content

Add hamming distance calculation to bloom filters #1085

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Godeps/Godeps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions blocks/bloom/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import (
"errors"
// Non crypto hash, because speed
"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/mtchavez/jenkins"
"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/steakknife/hamming"
"hash"
)

type Filter interface {
Add([]byte)
Find([]byte) bool
Merge(Filter) (Filter, error)
HammingDistance(Filter) (int, error)
}

func NewFilter(size int) Filter {
Expand Down Expand Up @@ -100,3 +102,23 @@ func (f *filter) Merge(o Filter) (Filter, error) {

return nfilt, nil
}

func (f *filter) HammingDistance(o Filter) (int, error) {
casfil, ok := o.(*filter)
if !ok {
return 0, errors.New("Unsupported filter type")
}

if len(f.filter) != len(casfil.filter) {
return 0, errors.New("filter lengths must match!")
}

acc := 0

// xor together
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whats being xor'ed?

for i := 0; i < len(f.filter); i++ {
acc += hamming.Byte(f.filter[i], casfil.filter[i])
}

return acc, nil
}
14 changes: 14 additions & 0 deletions blocks/bloom/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,17 @@ func TestMerge(t *testing.T) {
}
}
}

func TestHamming(t *testing.T) {
f1 := NewFilter(128)
f2 := NewFilter(128)

f1.Add([]byte("no collision"))
f1.Add([]byte("collision? no!"))

dist, _ := f1.HammingDistance(f2)

if dist != 6 {
t.Fatal("Should have 6 bit difference")
}
}