Skip to content

slices: tolerate Chunk([]string{}, 0) without raising panic for n<1 #73880

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/slices/iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down
19 changes: 18 additions & 1 deletion src/slices/iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down