Dragonfly2
75 строк · 1.4 Кб
1/*
2* Copyright 2020 The Dragonfly Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17//go:generate mockgen -destination mocks/set_mock.go -source set.go -package mocks
18
19package set
20
21type Set[T comparable] interface {
22Values() []T
23Add(T) bool
24Delete(T)
25Contains(...T) bool
26Len() uint
27Clear()
28}
29
30type set[T comparable] map[T]struct{}
31
32func New[T comparable]() Set[T] {
33return &set[T]{}
34}
35
36func (s *set[T]) Values() []T {
37var result []T
38for k := range *s {
39result = append(result, k)
40}
41
42return result
43}
44
45func (s *set[T]) Add(v T) bool {
46_, found := (*s)[v]
47if found {
48return false
49}
50
51(*s)[v] = struct{}{}
52return true
53}
54
55func (s *set[T]) Delete(v T) {
56delete(*s, v)
57}
58
59func (s *set[T]) Contains(vals ...T) bool {
60for _, v := range vals {
61if _, ok := (*s)[v]; !ok {
62return false
63}
64}
65
66return true
67}
68
69func (s *set[T]) Len() uint {
70return uint(len(*s))
71}
72
73func (s *set[T]) Clear() {
74*s = set[T]{}
75}
76