Compare commits

...

2 Commits

Author SHA1 Message Date
mmetc d1ead6cc65
Merge ed83029a8b into 8552bcf7c2 2025-06-18 15:32:55 -04:00
marco ed83029a8b slices.Chunk: tolerate n=0 (no panic) if the slice is empty 2025-05-27 13:29:53 +02:00
2 changed files with 20 additions and 3 deletions

View File

@ -93,9 +93,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")
}

View File

@ -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)
}
}
}