refactor: Implement extended IO

This commit is contained in:
H1JK
2023-01-16 09:42:03 +08:00
parent 8fa66c13a9
commit d1565bb46f
7 changed files with 219 additions and 39 deletions

View File

@ -3,18 +3,24 @@ package net
import (
"bufio"
"net"
"github.com/sagernet/sing/common/buf"
sing_bufio "github.com/sagernet/sing/common/bufio"
"github.com/sagernet/sing/common/network"
)
var _ network.ExtendedConn = (*BufferedConn)(nil)
type BufferedConn struct {
r *bufio.Reader
net.Conn
network.ExtendedConn
}
func NewBufferedConn(c net.Conn) *BufferedConn {
if bc, ok := c.(*BufferedConn); ok {
return bc
}
return &BufferedConn{bufio.NewReader(c), c}
return &BufferedConn{bufio.NewReader(c), sing_bufio.NewExtendedConn(c)}
}
// Reader returns the internal bufio.Reader.
@ -42,3 +48,18 @@ func (c *BufferedConn) UnreadByte() error {
func (c *BufferedConn) Buffered() int {
return c.r.Buffered()
}
func (c *BufferedConn) ReadBuffer(buffer *buf.Buffer) (err error) {
if c.r.Buffered() > 0 {
_, err = buffer.ReadOnceFrom(c.r)
return
}
return c.ExtendedConn.ReadBuffer(buffer)
}
func (c *BufferedConn) Upstream() any {
if wrapper, ok := c.ExtendedConn.(*sing_bufio.ExtendedConnWrapper); ok {
return wrapper.Conn
}
return c.ExtendedConn
}