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