mirror of
https://github.com/tailscale/tailscale.git
synced 2025-08-11 13:18:53 +00:00
util/slicesx: add AppendNonzero
By request of @agottardo. Updates #cleanup Change-Id: I2f02314eb9533b1581e47b66b45b6fb8ac257bb7 Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:

committed by
Brad Fitzpatrick

parent
17022ad0e9
commit
8b65598614
@@ -95,6 +95,17 @@ func Filter[S ~[]T, T any](dst, src S, fn func(T) bool) S {
|
||||
return dst
|
||||
}
|
||||
|
||||
// AppendNonzero appends all non-zero elements of src to dst.
|
||||
func AppendNonzero[S ~[]T, T comparable](dst, src S) S {
|
||||
var zero T
|
||||
for _, v := range src {
|
||||
if v != zero {
|
||||
dst = append(dst, v)
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// AppendMatching appends elements in ps to dst if f(x) is true.
|
||||
func AppendMatching[T any](dst, ps []T, f func(T) bool) []T {
|
||||
for _, p := range ps {
|
||||
|
@@ -137,6 +137,19 @@ func TestFilterNoAllocations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendNonzero(t *testing.T) {
|
||||
v := []string{"one", "two", "", "four"}
|
||||
got := AppendNonzero(nil, v)
|
||||
want := []string{"one", "two", "four"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v; want %v", got, want)
|
||||
}
|
||||
got = AppendNonzero(v[:0], v)
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("got %v; want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendMatching(t *testing.T) {
|
||||
v := []string{"one", "two", "three", "four"}
|
||||
got := AppendMatching(v[:0], v, func(s string) bool { return len(s) > 3 })
|
||||
|
Reference in New Issue
Block a user