Add bufio cached packet conn

This commit is contained in:
世界 2022-07-06 12:18:06 +08:00
parent 53c9f8d137
commit 9cd9268a7e
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 47 additions and 1 deletions

View file

@ -30,6 +30,7 @@ linters:
- gocognit
- golint
- goimports
- nosnakecase
linters-settings:
revive:
@ -41,4 +42,9 @@ linters-settings:
disable:
- composites
- fieldalignment
- shadow
- shadow
gci:
sections:
- standard
- prefix(github.com/sagernet/sing)
- default

View file

@ -6,6 +6,8 @@ import (
"time"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type CachedConn struct {
@ -135,3 +137,41 @@ func (r *CachedReader) Close() error {
r.buffer.Release()
return nil
}
type CachedPacketConn struct {
N.PacketConn
buffer *buf.Buffer
destination M.Socksaddr
}
func NewCachedPacketConn(conn N.PacketConn, buffer *buf.Buffer, destination M.Socksaddr) *CachedPacketConn {
return &CachedPacketConn{
PacketConn: conn,
buffer: buffer,
destination: destination,
}
}
func (c *CachedPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
if c.buffer != nil {
_, err = buffer.ReadFrom(c.buffer)
if err != nil {
return M.Socksaddr{}, err
}
c.buffer = nil
return c.destination, nil
}
return c.PacketConn.ReadPacket(buffer)
}
func (c *CachedPacketConn) Upstream() any {
return c.PacketConn
}
func (c *CachedPacketConn) ReaderReplaceable() bool {
return c.buffer == nil
}
func (c *CachedPacketConn) WriterReplaceable() bool {
return true
}