Skip to content

Commit 55051eb

Browse files
authored
Add fuzz test for CellUnion (#193)
Add fuzz test and jointly fixing panic that can happen for bad input. Slice creation with n < 0 panics. Starting point for #175
1 parent fac2d31 commit 55051eb

File tree

3 files changed

+36
-9
lines changed

3 files changed

+36
-9
lines changed

s2/cellunion.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,7 @@ func (cu *CellUnion) ExactArea() float64 {
539539
}
540540

541541
// Encode encodes the CellUnion.
542+
// Note: The CellUnion is not required to be valid according to IsValid().
542543
func (cu *CellUnion) Encode(w io.Writer) error {
543544
e := &encoder{w: w}
544545
cu.encode(e)
@@ -554,6 +555,7 @@ func (cu *CellUnion) encode(e *encoder) {
554555
}
555556

556557
// Decode decodes the CellUnion.
558+
// Note: The returned CellUnion is not necessarily valid according to IsValid().
557559
func (cu *CellUnion) Decode(r io.Reader) error {
558560
d := &decoder{r: asByteReader(r)}
559561
cu.decode(d)
@@ -569,7 +571,7 @@ func (cu *CellUnion) decode(d *decoder) {
569571
d.err = fmt.Errorf("only version %d is supported", encodingVersion)
570572
return
571573
}
572-
n := d.readInt64()
574+
n := d.readUint64()
573575
if d.err != nil {
574576
return
575577
}

s2/encode.go

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,6 @@ func (d *decoder) readInt8() (x int8) {
163163
return
164164
}
165165

166-
func (d *decoder) readInt64() (x int64) {
167-
if d.err != nil {
168-
return
169-
}
170-
d.err = binary.Read(d.r, binary.LittleEndian, &x)
171-
return
172-
}
173-
174166
func (d *decoder) readUint8() (x uint8) {
175167
if d.err != nil {
176168
return

s2/encode_fuzz_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Fuzz tests for s2 decoding. Run using
2+
// go test -fuzz=Fuzz github.com/golang/geo/s2
3+
package s2
4+
5+
import (
6+
"bytes"
7+
"testing"
8+
)
9+
10+
func FuzzDecodeCellUnion(f *testing.F) {
11+
cu := CellUnion([]CellID{
12+
CellID(0x33),
13+
CellID(0x8e3748fab),
14+
CellID(0x91230abcdef83427),
15+
})
16+
buf := new(bytes.Buffer)
17+
if err := cu.Encode(buf); err != nil {
18+
f.Errorf("error encoding %v: ", err)
19+
}
20+
f.Add(buf.Bytes())
21+
22+
f.Fuzz(func(t *testing.T, encoded []byte) {
23+
var c CellUnion
24+
if err := c.Decode(bytes.NewReader(encoded)); err != nil {
25+
// Construction failed, no need to test further.
26+
return
27+
}
28+
if got := c.ApproxArea(); got < 0 {
29+
t.Errorf("ApproxArea() = %v, want >= 0. CellUnion: %v", got, c)
30+
}
31+
// TODO: Test more invariants that should hold for all CellUnion.
32+
})
33+
}

0 commit comments

Comments
 (0)