github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/protorpc/netstring.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/codec/protorpc/netstring.go 14 15 package protorpc 16 17 import ( 18 "encoding/binary" 19 "io" 20 ) 21 22 // WriteNetString writes data to a big-endian netstring on a Writer. 23 // Size is always a 32-bit unsigned int. 24 func WriteNetString(w io.Writer, data []byte) (written int, err error) { 25 size := make([]byte, 4) 26 binary.BigEndian.PutUint32(size, uint32(len(data))) 27 if written, err = w.Write(size); err != nil { 28 return 29 } 30 return w.Write(data) 31 } 32 33 // ReadNetString reads data from a big-endian netstring. 34 func ReadNetString(r io.Reader) (data []byte, err error) { 35 sizeBuf := make([]byte, 4) 36 _, err = r.Read(sizeBuf) 37 if err != nil { 38 return nil, err 39 } 40 size := binary.BigEndian.Uint32(sizeBuf) 41 if size == 0 { 42 return nil, nil 43 } 44 data = make([]byte, size) 45 _, err = r.Read(data) 46 if err != nil { 47 return nil, err 48 } 49 return 50 }