Skip to content

Add fuzz test for CellUnion #193

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion s2/cellunion.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,7 @@ func (cu *CellUnion) ExactArea() float64 {
}

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

// Decode decodes the CellUnion.
// Note: The returned CellUnion is not necessarily valid according to IsValid().
func (cu *CellUnion) Decode(r io.Reader) error {
d := &decoder{r: asByteReader(r)}
cu.decode(d)
Expand All @@ -569,7 +571,7 @@ func (cu *CellUnion) decode(d *decoder) {
d.err = fmt.Errorf("only version %d is supported", encodingVersion)
return
}
n := d.readInt64()
n := d.readUint64()
if d.err != nil {
return
}
Expand Down
8 changes: 0 additions & 8 deletions s2/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,6 @@ func (d *decoder) readInt8() (x int8) {
return
}

func (d *decoder) readInt64() (x int64) {
if d.err != nil {
return
}
d.err = binary.Read(d.r, binary.LittleEndian, &x)
return
}

func (d *decoder) readUint8() (x uint8) {
if d.err != nil {
return
Expand Down
33 changes: 33 additions & 0 deletions s2/encode_fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Fuzz tests for s2 decoding. Run using
// go test -fuzz=Fuzz github.com/golang/geo/s2
package s2

import (
"bytes"
"testing"
)

func FuzzDecodeCellUnion(f *testing.F) {
cu := CellUnion([]CellID{
CellID(0x33),
CellID(0x8e3748fab),
CellID(0x91230abcdef83427),
})
buf := new(bytes.Buffer)
if err := cu.Encode(buf); err != nil {
f.Errorf("error encoding %v: ", err)
}
f.Add(buf.Bytes())

f.Fuzz(func(t *testing.T, encoded []byte) {
var c CellUnion
if err := c.Decode(bytes.NewReader(encoded)); err != nil {
// Construction failed, no need to test further.
return
}
if got := c.ApproxArea(); got < 0 {
t.Errorf("ApproxArea() = %v, want >= 0. CellUnion: %v", got, c)
}
// TODO: Test more invariants that should hold for all CellUnion.
})
}