From 9e343973a4629da234a8eca0aad725a7e888328c Mon Sep 17 00:00:00 2001 From: Mihir Gandhi Date: Mon, 15 Jul 2024 22:46:03 +0530 Subject: [PATCH] fix: chunk memory leak (#491) --- slice.go | 2 +- slice_test.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/slice.go b/slice.go index bf69d3b0..38b50e82 100644 --- a/slice.go +++ b/slice.go @@ -182,7 +182,7 @@ func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { if last > len(collection) { last = len(collection) } - result = append(result, collection[i*size:last]) + result = append(result, collection[i*size:last:last]) } return result diff --git a/slice_test.go b/slice_test.go index 0917e171..f13e129c 100644 --- a/slice_test.go +++ b/slice_test.go @@ -235,6 +235,12 @@ func TestChunk(t *testing.T) { allStrings := myStrings{"", "foo", "bar"} nonempty := Chunk(allStrings, 2) is.IsType(nonempty[0], allStrings, "type preserved") + + // appending to a chunk should not affect original array + originalArray := []int{0, 1, 2, 3, 4, 5} + result5 := Chunk(originalArray, 2) + result5[0] = append(result5[0], 6) + is.Equal(originalArray, []int{0, 1, 2, 3, 4, 5}) } func TestPartitionBy(t *testing.T) {