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