github.com/kelleygo/clashcore@v1.0.2/transport/ssr/protocol/packet.go (about)

     1  package protocol
     2  
     3  import (
     4  	"net"
     5  
     6  	N "github.com/kelleygo/clashcore/common/net"
     7  	"github.com/kelleygo/clashcore/common/pool"
     8  )
     9  
    10  type PacketConn struct {
    11  	N.EnhancePacketConn
    12  	Protocol
    13  }
    14  
    15  func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
    16  	buf := pool.GetBuffer()
    17  	defer pool.PutBuffer(buf)
    18  	err := c.EncodePacket(buf, b)
    19  	if err != nil {
    20  		return 0, err
    21  	}
    22  	_, err = c.EnhancePacketConn.WriteTo(buf.Bytes(), addr)
    23  	return len(b), err
    24  }
    25  
    26  func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
    27  	n, addr, err := c.EnhancePacketConn.ReadFrom(b)
    28  	if err != nil {
    29  		return n, addr, err
    30  	}
    31  	decoded, err := c.DecodePacket(b[:n])
    32  	if err != nil {
    33  		return n, addr, err
    34  	}
    35  	copy(b, decoded)
    36  	return len(decoded), addr, nil
    37  }
    38  
    39  func (c *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
    40  	data, put, addr, err = c.EnhancePacketConn.WaitReadFrom()
    41  	if err != nil {
    42  		return
    43  	}
    44  	data, err = c.DecodePacket(data)
    45  	if err != nil {
    46  		if put != nil {
    47  			put()
    48  		}
    49  		data = nil
    50  		put = nil
    51  		return
    52  	}
    53  	return
    54  }