Skip to content
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

fix: panic when Slice() accepts a negative index #256

Merged
merged 2 commits into from Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions slice.go
Expand Up @@ -513,10 +513,16 @@ func Slice[T any](collection []T, start int, end int) []T {
if start > size {
start = size
}
if start < 0 {
start = 0
}

if end > size {
end = size
}
if end < 0 {
end = 0
}

return collection[start:end]
}
Expand Down
6 changes: 6 additions & 0 deletions slice_test.go
Expand Up @@ -623,6 +623,9 @@ func TestSlice(t *testing.T) {
out13 := Slice(in, 5, 0)
out14 := Slice(in, 6, 4)
out15 := Slice(in, 6, 7)
out16 := Slice(in, -10, 1)
out17 := Slice(in, -1, 3)
out18 := Slice(in, -10, 7)

is.Equal([]int{}, out1)
is.Equal([]int{0}, out2)
Expand All @@ -639,6 +642,9 @@ func TestSlice(t *testing.T) {
is.Equal([]int{}, out13)
is.Equal([]int{}, out14)
is.Equal([]int{}, out15)
is.Equal([]int{0}, out16)
is.Equal([]int{0, 1, 2}, out17)
is.Equal([]int{0, 1, 2, 3, 4}, out18)
}

func TestReplace(t *testing.T) {
Expand Down