mirror of
https://github.com/tursom/GoCollections.git
synced 2024-12-27 00:20:43 +08:00
Compare commits
2 Commits
9e06ed4b5e
...
c749131351
Author | SHA1 | Date | |
---|---|---|---|
c749131351 | |||
418b9c4045 |
@ -1,10 +1,14 @@
|
||||
package bloom
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"unsafe"
|
||||
|
||||
"github.com/spaolacci/murmur3"
|
||||
|
||||
"github.com/tursom/GoCollections/exceptions"
|
||||
"github.com/tursom/GoCollections/lang"
|
||||
)
|
||||
|
||||
@ -70,7 +74,7 @@ func (b *Bloom) M() uint {
|
||||
func (b *Bloom) Contains(data []byte) bool {
|
||||
for i := 0; i < int(b.k); i++ {
|
||||
hashCode := uint(HashFunc(data, uint32(i)))
|
||||
if !b.m.GetBit(hashCode & b.m.BitLength()) {
|
||||
if !b.m.GetBit(hashCode % b.m.BitLength()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@ -85,3 +89,29 @@ func (b *Bloom) Add(data []byte) {
|
||||
b.m.SetBit(hashCode%b.m.BitLength(), true)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bloom) Marshal(writer io.Writer) {
|
||||
if err := binary.Write(writer, binary.BigEndian, uint32(b.k)); err != nil {
|
||||
panic(exceptions.Package(err))
|
||||
}
|
||||
if err := binary.Write(writer, binary.BigEndian, uint32(b.c)); err != nil {
|
||||
panic(exceptions.Package(err))
|
||||
}
|
||||
|
||||
if _, err := writer.Write(b.m.Bytes()); err != nil {
|
||||
panic(exceptions.Package(err))
|
||||
}
|
||||
}
|
||||
|
||||
func Unmarshal(data []byte) *Bloom {
|
||||
k := binary.BigEndian.Uint32(data)
|
||||
c := binary.BigEndian.Uint32(data[4:])
|
||||
|
||||
m := data[8:]
|
||||
|
||||
return &Bloom{
|
||||
m: *(*lang.UInt8Array)(unsafe.Pointer(&m)),
|
||||
k: uint(k),
|
||||
c: uint(c),
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user