VictoriaMetrics/lib/slicesutil/slicesutil.go
Aliaksandr Valialkin 590160ddbb
lib/slicesutil: add helper functions for setting slice length and extending its capacity
The added helper functions - SetLength() and ExtendCapacity() - replace error-prone code with simple function calls.
2024-05-12 11:32:17 +02:00

24 lines
639 B
Go

package slicesutil
// ExtendCapacity returns a with the capacity extended to len(a)+itemsToAdd.
//
// It may allocate new slice if cap(a) is smaller than len(a)+itemsToAdd.
func ExtendCapacity[T any](a []T, itemsToAdd int) []T {
aLen := len(a)
if n := aLen + itemsToAdd - cap(a); n > 0 {
a = append(a[:cap(a)], make([]T, n)...)
return a[:aLen]
}
return a
}
// SetLength sets len(a) to newLen and returns the result.
//
// It may allocate new slice if cap(a) is smaller than newLen.
func SetLength[T any](a []T, newLen int) []T {
if n := newLen - cap(a); n > 0 {
a = append(a[:cap(a)], make([]T, n)...)
}
return a[:newLen]
}