Skip to content

Commit

Permalink
Throw error on garbage byte array (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
OldPanda authored Apr 30, 2021
1 parent 77f9905 commit f20bed9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
14 changes: 12 additions & 2 deletions bloomfilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,13 @@ func FromBytes(b []byte) (*BloomFilter, error) {
// read strategy
strategyByte, err := reader.ReadByte()
if err != nil {
return nil, errors.New("Failed to read strategy")
return nil, fmt.Errorf("Failed to read strategy: %v", err)
}
strategy := strategyList[int(strategyByte)]
strategyIndex := int(strategyByte)
if strategyIndex >= len(strategyList) {
return nil, fmt.Errorf("Unknown strategy byte: %v", strategyByte)
}
strategy := strategyList[strategyIndex]

// read number of hash functions
numHashFuncByte, err := reader.ReadByte()
Expand All @@ -80,6 +84,9 @@ func FromBytes(b []byte) (*BloomFilter, error) {
if err != nil {
return nil, fmt.Errorf("Failed to read number of bits: %v", err)
}
if len(numUint64Bytes) != 4 {
return nil, fmt.Errorf("Not a valid uint32 bytes: %v", numUint64Bytes)
}
numUint64 := binary.BigEndian.Uint32(numUint64Bytes)
array := bitarray.NewBitArray(uint64(numUint64) * 64)

Expand All @@ -89,6 +96,9 @@ func FromBytes(b []byte) (*BloomFilter, error) {
if err != nil {
return nil, fmt.Errorf("Failed to build bitarray: %v", err)
}
if len(block) != 8 {
return nil, fmt.Errorf("Not a valid uint64 bytes: %v", block)
}
num := binary.BigEndian.Uint64(block)
var pos uint64 = 1 << 63
var index uint64
Expand Down
16 changes: 16 additions & 0 deletions bloomfilter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,22 @@ func TestJavaCompatibility(t *testing.T) {
}
}

func TestGarbageByteArray(t *testing.T) {
garbageBytes := [][]byte{
[]byte("this-is-a-line-of-garbage"),
{0},
{0, 1},
{0, 1, 2},
{0, 1, 2, 3, 4, 5},
}
for _, bytes := range garbageBytes {
_, err := FromBytes(bytes)
if err == nil {
t.Errorf("Expected error on garbage byte array: %v", bytes)
}
}
}

func TestBloomFilterInvalidParams(t *testing.T) {
// too small error rate
_, err := NewBloomFilter(500, 0.0)
Expand Down

0 comments on commit f20bed9

Please sign in to comment.