Skip to content

Commit 97e19c1

Browse files
authored
CellID.AllNeighbors: Return nil for invalid level (golang#146)
Return nil if level is too low (cells are too large and might not be neighbors) or higher than MaxLevel (no such cells exist). Weakens precondition of function. golang#104 complained that AllNeighbors was returning the wrong results, but the level precondition was being violated. Make this more obvious and less confusing.
1 parent 9ff7231 commit 97e19c1

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

s2/cellid.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -268,8 +268,13 @@ func (ci CellID) VertexNeighbors(level int) []CellID {
268268
// same neighbor may be returned more than once. There could be up to eight
269269
// neighbors including the diagonal ones that share the vertex.
270270
//
271-
// This requires level >= ci.Level().
271+
// Returns nil if level < ci.Level() (cells would not be neighboring) or
272+
// level > MaxLevel (no such cells exist).
272273
func (ci CellID) AllNeighbors(level int) []CellID {
274+
if level < ci.Level() || level > MaxLevel {
275+
return nil
276+
}
277+
273278
var neighbors []CellID
274279

275280
face, i, j, _ := ci.faceIJOrientation()

s2/cellid_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,19 @@ func TestCellIDAllNeighbors(t *testing.T) {
323323
}
324324
}
325325

326+
func TestCellIDAllNeighborsBadLevels(t *testing.T) {
327+
ci := CellIDFromLatLng(LatLngFromDegrees(47.38, 8.54)).Parent(29)
328+
if got := ci.AllNeighbors(-1); got != nil {
329+
t.Errorf("AllNeighbors(%v) = %v, want nil", -1, got)
330+
}
331+
if got := ci.AllNeighbors(28); got != nil {
332+
t.Errorf("AllNeighbors(%v) = %v, want nil", 28, got)
333+
}
334+
if got := ci.AllNeighbors(31); got != nil {
335+
t.Errorf("AllNeighbors(%v) = %v, want nil", 31, got)
336+
}
337+
}
338+
326339
func TestCellIDTokensNominal(t *testing.T) {
327340
tests := []struct {
328341
token string

0 commit comments

Comments
 (0)