Compare commits

...

2 Commits

Author SHA1 Message Date
c749131351 add bloom marshal function 2023-04-18 18:24:06 +08:00
418b9c4045 update 2023-04-18 18:15:04 +08:00

View File

@ -1,10 +1,14 @@
package bloom package bloom
import ( import (
"encoding/binary"
"io"
"math" "math"
"unsafe"
"github.com/spaolacci/murmur3" "github.com/spaolacci/murmur3"
"github.com/tursom/GoCollections/exceptions"
"github.com/tursom/GoCollections/lang" "github.com/tursom/GoCollections/lang"
) )
@ -70,7 +74,7 @@ func (b *Bloom) M() uint {
func (b *Bloom) Contains(data []byte) bool { func (b *Bloom) Contains(data []byte) bool {
for i := 0; i < int(b.k); i++ { for i := 0; i < int(b.k); i++ {
hashCode := uint(HashFunc(data, uint32(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 return false
} }
} }
@ -85,3 +89,29 @@ func (b *Bloom) Add(data []byte) {
b.m.SetBit(hashCode%b.m.BitLength(), true) 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),
}
}