Skip to content

Commit ed83029

Browse files
committed
slices.Chunk: tolerate n=0 (no panic) if the slice is empty
1 parent 3fd729b commit ed83029

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/slices/iter.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,9 @@ func SortedStableFunc[E any](seq iter.Seq[E], cmp func(E, E) int) []E {
8888
// All but the last sub-slice will have size n.
8989
// All sub-slices are clipped to have no capacity beyond the length.
9090
// If s is empty, the sequence is empty: there is no empty slice in the sequence.
91-
// Chunk panics if n is less than 1.
91+
// Chunk panics if n is less than 1, unless n=0 and s is empty which is tolerated.
9292
func Chunk[Slice ~[]E, E any](s Slice, n int) iter.Seq[Slice] {
93-
if n < 1 {
93+
if n < 1 && (len(s) > 0 || n < 0) {
9494
panic("cannot be less than 1")
9595
}
9696

src/slices/iter_test.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,16 +259,33 @@ func TestChunkPanics(t *testing.T) {
259259
name string
260260
x []struct{}
261261
n int
262+
p bool
262263
}{
263264
{
264265
name: "cannot be less than 1",
266+
x: make([]struct{}, 1),
267+
n: 0,
268+
p: true,
269+
},
270+
{
271+
name: "don't panic on an empty slice",
265272
x: make([]struct{}, 0),
266273
n: 0,
274+
p: false,
275+
},
276+
{
277+
name: "cannot be less than 0 on an empty slice",
278+
x: make([]struct{}, 0),
279+
n: -1,
280+
p: true,
267281
},
268282
} {
269-
if !panics(func() { _ = Chunk(test.x, test.n) }) {
283+
if test.p && !panics(func() { _ = Chunk(test.x, test.n) }) {
270284
t.Errorf("Chunk %s: got no panic, want panic", test.name)
271285
}
286+
if !test.p && panics(func() { _ = Chunk(test.x, test.n) }) {
287+
t.Errorf("Chunk %s: got panic, want no panic", test.name)
288+
}
272289
}
273290
}
274291

0 commit comments

Comments
 (0)