Skip to content

Commit 682a320

Browse files
committed
Explicit copy from string to byte array
1 parent 4767748 commit 682a320

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

filter.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ func (f *Filter) AddByte(b []byte) bool {
7373
h1, h2 := murmur.hash(b)
7474
trunc := uint64(len(f.data))<<shift - 1
7575
member := true
76-
for i := f.lookups; i > 0; i, h1 = i-1, h1+h2 {
76+
for i := f.lookups; i > 0; i-- {
77+
h1 += h2
7778
n := h1 & trunc
7879
k, b := n>>shift, uint64(1<<uint(n&mask))
7980
if f.data[k]&b == 0 {
@@ -89,14 +90,17 @@ func (f *Filter) AddByte(b []byte) bool {
8990

9091
// Add adds s to the filter and tells if s was already a likely member.
9192
func (f *Filter) Add(s string) bool {
92-
return f.AddByte([]byte(s))
93+
b := make([]byte, len(s))
94+
copy(b, s)
95+
return f.AddByte(b)
9396
}
9497

9598
// LikelyByte tells if b is a likely member of this filter.
9699
func (f *Filter) LikelyByte(b []byte) bool {
97100
h1, h2 := murmur.hash(b)
98101
trunc := uint64(len(f.data))<<shift - 1
99-
for i := f.lookups; i > 0; i, h1 = i-1, h1+h2 {
102+
for i := f.lookups; i > 0; i-- {
103+
h1 += h2
100104
n := h1 & trunc
101105
k, b := n>>shift, uint64(1<<uint(n&mask))
102106
if f.data[k]&b == 0 {
@@ -108,7 +112,9 @@ func (f *Filter) LikelyByte(b []byte) bool {
108112

109113
// Likely tells if s is a likely member of this filter.
110114
func (f *Filter) Likely(s string) bool {
111-
return f.LikelyByte([]byte(s))
115+
b := make([]byte, len(s))
116+
copy(b, s)
117+
return f.LikelyByte(b)
112118
}
113119

114120
// Count returns an estimate of the number of unique elements added to this filter.

filter_test.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,19 @@ func BenchmarkAdd(b *testing.B) {
6262
b.StopTimer()
6363
filter := New(1<<30, 200)
6464
b.StartTimer()
65+
s := "The quick brown fox jumps over the lazy dog."
6566
for i := 0; i < b.N; i++ {
66-
filter.Add("The quick brown fox jumps over the lazy dog.")
67+
filter.Add(s)
68+
}
69+
}
70+
71+
func BenchmarkAddByte(b *testing.B) {
72+
b.StopTimer()
73+
filter := New(1<<30, 200)
74+
b.StartTimer()
75+
s := []byte("The quick brown fox jumps over the lazy dog.")
76+
for i := 0; i < b.N; i++ {
77+
filter.AddByte(s)
6778
}
6879
}
6980

@@ -75,3 +86,13 @@ func BenchmarkLikely(b *testing.B) {
7586
filter.Likely("The quick brown fox jumps over the lazy dog.")
7687
}
7788
}
89+
90+
func BenchmarkLikelyByte(b *testing.B) {
91+
b.StopTimer()
92+
filter := New(1<<30, 200)
93+
b.StartTimer()
94+
s := []byte("The quick brown fox jumps over the lazy dog.")
95+
for i := 0; i < b.N; i++ {
96+
filter.LikelyByte(s)
97+
}
98+
}

0 commit comments

Comments
 (0)