github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/tun/device/linkWriterToWriter.go (about)

     1  package device
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/v2fly/v2ray-core/v5/common/errors"
     7  
     8  	"gvisor.dev/gvisor/pkg/buffer"
     9  	"gvisor.dev/gvisor/pkg/tcpip/stack"
    10  )
    11  
    12  func NewLinkWriterToWriter(writer stack.LinkWriter) io.Writer {
    13  	return &linkWriterToWriter{writer: writer}
    14  }
    15  
    16  type linkWriterToWriter struct {
    17  	writer stack.LinkWriter
    18  }
    19  
    20  func (l linkWriterToWriter) Write(p []byte) (n int, err error) {
    21  	buffer := buffer.MakeWithData(p)
    22  	packetBufferPtr := stack.NewPacketBuffer(stack.PacketBufferOptions{
    23  		Payload: buffer,
    24  		OnRelease: func() {
    25  			buffer.Release()
    26  		},
    27  	})
    28  	packetList := stack.PacketBufferList{}
    29  	packetList.PushBack(packetBufferPtr)
    30  	_, terr := l.writer.WritePackets(packetList)
    31  	if terr != nil {
    32  		return 0, newError("failed to write packet").Base(errors.New(terr.String())).AtError()
    33  	}
    34  	return len(p), nil
    35  }