knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/kmap/map.go (about) 1 /* 2 Copyright 2021 The Knative 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 package kmap 18 19 // Copy makes a copy of the map. 20 func Copy(a map[string]string) map[string]string { 21 ret := make(map[string]string, len(a)) 22 for k, v := range a { 23 ret[k] = v 24 } 25 return ret 26 } 27 28 // Union returns a map constructed from the union of input maps. 29 // where values from latter maps win. 30 func Union(maps ...map[string]string) map[string]string { 31 if len(maps) == 0 { 32 return map[string]string{} 33 } 34 out := make(map[string]string, len(maps[0])) 35 36 for _, m := range maps { 37 for k, v := range m { 38 out[k] = v 39 } 40 } 41 return out 42 } 43 44 // Filter creates a copy of the provided map, filtering out the elements 45 // that match `filter`. 46 // nil `filter` is accepted. 47 func Filter(in map[string]string, filter func(string) bool) map[string]string { 48 ret := make(map[string]string, len(in)) 49 for k, v := range in { 50 if filter != nil && filter(k) { 51 continue 52 } 53 ret[k] = v 54 } 55 return ret 56 } 57 58 // ExcludeKeys creates a copy of the provided map filtering out the excluded `keys` 59 func ExcludeKeys(in map[string]string, keys ...string) map[string]string { 60 return ExcludeKeyList(in, keys) 61 } 62 63 // ExcludeKeyList creates a copy of the provided map filtering out excluded `keys` 64 func ExcludeKeyList(in map[string]string, keys []string) map[string]string { 65 ret := make(map[string]string, len(in)) 66 67 outer: 68 for k, v := range in { 69 // opted to skip memory allocation (creating a set) in favour of 70 // looping since the places Knative will use this we typically 71 // exclude one or two keys 72 for _, excluded := range keys { 73 if k == excluded { 74 continue outer 75 } 76 } 77 ret[k] = v 78 } 79 return ret 80 }