From e7d1538a2d344b58ee2dc20cb24a4c0cada59d51 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Sun, 27 Aug 2023 16:32:06 -0700 Subject: [PATCH] types/views: add SliceEqual, like std slices.Equal Updates tailscale/corp#6198 Change-Id: I38614a4552c9fa933036aa493c7cdb57c7ffe2d2 Signed-off-by: Brad Fitzpatrick --- types/views/views.go | 6 ++++++ types/views/views_test.go | 14 ++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/types/views/views.go b/types/views/views.go index 3a802a09c..117e80adc 100644 --- a/types/views/views.go +++ b/types/views/views.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "maps" + "slices" "go4.org/mem" ) @@ -275,6 +276,11 @@ func SliceContains[T comparable](v Slice[T], e T) bool { return false } +// SliceEqual is like the standard library's slices.Equal, but for two views. +func SliceEqual[T comparable](a, b Slice[T]) bool { + return slices.Equal(a.ж, b.ж) +} + // SliceEqualAnyOrder reports whether a and b contain the same elements, regardless of order. // The underlying slices for a and b can be nil. func SliceEqualAnyOrder[T comparable](a, b Slice[T]) bool { diff --git a/types/views/views_test.go b/types/views/views_test.go index c04eef62b..93cda30e5 100644 --- a/types/views/views_test.go +++ b/types/views/views_test.go @@ -150,3 +150,17 @@ func TestLenIter(t *testing.T) { t.Errorf("got %q; want %q", got, orig) } } + +func TestSliceEqual(t *testing.T) { + a := SliceOf([]string{"foo", "bar"}) + b := SliceOf([]string{"foo", "bar"}) + if !SliceEqual(a, b) { + t.Errorf("got a != b") + } + if !SliceEqual(a.SliceTo(0), b.SliceTo(0)) { + t.Errorf("got a[:0] != b[:0]") + } + if SliceEqual(a.SliceTo(2), a.SliceTo(1)) { + t.Error("got a[:2] == a[:1]") + } +}