mirror of
https://github.com/opentofu/opentofu.git
synced 2024-12-23 23:50:12 -06:00
fa638907f1
Signed-off-by: Janos <86970079+janosdebugs@users.noreply.github.com> Signed-off-by: Mikel Olasagasti Uranga <mikel@olasagasti.info> Signed-off-by: Christian Mesh <christianmesh1@gmail.com> Signed-off-by: James Humphries <James@james-humphries.co.uk> Co-authored-by: James Humphries <jamesh@spacelift.io> Co-authored-by: Serdar Dalgıç <serdardalgic@users.noreply.github.com> Co-authored-by: Mikel Olasagasti Uranga <mikel@olasagasti.info> Co-authored-by: Christian Mesh <christianmesh1@gmail.com>
60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package collections
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"golang.org/x/exp/slices"
|
|
)
|
|
|
|
// Set is a container that can hold each item only once and has a fast lookup time.
|
|
//
|
|
// You can define a new set like this:
|
|
//
|
|
// var validKeyLengths = collections.Set[int]{
|
|
// 16: {},
|
|
// 24: {},
|
|
// 32: {},
|
|
// }
|
|
//
|
|
// You can also use the constructor to create a new set
|
|
//
|
|
// var validKeyLengths = collections.NewSet[int](16,24,32)
|
|
type Set[T comparable] map[T]struct{}
|
|
|
|
// Constructs a new set given the members of type T
|
|
func NewSet[T comparable](members ...T) Set[T] {
|
|
set := Set[T]{}
|
|
for _, member := range members {
|
|
set[member] = struct{}{}
|
|
}
|
|
return set
|
|
}
|
|
|
|
// Has returns true if the item exists in the Set
|
|
func (s Set[T]) Has(value T) bool {
|
|
_, ok := s[value]
|
|
return ok
|
|
}
|
|
|
|
// String creates a comma-separated list of all values in the set.
|
|
func (s Set[T]) String() string {
|
|
parts := make([]string, len(s))
|
|
i := 0
|
|
for v := range s {
|
|
parts[i] = fmt.Sprintf("%v", v)
|
|
i++
|
|
}
|
|
|
|
slices.SortStableFunc(parts, func(a, b string) int {
|
|
if a < b {
|
|
return -1
|
|
} else if b > a {
|
|
return 1
|
|
} else {
|
|
return 0
|
|
}
|
|
})
|
|
return strings.Join(parts, ", ")
|
|
}
|