github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/common/buf/readv_test.go (about)

     1  // +build !wasm
     2  
     3  package buf_test
     4  
     5  import (
     6  	"crypto/rand"
     7  	"net"
     8  	"testing"
     9  
    10  	"github.com/google/go-cmp/cmp"
    11  
    12  	"golang.org/x/sync/errgroup"
    13  	"v2ray.com/core/common"
    14  	. "v2ray.com/core/common/buf"
    15  	"v2ray.com/core/testing/servers/tcp"
    16  )
    17  
    18  func TestReadvReader(t *testing.T) {
    19  	tcpServer := &tcp.Server{
    20  		MsgProcessor: func(b []byte) []byte {
    21  			return b
    22  		},
    23  	}
    24  	dest, err := tcpServer.Start()
    25  	common.Must(err)
    26  	defer tcpServer.Close() // nolint: errcheck
    27  
    28  	conn, err := net.Dial("tcp", dest.NetAddr())
    29  	common.Must(err)
    30  	defer conn.Close() // nolint: errcheck
    31  
    32  	const size = 8192
    33  	data := make([]byte, 8192)
    34  	common.Must2(rand.Read(data))
    35  
    36  	var errg errgroup.Group
    37  	errg.Go(func() error {
    38  		writer := NewWriter(conn)
    39  		mb := MergeBytes(nil, data)
    40  
    41  		return writer.WriteMultiBuffer(mb)
    42  	})
    43  
    44  	defer func() {
    45  		if err := errg.Wait(); err != nil {
    46  			t.Error(err)
    47  		}
    48  	}()
    49  
    50  	rawConn, err := conn.(*net.TCPConn).SyscallConn()
    51  	common.Must(err)
    52  
    53  	reader := NewReadVReader(conn, rawConn)
    54  	var rmb MultiBuffer
    55  	for {
    56  		mb, err := reader.ReadMultiBuffer()
    57  		if err != nil {
    58  			t.Fatal("unexpected error: ", err)
    59  		}
    60  		rmb, _ = MergeMulti(rmb, mb)
    61  		if rmb.Len() == size {
    62  			break
    63  		}
    64  	}
    65  
    66  	rdata := make([]byte, size)
    67  	SplitBytes(rmb, rdata)
    68  
    69  	if r := cmp.Diff(data, rdata); r != "" {
    70  		t.Fatal(r)
    71  	}
    72  }