Skip to content

Commit

Permalink
fix(exp): set capacity for each batch (#490)
Browse files Browse the repository at this point in the history
Inspired by the new golang 1.23 Chunk implementation:
https://togithub.com/golang/go/issues/53987
  • Loading branch information
jooola authored Jul 23, 2024
1 parent 2db9575 commit 57f53c1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 4 additions & 1 deletion hcloud/exp/kit/sliceutil/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package sliceutil

// Batches splits a slice into multiple batches of a desired size.
func Batches[T any](all []T, size int) (batches [][]T) {
batches = make([][]T, 0, (len(all)/size)+1)
for size < len(all) {
all, batches = all[size:], append(batches, all[:size])
// Set the capacity of each chunk so that appending to a chunk does not
// modify the original slice.
all, batches = all[size:], append(batches, all[:size:size])
}
return append(batches, all)
}
6 changes: 6 additions & 0 deletions hcloud/exp/kit/sliceutil/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ func TestBatches(t *testing.T) {
batches := Batches(all, 2)

assert.Len(t, batches, 3)

assert.Equal(t, []int{1, 2}, batches[0])
assert.Equal(t, 2, cap(batches[0]))

assert.Equal(t, []int{3, 4}, batches[1])
assert.Equal(t, 2, cap(batches[1]))

assert.Equal(t, []int{5}, batches[2])
assert.Equal(t, 1, cap(batches[2]))
}

0 comments on commit 57f53c1

Please sign in to comment.