github.com/fafucoder/cilium@v1.6.11/pkg/set/set.go (about) 1 // Copyright 2019 Authors of Cilium 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 set 16 17 // SliceSubsetOf checks whether the first slice is a subset of the second slice. If 18 // not, it also returns slice of elements which are the difference of both 19 // input slices. 20 func SliceSubsetOf(sub, main []string) (bool, []string) { 21 var diff []string 22 occurrences := make(map[string]int, len(main)) 23 result := true 24 for _, element := range main { 25 occurrences[element]++ 26 } 27 for _, element := range sub { 28 if count, ok := occurrences[element]; !ok { 29 // Element was not found in the main slice. 30 result = false 31 diff = append(diff, element) 32 } else if count < 1 { 33 // The element is in both slices, but the sub slice 34 // has more duplicates. 35 result = false 36 } else { 37 occurrences[element]-- 38 } 39 } 40 return result, diff 41 }