github.com/xmplusdev/xray-core@v1.8.10/common/buf/readv_test.go (about)

     1  //go:build !wasm
     2  // +build !wasm
     3  
     4  package buf_test
     5  
     6  import (
     7  	"crypto/rand"
     8  	"net"
     9  	"testing"
    10  
    11  	"github.com/google/go-cmp/cmp"
    12  	"github.com/xmplusdev/xray-core/common"
    13  	. "github.com/xmplusdev/xray-core/common/buf"
    14  	"github.com/xmplusdev/xray-core/testing/servers/tcp"
    15  	"golang.org/x/sync/errgroup"
    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()
    27  
    28  	conn, err := net.Dial("tcp", dest.NetAddr())
    29  	common.Must(err)
    30  	defer conn.Close()
    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, nil)
    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  }