github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/string_multimap.go (about) 1 // Copyright 2020 DataStax 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 primitive 16 17 import ( 18 "fmt" 19 "io" 20 ) 21 22 // [string multimap] 23 24 func ReadStringMultiMap(source io.Reader) (decoded map[string][]string, err error) { 25 if length, err := ReadShort(source); err != nil { 26 return nil, fmt.Errorf("cannot read [string multimap] length: %w", err) 27 } else { 28 decoded := make(map[string][]string, length) 29 for i := uint16(0); i < length; i++ { 30 if key, err := ReadString(source); err != nil { 31 return nil, fmt.Errorf("cannot read [string multimap] entry %d key: %w", i, err) 32 } else if value, err := ReadStringList(source); err != nil { 33 return nil, fmt.Errorf("cannot read [string multimap] entry %d value: %w", i, err) 34 } else { 35 decoded[key] = value 36 } 37 } 38 return decoded, nil 39 } 40 } 41 42 func WriteStringMultiMap(m map[string][]string, dest io.Writer) error { 43 if err := WriteShort(uint16(len(m)), dest); err != nil { 44 return fmt.Errorf("cannot write [string multimap] length: %w", err) 45 } 46 for key, value := range m { 47 if err := WriteString(key, dest); err != nil { 48 return fmt.Errorf("cannot write [string multimap] entry '%v' key: %w", key, err) 49 } 50 if err := WriteStringList(value, dest); err != nil { 51 return fmt.Errorf("cannot write [string multimap] entry '%v' value: %w", key, err) 52 } 53 } 54 return nil 55 } 56 57 func LengthOfStringMultiMap(m map[string][]string) int { 58 length := LengthOfShort 59 for key, value := range m { 60 length += LengthOfString(key) + LengthOfStringList(value) 61 } 62 return length 63 }