github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/internal/collections/set.go (about) 1 // Copyright 2024 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package collections 16 17 type Set[T comparable] map[T]struct{} 18 19 func (s Set[T]) Add(el ...T) { 20 for _, el := range el { 21 s[el] = struct{}{} 22 } 23 } 24 25 func (s Set[T]) Remove(el T) bool { 26 if !s.Contains(el) { 27 return false 28 } 29 delete(s, el) 30 return true 31 } 32 33 func (s Set[T]) Contains(el T) bool { 34 _, ok := s[el] 35 return ok 36 } 37 38 func (s Set[T]) ToSlice() []T { 39 sl := []T{} 40 for el := range s { 41 sl = append(sl, el) 42 } 43 return sl 44 } 45 46 func (s Set[T]) Clone() Set[T] { 47 newSet := Set[T]{} 48 for el := range s { 49 newSet.Add(el) 50 } 51 return newSet 52 } 53 54 func (s Set[T]) Equals(rhs Set[T]) bool { 55 if len(s) != len(rhs) { 56 return false 57 } 58 rhsClone := rhs.Clone() 59 for el := range s { 60 rhsClone.Remove(el) 61 } 62 return len(rhsClone) == 0 63 } 64 65 func SliceToSet[T comparable](sl []T) Set[T] { 66 set := Set[T]{} 67 for _, el := range sl { 68 set.Add(el) 69 } 70 return set 71 }