github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/utils/collections/collections_utils.go (about) 1 // Copyright 2020 Google Inc. All Rights Reserved. 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 // ReverseMap reverses keys and their values. 18 // The 2nd returned value indicates whether the operation succeeded. A map with 19 // duplicate values can't be reversed. In that case, a 'false' is returned. 20 func ReverseMap(m map[string]string) (map[string]string, bool) { 21 newMap := make(map[string]string, len(m)) 22 for k, v := range m { 23 if _, ok := newMap[v]; ok { 24 return nil, false 25 } 26 newMap[v] = k 27 } 28 return newMap, true 29 } 30 31 // GetKeys gets all keys of the map. 32 func GetKeys(m map[string]string) []string { 33 keys := make([]string, 0, len(m)) 34 for k := range m { 35 keys = append(keys, k) 36 } 37 return keys 38 }