util/set: add OfSliceView constructor and Set.AddSliceView

Building a Set from a views.Slice previously required set.Of(v.AsSlice()...),
which allocates an intermediate slice copy before allocating the set. Add
OfSliceView and AddSliceView to populate a set directly from the view,
mirroring the existing AddSlice/AddSeq/AddSet family.

Updates tailscale/corp#45499

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Change-Id: I3f2a9d417c60be8e5f1acd42708e2f9a4d6c1b7e
This commit is contained in:
Brad Fitzpatrick
2026-07-27 16:30:30 -07:00
committed by Brad Fitzpatrick
parent e48e7b730a
commit d0b4d44963
2 changed files with 30 additions and 0 deletions
+16
View File
@@ -10,6 +10,8 @@ import (
"maps"
"reflect"
"sort"
"tailscale.com/types/views"
)
// Set is a set of T.
@@ -27,6 +29,13 @@ func Of[T comparable](slice ...T) Set[T] {
return s
}
// OfSliceView returns a new set constructed from the elements in v.
func OfSliceView[T comparable](v views.Slice[T]) Set[T] {
s := make(Set[T], v.Len())
s.AddSliceView(v)
return s
}
// Clone returns a new set cloned from the elements in s.
func (s Set[T]) Clone() Set[T] {
return maps.Clone(s)
@@ -56,6 +65,13 @@ func (s Set[T]) AddSlice(es []T) {
}
}
// AddSliceView adds each element of v to s.
func (s Set[T]) AddSliceView(v views.Slice[T]) {
for _, e := range v.All() {
s.Add(e)
}
}
// AddSet adds each element of es to s.
func (s Set[T]) AddSet(es Set[T]) {
for e := range es {