github.com/datastax/go-cassandra-native-protocol@v0.0.0-20220706104457-5e8aad05cf90/primitive/inet.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 "net" 22 ) 23 24 // [inet] (net.IP + port) 25 26 // Inet is the [inet] protocol type. It is the combination of a net.IP + port number. 27 // +k8s:deepcopy-gen=true 28 type Inet struct { 29 Addr net.IP 30 Port int32 31 } 32 33 func (i Inet) String() string { 34 return fmt.Sprintf("%v:%v", i.Addr, i.Port) 35 } 36 37 func ReadInet(source io.Reader) (*Inet, error) { 38 if addr, err := ReadInetAddr(source); err != nil { 39 return nil, fmt.Errorf("cannot read [inet] address: %w", err) 40 } else if port, err := ReadInt(source); err != nil { 41 return nil, fmt.Errorf("cannot read [inet] port number: %w", err) 42 } else { 43 return &Inet{Addr: addr, Port: port}, nil 44 } 45 } 46 47 func WriteInet(inet *Inet, dest io.Writer) error { 48 if inet == nil { 49 return errors.New("cannot write nil [inet]") 50 } 51 if err := WriteInetAddr(inet.Addr, dest); err != nil { 52 return fmt.Errorf("cannot write [inet] address: %w", err) 53 } else if err := WriteInt(inet.Port, dest); err != nil { 54 return fmt.Errorf("cannot write [inet] port number: %w", err) 55 } 56 return nil 57 } 58 59 func LengthOfInet(inet *Inet) (length int, err error) { 60 if inet == nil { 61 return -1, errors.New("cannot compute nil [inet] length") 62 } 63 length, err = LengthOfInetAddr(inet.Addr) 64 if err != nil { 65 return -1, err 66 } 67 return length + LengthOfInt, nil 68 }