github.com/iotexproject/iotex-core@v1.14.1-rc1/blockindex/bloom_range.go (about) 1 package blockindex 2 3 import ( 4 "github.com/iotexproject/go-pkgs/bloom" 5 "github.com/iotexproject/go-pkgs/byteutil" 6 "github.com/pkg/errors" 7 ) 8 9 type bloomRange struct { 10 start, end uint64 11 bloom.BloomFilter 12 } 13 14 func newBloomRange(bfSize, bfNumHash uint64) (*bloomRange, error) { 15 bf, err := bloom.NewBloomFilter(bfSize, bfNumHash) 16 if err != nil { 17 return nil, err 18 } 19 return &bloomRange{ 20 BloomFilter: bf, 21 }, nil 22 } 23 24 func (br *bloomRange) Start() uint64 { 25 return br.start 26 } 27 28 func (br *bloomRange) SetStart(start uint64) { 29 br.start = start 30 } 31 32 func (br *bloomRange) End() uint64 { 33 return br.end 34 } 35 36 func (br *bloomRange) SetEnd(end uint64) { 37 br.end = end 38 } 39 40 func (br *bloomRange) Bytes() ([]byte, error) { 41 if br.end < br.start { 42 return nil, errors.New("end should be larger than start") 43 } 44 45 b := br.BloomFilter.Bytes() 46 b = append(b, byteutil.Uint64ToBytesBigEndian(br.start)...) 47 b = append(b, byteutil.Uint64ToBytesBigEndian(br.end)...) 48 return b, nil 49 } 50 51 func (br *bloomRange) FromBytes(data []byte) error { 52 if br.BloomFilter == nil { 53 return errors.New("the bloomFilter of bloomRange is nil") 54 } 55 length := len(data) 56 if length <= 16 { 57 return errors.New("not enough data") 58 } 59 60 // data = bf.Bytes() + start (8-byte) + end (8-byte) 61 if err := br.BloomFilter.FromBytes(data[:length-16]); err != nil { 62 return err 63 } 64 br.start = byteutil.BytesToUint64BigEndian(data[length-16 : length-8]) 65 br.end = byteutil.BytesToUint64BigEndian(data[length-8:]) 66 return nil 67 }