From 613f0c0eb8a17a98ecdb096a7f9f7d5053c1c963 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Wed, 12 Jul 2023 16:04:46 -0700 Subject: [PATCH] slices: add DeleteFunc DeleteFunc was added to the standard library for the 1.21 release. Add it here in x/exp for people still using earlier releases. For golang/go#54768 Fixes golang/go#61327 Change-Id: I3c37051c289f46b0068bc1ee5da610149c59cd22 Reviewed-on: https://go-review.googlesource.com/c/exp/+/509236 Run-TryBot: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Cherry Mui Auto-Submit: Ian Lance Taylor TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: Eli Bendersky --- slices/slices.go | 24 ++++++++++++++++++++++ slices/slices_test.go | 46 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/slices/slices.go b/slices/slices.go index 2540bd682..8a7cf20db 100644 --- a/slices/slices.go +++ b/slices/slices.go @@ -168,6 +168,30 @@ func Delete[S ~[]E, E any](s S, i, j int) S { return append(s[:i], s[j:]...) } +// DeleteFunc removes any elements from s for which del returns true, +// returning the modified slice. +// When DeleteFunc removes m elements, it might not modify the elements +// s[len(s)-m:len(s)]. If those elements contain pointers you might consider +// zeroing those elements so that objects they reference can be garbage +// collected. +func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S { + // Don't start copying elements until we find one to delete. + for i, v := range s { + if del(v) { + j := i + for i++; i < len(s); i++ { + v = s[i] + if !del(v) { + s[j] = v + j++ + } + } + return s[:j] + } + } + return s +} + // Replace replaces the elements s[i:j] by the given v, and returns the // modified slice. Replace panics if s[i:j] is not a valid slice of s. func Replace[S ~[]E, E any](s S, i, j int, v ...E) S { diff --git a/slices/slices_test.go b/slices/slices_test.go index 6ecd822d6..c2402dd76 100644 --- a/slices/slices_test.go +++ b/slices/slices_test.go @@ -498,6 +498,52 @@ func TestDelete(t *testing.T) { } } +var deleteFuncTests = []struct { + s []int + fn func(int) bool + want []int +}{ + { + nil, + func(int) bool { return true }, + nil, + }, + { + []int{1, 2, 3}, + func(int) bool { return true }, + nil, + }, + { + []int{1, 2, 3}, + func(int) bool { return false }, + []int{1, 2, 3}, + }, + { + []int{1, 2, 3}, + func(i int) bool { return i > 2 }, + []int{1, 2}, + }, + { + []int{1, 2, 3}, + func(i int) bool { return i < 2 }, + []int{2, 3}, + }, + { + []int{10, 2, 30}, + func(i int) bool { return i >= 10 }, + []int{2}, + }, +} + +func TestDeleteFunc(t *testing.T) { + for i, test := range deleteFuncTests { + copy := Clone(test.s) + if got := DeleteFunc(copy, test.fn); !Equal(got, test.want) { + t.Errorf("DeleteFunc case %d: got %v, want %v", i, got, test.want) + } + } +} + func panics(f func()) (b bool) { defer func() { if x := recover(); x != nil {