github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/types/label/convert.go (about) 1 // Copyright 2024 Gravitational, Inc. 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 label 16 17 import labelv1 "github.com/gravitational/teleport/api/gen/proto/go/teleport/label/v1" 18 19 // FromMap converts a map[string][]string to a slice of *labelv1.Label. 20 // Each key-value pair in the input map is transformed into a label with the 21 // key as the name and the corresponding slice of strings as values. 22 func FromMap(in map[string][]string) []*labelv1.Label { 23 if len(in) == 0 { 24 return nil 25 } 26 27 out := make([]*labelv1.Label, 0, len(in)) 28 for name, values := range in { 29 out = append(out, &labelv1.Label{Name: name, Values: values}) 30 } 31 return out 32 } 33 34 // ToMap converts a slice of *labelv1.Label to a map[string][]string. 35 // Each label in the input slice contributes to the resulting map by adding 36 // its name as the key and appending its values to the corresponding slice 37 // of strings in the map. 38 // If there are multiple labels with the same key, their values will be concatenated. 39 func ToMap(labels []*labelv1.Label) map[string][]string { 40 out := make(map[string][]string) 41 for _, label := range labels { 42 entry := out[label.GetName()] 43 entry = append(entry, label.Values...) 44 out[label.GetName()] = entry 45 } 46 return out 47 }