Skip to content

Commit a63082e

Browse files
nes1983dsymonds
authored andcommitted
s2: Fix panic when round-tripping empty loop.
Signed-off-by: David Symonds <[email protected]>
1 parent bc9a478 commit a63082e

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

s2/encode_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,34 @@ func TestLoopEncodeDecode(t *testing.T) {
309309
}
310310
}
311311

312+
func TestLoopEncodeDecodeFuzzed(t *testing.T) {
313+
for i := 3; i < 100; i++ {
314+
var pts []Point
315+
for j := 0; j < i; j++ {
316+
pts = append(pts, randomPoint())
317+
}
318+
loop := LoopFromPoints(pts)
319+
if err := loop.Validate(); err != nil {
320+
t.Fatalf("loop(%v).Validate: %v", loop, err)
321+
}
322+
polygon := PolygonFromLoops([]*Loop{loop})
323+
var buf bytes.Buffer
324+
if err := polygon.Encode(&buf); err != nil {
325+
t.Fatal(err)
326+
}
327+
got := new(Loop)
328+
if err := got.Decode(&buf); err != nil {
329+
// TODO(nsch): Uncomment the next line as soon as decoding of all encoded loops works.
330+
// t.Fatalf("decode(encode(%v)): %v", loop, err)
331+
continue
332+
}
333+
334+
if !reflect.DeepEqual(got, polygon) {
335+
t.Errorf("decode(encode()) = %v, want %v", got, polygon)
336+
}
337+
}
338+
}
339+
312340
func BenchmarkRectDecode(b *testing.B) {
313341
rect := RectFromCenterSize(LatLngFromDegrees(80, 170), LatLngFromDegrees(40, 60))
314342
var buf bytes.Buffer

s2/loop.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,10 @@ func (l *Loop) initOriginAndBound() {
167167

168168
// initBound sets up the approximate bounding Rects for this loop.
169169
func (l *Loop) initBound() {
170+
if len(l.vertices) == 0 {
171+
*l = *EmptyLoop()
172+
return
173+
}
170174
// Check for the special "empty" and "full" loops.
171175
if l.isEmptyOrFull() {
172176
if l.IsEmpty() {

0 commit comments

Comments
 (0)