trpc.group/trpc-go/trpc-go@v1.0.3/codec/framer_builder.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package codec 15 16 import ( 17 "bufio" 18 "io" 19 ) 20 21 // DefaultReaderSize is the default size of reader in bit. 22 const DefaultReaderSize = 4 * 1024 23 24 // readerSizeConfig is the default size of buffer when framer read package. 25 var readerSizeConfig = DefaultReaderSize 26 27 // NewReaderSize returns a reader with read buffer. Size <= 0 means no buffer. 28 func NewReaderSize(r io.Reader, size int) io.Reader { 29 if size <= 0 { 30 return r 31 } 32 return bufio.NewReaderSize(r, size) 33 } 34 35 // NewReader returns reader with the default buffer size. 36 func NewReader(r io.Reader) io.Reader { 37 return bufio.NewReaderSize(r, readerSizeConfig) 38 } 39 40 // GetReaderSize returns size of read buffer in bit. 41 func GetReaderSize() int { 42 return readerSizeConfig 43 } 44 45 // SetReaderSize sets the size of read buffer in bit. 46 func SetReaderSize(size int) { 47 readerSizeConfig = size 48 } 49 50 // FramerBuilder defines how to build a framer. In general, each connection 51 // build a framer. 52 type FramerBuilder interface { 53 New(io.Reader) Framer 54 } 55 56 // Framer defines how to read a data frame. 57 type Framer interface { 58 ReadFrame() ([]byte, error) 59 } 60 61 // SafeFramer is a special framer, provides an isSafe() method 62 // to describe if it is safe when concurrent read. 63 type SafeFramer interface { 64 Framer 65 // IsSafe returns if this framer is safe when concurrent read. 66 IsSafe() bool 67 } 68 69 // IsSafeFramer returns if this framer is safe when concurrent read. The input 70 // parameter f should implement SafeFramer interface. If not , this method will return false. 71 func IsSafeFramer(f interface{}) bool { 72 framer, ok := f.(SafeFramer) 73 if ok && framer.IsSafe() { 74 return true 75 } 76 return false 77 }