fix(chunk): Copy chunk in a new slice

Prevents memory leak and free memory from initial collection.
This commit is contained in:
Samuel Berthe
2025-07-06 15:29:28 +02:00
parent 49f24de919
commit d905a6349d
2 changed files with 7 additions and 1 deletions

View File

@@ -25,6 +25,8 @@ tools:
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go get -t -u golang.org/x/tools/cmd/cover
go install github.com/sonatype-nexus-community/nancy@latest
go install golang.org/x/perf/cmd/benchstat@latest
go install github.com/cespare/prettybench@latest
go mod tidy
lint:

View File

@@ -221,7 +221,11 @@ 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:last])
// Copy chunk in a new slice, to prevent memory leak and free memory from initial collection.
newSlice := make(Slice, last-i*size)
copy(newSlice, collection[i*size:last])
result = append(result, newSlice)
}
return result