github.com/metacubex/mihomo@v1.18.5/common/net/packet/ref.go (about) 1 package packet 2 3 import ( 4 "net" 5 "runtime" 6 "time" 7 ) 8 9 type refPacketConn struct { 10 pc EnhancePacketConn 11 ref any 12 } 13 14 func (c *refPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) { 15 defer runtime.KeepAlive(c.ref) 16 return c.pc.WaitReadFrom() 17 } 18 19 func (c *refPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { 20 defer runtime.KeepAlive(c.ref) 21 return c.pc.ReadFrom(p) 22 } 23 24 func (c *refPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { 25 defer runtime.KeepAlive(c.ref) 26 return c.pc.WriteTo(p, addr) 27 } 28 29 func (c *refPacketConn) Close() error { 30 defer runtime.KeepAlive(c.ref) 31 return c.pc.Close() 32 } 33 34 func (c *refPacketConn) LocalAddr() net.Addr { 35 defer runtime.KeepAlive(c.ref) 36 return c.pc.LocalAddr() 37 } 38 39 func (c *refPacketConn) SetDeadline(t time.Time) error { 40 defer runtime.KeepAlive(c.ref) 41 return c.pc.SetDeadline(t) 42 } 43 44 func (c *refPacketConn) SetReadDeadline(t time.Time) error { 45 defer runtime.KeepAlive(c.ref) 46 return c.pc.SetReadDeadline(t) 47 } 48 49 func (c *refPacketConn) SetWriteDeadline(t time.Time) error { 50 defer runtime.KeepAlive(c.ref) 51 return c.pc.SetWriteDeadline(t) 52 } 53 54 func (c *refPacketConn) Upstream() any { 55 return c.pc 56 } 57 58 func (c *refPacketConn) ReaderReplaceable() bool { // Relay() will handle reference 59 return true 60 } 61 62 func (c *refPacketConn) WriterReplaceable() bool { // Relay() will handle reference 63 return true 64 } 65 66 func NewRefPacketConn(pc net.PacketConn, ref any) EnhancePacketConn { 67 rPC := &refPacketConn{pc: NewEnhancePacketConn(pc), ref: ref} 68 if singPC, isSingPC := pc.(SingPacketConn); isSingPC { 69 return &refSingPacketConn{ 70 refPacketConn: rPC, 71 singPacketConn: singPC, 72 } 73 } 74 return rPC 75 }