diff --git a/s2/cellid.go b/s2/cellid.go index 1fb8ee12..00ad0322 100644 --- a/s2/cellid.go +++ b/s2/cellid.go @@ -268,8 +268,13 @@ func (ci CellID) VertexNeighbors(level int) []CellID { // same neighbor may be returned more than once. There could be up to eight // neighbors including the diagonal ones that share the vertex. // -// This requires level >= ci.Level(). +// Returns nil if level < ci.Level() (cells would not be neighboring) or +// level > MaxLevel (no such cells exist). func (ci CellID) AllNeighbors(level int) []CellID { + if level < ci.Level() || level > MaxLevel { + return nil + } + var neighbors []CellID face, i, j, _ := ci.faceIJOrientation() diff --git a/s2/cellid_test.go b/s2/cellid_test.go index 923b57df..4a2063b9 100644 --- a/s2/cellid_test.go +++ b/s2/cellid_test.go @@ -323,6 +323,19 @@ func TestCellIDAllNeighbors(t *testing.T) { } } +func TestCellIDAllNeighborsBadLevels(t *testing.T) { + ci := CellIDFromLatLng(LatLngFromDegrees(47.38, 8.54)).Parent(29) + if got := ci.AllNeighbors(-1); got != nil { + t.Errorf("AllNeighbors(%v) = %v, want nil", -1, got) + } + if got := ci.AllNeighbors(28); got != nil { + t.Errorf("AllNeighbors(%v) = %v, want nil", 28, got) + } + if got := ci.AllNeighbors(31); got != nil { + t.Errorf("AllNeighbors(%v) = %v, want nil", 31, got) + } +} + func TestCellIDTokensNominal(t *testing.T) { tests := []struct { token string