github.com/cloudwego/hertz@v0.9.3/pkg/common/test/mock/reader.go (about) 1 /* 2 * Copyright 2022 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package mock 18 19 import ( 20 "bufio" 21 "bytes" 22 "io" 23 ) 24 25 // ZeroCopyReader is used to create ZeroCopyReader for testing. 26 // 27 // NOTE: In principle, ut should use the zcReader created by netpoll.NewReader() for mock testing, 28 // but because zcReader does not implement the io.Reader interface, the test requirements of 29 // io.Reader involved are replaced with MockZeroCopyReader 30 type ZeroCopyReader struct { 31 *bufio.Reader 32 } 33 34 func (m ZeroCopyReader) Peek(n int) ([]byte, error) { 35 b, err := m.Reader.Peek(n) 36 // if n is bigger than the buffer in m.Reader, 37 // it will only return bufio.ErrBufferFull even if the underline reader return io.EOF. 38 // so we make another Peek to get the real error. 39 // for more info: https://github.com/golang/go/issues/50569 40 if err == bufio.ErrBufferFull && len(b) == 0 { 41 return m.Reader.Peek(1) 42 } 43 return b, err 44 } 45 46 func (m ZeroCopyReader) Skip(n int) (err error) { 47 _, err = m.Reader.Discard(n) 48 return 49 } 50 51 func (m ZeroCopyReader) Release() (err error) { 52 return nil 53 } 54 55 func (m ZeroCopyReader) Len() (length int) { 56 return m.Reader.Buffered() 57 } 58 59 func (m ZeroCopyReader) ReadBinary(n int) (p []byte, err error) { 60 panic("implement me") 61 } 62 63 func NewZeroCopyReader(r string) ZeroCopyReader { 64 br := bufio.NewReaderSize(bytes.NewBufferString(r), len(r)) 65 return ZeroCopyReader{br} 66 } 67 68 func NewLimitReader(r *bytes.Buffer) io.LimitedReader { 69 return io.LimitedReader{ 70 R: r, 71 N: int64(r.Len()), 72 } 73 } 74 75 type EOFReader struct{} 76 77 func (e *EOFReader) Peek(n int) ([]byte, error) { 78 return []byte{}, io.EOF 79 } 80 81 func (e *EOFReader) Skip(n int) error { 82 return nil 83 } 84 85 func (e *EOFReader) Release() error { 86 return nil 87 } 88 89 func (e *EOFReader) Len() int { 90 return 0 91 } 92 93 func (e *EOFReader) ReadByte() (byte, error) { 94 return ' ', io.EOF 95 } 96 97 func (e *EOFReader) ReadBinary(n int) (p []byte, err error) { 98 return p, io.EOF 99 } 100 101 func (e *EOFReader) Read(p []byte) (n int, err error) { 102 return 0, io.EOF 103 }