github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/string.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 "errors" 19 "fmt" 20 "io" 21 ) 22 23 // [string] 24 25 func ReadString(source io.Reader) (string, error) { 26 if length, err := ReadShort(source); err != nil { 27 return "", fmt.Errorf("cannot read [string] length: %w", err) 28 } else if length <= 0 { 29 return "", nil 30 } else { 31 decoded := make([]byte, length) 32 if _, err := io.ReadFull(source, decoded); err != nil { 33 return "", fmt.Errorf("cannot read [string] content: %w", err) 34 } 35 return string(decoded), nil 36 } 37 } 38 39 func WriteString(s string, dest io.Writer) error { 40 length := len(s) 41 if err := WriteShort(uint16(length), dest); err != nil { 42 return fmt.Errorf("cannot write [string] length: %w", err) 43 } else if n, err := dest.Write([]byte(s)); err != nil { 44 return fmt.Errorf("cannot write [string] length: %w", err) 45 } else if n < length { 46 return errors.New("not enough capacity to write [string] content") 47 } 48 return nil 49 } 50 51 func LengthOfString(s string) int { 52 return LengthOfShort + len(s) 53 }