github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/integers.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 "encoding/binary" 19 "fmt" 20 "io" 21 ) 22 23 const ( 24 LengthOfByte = 1 25 LengthOfShort = 2 26 LengthOfInt = 4 27 LengthOfLong = 8 28 ) 29 30 // [byte] ([byte] is not defined in protocol specs but is used by other primitives) 31 32 func ReadByte(source io.Reader) (decoded uint8, err error) { 33 if err = binary.Read(source, binary.BigEndian, &decoded); err != nil { 34 err = fmt.Errorf("cannot read [byte]: %w", err) 35 } 36 return decoded, err 37 } 38 39 func WriteByte(b uint8, dest io.Writer) error { 40 if err := binary.Write(dest, binary.BigEndian, b); err != nil { 41 return fmt.Errorf("cannot write [byte]: %w", err) 42 } 43 return nil 44 } 45 46 // [short] 47 48 func ReadShort(source io.Reader) (decoded uint16, err error) { 49 if err = binary.Read(source, binary.BigEndian, &decoded); err != nil { 50 err = fmt.Errorf("cannot read [short]: %w", err) 51 } 52 return decoded, err 53 } 54 55 func WriteShort(i uint16, dest io.Writer) error { 56 if err := binary.Write(dest, binary.BigEndian, i); err != nil { 57 return fmt.Errorf("cannot write [short]: %w", err) 58 } 59 return nil 60 } 61 62 // [int] 63 64 func ReadInt(source io.Reader) (decoded int32, err error) { 65 if err = binary.Read(source, binary.BigEndian, &decoded); err != nil { 66 err = fmt.Errorf("cannot read [int]: %w", err) 67 } 68 return decoded, err 69 } 70 71 func WriteInt(i int32, dest io.Writer) error { 72 if err := binary.Write(dest, binary.BigEndian, i); err != nil { 73 return fmt.Errorf("cannot write [int]: %w", err) 74 } 75 return nil 76 } 77 78 // [long] 79 80 func ReadLong(source io.Reader) (decoded int64, err error) { 81 if err = binary.Read(source, binary.BigEndian, &decoded); err != nil { 82 err = fmt.Errorf("cannot read [long]: %w", err) 83 } 84 return decoded, err 85 } 86 87 func WriteLong(l int64, dest io.Writer) error { 88 if err := binary.Write(dest, binary.BigEndian, l); err != nil { 89 return fmt.Errorf("cannot write [long]: %w", err) 90 } 91 return nil 92 }