github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/string_list.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 list] 23 24 func ReadStringList(source io.Reader) (decoded []string, err error) { 25 var length uint16 26 length, err = ReadShort(source) 27 if err != nil { 28 return nil, fmt.Errorf("cannot read [string list] length: %w", err) 29 } 30 31 if length < 0 { 32 return nil, nil 33 } else if length == 0 { 34 return []string{}, nil 35 } 36 37 decoded = make([]string, length) 38 for i := uint16(0); i < length; i++ { 39 var str string 40 str, err = ReadString(source) 41 if err != nil { 42 return nil, fmt.Errorf("cannot read [string list] element %d: %w", i, err) 43 } 44 decoded[i] = str 45 } 46 return decoded, nil 47 } 48 49 func WriteStringList(list []string, dest io.Writer) error { 50 length := len(list) 51 if err := WriteShort(uint16(length), dest); err != nil { 52 return fmt.Errorf("cannot write [string list] length: %w", err) 53 } 54 for i, s := range list { 55 if err := WriteString(s, dest); err != nil { 56 return fmt.Errorf("cannot write [string list] element %d: %w", i, err) 57 } 58 } 59 return nil 60 } 61 62 func LengthOfStringList(list []string) int { 63 length := LengthOfShort 64 for _, s := range list { 65 length += LengthOfString(s) 66 } 67 return length 68 }