diff --git a/src/slices/iter.go b/src/slices/iter.go index cd8f308ca08ece..43d8419a4eb32e 100644 --- a/src/slices/iter.go +++ b/src/slices/iter.go @@ -88,9 +88,9 @@ func SortedStableFunc[E any](seq iter.Seq[E], cmp func(E, E) int) []E { // All but the last sub-slice will have size n. // All sub-slices are clipped to have no capacity beyond the length. // If s is empty, the sequence is empty: there is no empty slice in the sequence. -// Chunk panics if n is less than 1. +// Chunk panics if n is less than 1, unless n=0 and s is empty which is tolerated. func Chunk[Slice ~[]E, E any](s Slice, n int) iter.Seq[Slice] { - if n < 1 { + if n < 1 && (len(s) > 0 || n < 0) { panic("cannot be less than 1") } diff --git a/src/slices/iter_test.go b/src/slices/iter_test.go index 07d73e90e2bc56..f1128254beab60 100644 --- a/src/slices/iter_test.go +++ b/src/slices/iter_test.go @@ -259,16 +259,33 @@ func TestChunkPanics(t *testing.T) { name string x []struct{} n int + p bool }{ { name: "cannot be less than 1", + x: make([]struct{}, 1), + n: 0, + p: true, + }, + { + name: "don't panic on an empty slice", x: make([]struct{}, 0), n: 0, + p: false, + }, + { + name: "cannot be less than 0 on an empty slice", + x: make([]struct{}, 0), + n: -1, + p: true, }, } { - if !panics(func() { _ = Chunk(test.x, test.n) }) { + if test.p && !panics(func() { _ = Chunk(test.x, test.n) }) { t.Errorf("Chunk %s: got no panic, want panic", test.name) } + if !test.p && panics(func() { _ = Chunk(test.x, test.n) }) { + t.Errorf("Chunk %s: got panic, want no panic", test.name) + } } }