go.uber.org/yarpc@v1.72.1/transport/tchannel/internal/reader.go (about) 1 // Copyright (c) 2022 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package internal 22 23 import ( 24 "encoding/binary" 25 "io" 26 "sync" 27 ) 28 29 // This file lifted almost as-is from tchannel/typed. 30 31 const _maxPoolStringLen = 32 32 33 // Reader is a reader that reads typed values from an io.Reader. 34 type Reader struct { 35 reader io.Reader 36 err error 37 buf [_maxPoolStringLen]byte 38 } 39 40 var readerPool = sync.Pool{New: func() interface{} { return &Reader{} }} 41 42 // NewReader returns a reader that reads typed values from the reader. 43 func NewReader(reader io.Reader) *Reader { 44 r := readerPool.Get().(*Reader) 45 r.reader = reader 46 r.err = nil 47 return r 48 } 49 50 // ReadUint16 reads a uint16. 51 func (r *Reader) ReadUint16() uint16 { 52 if r.err != nil { 53 return 0 54 } 55 56 buf := r.buf[:2] 57 58 var readN int 59 readN, r.err = io.ReadFull(r.reader, buf) 60 if readN < 2 { 61 return 0 62 } 63 return binary.BigEndian.Uint16(buf) 64 } 65 66 // ReadString reads a string of length n. 67 func (r *Reader) ReadString(n int) string { 68 if r.err != nil { 69 return "" 70 } 71 72 var buf []byte 73 if n <= _maxPoolStringLen { 74 buf = r.buf[:n] 75 } else { 76 buf = make([]byte, n) 77 } 78 79 var readN int 80 readN, r.err = io.ReadFull(r.reader, buf) 81 if readN < n { 82 return "" 83 } 84 s := string(buf) 85 86 return s 87 } 88 89 // ReadLen16String reads a uint16-length prefixed string. 90 func (r *Reader) ReadLen16String() string { 91 len := r.ReadUint16() 92 return r.ReadString(int(len)) 93 } 94 95 // Err returns any errors hit while reading from the underlying reader. 96 func (r *Reader) Err() error { 97 return r.err 98 } 99 100 // Release puts the Reader back in the pool. 101 func (r *Reader) Release() { 102 readerPool.Put(r) 103 }