github.com/v2fly/v2ray-core/v4@v4.45.2/common/buf/writer_test.go (about) 1 package buf_test 2 3 import ( 4 "bufio" 5 "bytes" 6 "crypto/rand" 7 "io" 8 "testing" 9 10 "github.com/google/go-cmp/cmp" 11 12 "github.com/v2fly/v2ray-core/v4/common" 13 . "github.com/v2fly/v2ray-core/v4/common/buf" 14 "github.com/v2fly/v2ray-core/v4/transport/pipe" 15 ) 16 17 func TestWriter(t *testing.T) { 18 lb := New() 19 common.Must2(lb.ReadFrom(rand.Reader)) 20 21 expectedBytes := append([]byte(nil), lb.Bytes()...) 22 23 writeBuffer := bytes.NewBuffer(make([]byte, 0, 1024*1024)) 24 25 writer := NewBufferedWriter(NewWriter(writeBuffer)) 26 writer.SetBuffered(false) 27 common.Must(writer.WriteMultiBuffer(MultiBuffer{lb})) 28 common.Must(writer.Flush()) 29 30 if r := cmp.Diff(expectedBytes, writeBuffer.Bytes()); r != "" { 31 t.Error(r) 32 } 33 } 34 35 func TestBytesWriterReadFrom(t *testing.T) { 36 const size = 50000 37 pReader, pWriter := pipe.New(pipe.WithSizeLimit(size)) 38 reader := bufio.NewReader(io.LimitReader(rand.Reader, size)) 39 writer := NewBufferedWriter(pWriter) 40 writer.SetBuffered(false) 41 nBytes, err := reader.WriteTo(writer) 42 if nBytes != size { 43 t.Fatal("unexpected size of bytes written: ", nBytes) 44 } 45 if err != nil { 46 t.Fatal("expect success, but actually error: ", err.Error()) 47 } 48 49 mb, err := pReader.ReadMultiBuffer() 50 common.Must(err) 51 if mb.Len() != size { 52 t.Fatal("unexpected size read: ", mb.Len()) 53 } 54 } 55 56 func TestDiscardBytes(t *testing.T) { 57 b := New() 58 common.Must2(b.ReadFullFrom(rand.Reader, Size)) 59 60 nBytes, err := io.Copy(DiscardBytes, b) 61 common.Must(err) 62 if nBytes != Size { 63 t.Error("copy size: ", nBytes) 64 } 65 } 66 67 func TestDiscardBytesMultiBuffer(t *testing.T) { 68 const size = 10240*1024 + 1 69 buffer := bytes.NewBuffer(make([]byte, 0, size)) 70 common.Must2(buffer.ReadFrom(io.LimitReader(rand.Reader, size))) 71 72 r := NewReader(buffer) 73 nBytes, err := io.Copy(DiscardBytes, &BufferedReader{Reader: r}) 74 common.Must(err) 75 if nBytes != size { 76 t.Error("copy size: ", nBytes) 77 } 78 } 79 80 func TestWriterInterface(t *testing.T) { 81 { 82 var writer interface{} = (*BufferToBytesWriter)(nil) 83 switch writer.(type) { 84 case Writer, io.Writer, io.ReaderFrom: 85 default: 86 t.Error("BufferToBytesWriter is not Writer, io.Writer or io.ReaderFrom") 87 } 88 } 89 90 { 91 var writer interface{} = (*BufferedWriter)(nil) 92 switch writer.(type) { 93 case Writer, io.Writer, io.ReaderFrom, io.ByteWriter: 94 default: 95 t.Error("BufferedWriter is not Writer, io.Writer, io.ReaderFrom or io.ByteWriter") 96 } 97 } 98 }