mirror of
https://github.com/tailscale/tailscale.git
synced 2025-12-05 04:11:59 +00:00
util/set: add some useful utility functions for Set (#9535)
Also give each type of set its own file. Updates #cleanup Signed-off-by: Chris Palmer <cpalmer@tailscale.com>
This commit is contained in:
@@ -7,9 +7,33 @@ package set
|
||||
// Set is a set of T.
|
||||
type Set[T comparable] map[T]struct{}
|
||||
|
||||
// SetOf returns a new set constructed from the elements in slice.
|
||||
func SetOf[T comparable](slice []T) Set[T] {
|
||||
s := make(Set[T])
|
||||
s.AddSlice(slice)
|
||||
return s
|
||||
}
|
||||
|
||||
// Add adds e to the set.
|
||||
func (s Set[T]) Add(e T) { s[e] = struct{}{} }
|
||||
|
||||
// AddSlice adds each element of es to the set.
|
||||
func (s Set[T]) AddSlice(es []T) {
|
||||
for _, e := range es {
|
||||
s.Add(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Slice returns the elements of the set as a slice. The elements will not be
|
||||
// in any particular order.
|
||||
func (s Set[T]) Slice() []T {
|
||||
es := make([]T, 0, s.Len())
|
||||
for k := range s {
|
||||
es = append(es, k)
|
||||
}
|
||||
return es
|
||||
}
|
||||
|
||||
// Delete removes e from the set.
|
||||
func (s Set[T]) Delete(e T) { delete(s, e) }
|
||||
|
||||
@@ -21,27 +45,3 @@ func (s Set[T]) Contains(e T) bool {
|
||||
|
||||
// Len reports the number of items in s.
|
||||
func (s Set[T]) Len() int { return len(s) }
|
||||
|
||||
// HandleSet is a set of T.
|
||||
//
|
||||
// It is not safe for concurrent use.
|
||||
type HandleSet[T any] map[Handle]T
|
||||
|
||||
// Handle is a opaque comparable value that's used as the map key
|
||||
// in a HandleSet. The only way to get one is to call HandleSet.Add.
|
||||
type Handle struct {
|
||||
v *byte
|
||||
}
|
||||
|
||||
// Add adds the element (map value) e to the set.
|
||||
//
|
||||
// It returns the handle (map key) with which e can be removed, using a map
|
||||
// delete.
|
||||
func (s *HandleSet[T]) Add(e T) Handle {
|
||||
h := Handle{new(byte)}
|
||||
if *s == nil {
|
||||
*s = make(HandleSet[T])
|
||||
}
|
||||
(*s)[h] = e
|
||||
return h
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user