2021-06-15 09:13:40 +00:00
|
|
|
package net
|
2020-05-12 03:29:53 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"net"
|
2023-01-16 01:42:03 +00:00
|
|
|
|
|
|
|
"github.com/sagernet/sing/common/buf"
|
|
|
|
sing_bufio "github.com/sagernet/sing/common/bufio"
|
|
|
|
"github.com/sagernet/sing/common/network"
|
2020-05-12 03:29:53 +00:00
|
|
|
)
|
|
|
|
|
2023-01-16 01:42:03 +00:00
|
|
|
var _ network.ExtendedConn = (*BufferedConn)(nil)
|
|
|
|
|
2020-05-12 03:29:53 +00:00
|
|
|
type BufferedConn struct {
|
|
|
|
r *bufio.Reader
|
2023-01-16 01:42:03 +00:00
|
|
|
network.ExtendedConn
|
2020-05-12 03:29:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewBufferedConn(c net.Conn) *BufferedConn {
|
2021-09-28 15:15:53 +00:00
|
|
|
if bc, ok := c.(*BufferedConn); ok {
|
|
|
|
return bc
|
|
|
|
}
|
2023-01-16 01:42:03 +00:00
|
|
|
return &BufferedConn{bufio.NewReader(c), sing_bufio.NewExtendedConn(c)}
|
2020-05-12 03:29:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Reader returns the internal bufio.Reader.
|
|
|
|
func (c *BufferedConn) Reader() *bufio.Reader {
|
|
|
|
return c.r
|
|
|
|
}
|
|
|
|
|
|
|
|
// Peek returns the next n bytes without advancing the reader.
|
|
|
|
func (c *BufferedConn) Peek(n int) ([]byte, error) {
|
|
|
|
return c.r.Peek(n)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *BufferedConn) Read(p []byte) (int, error) {
|
|
|
|
return c.r.Read(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *BufferedConn) ReadByte() (byte, error) {
|
|
|
|
return c.r.ReadByte()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *BufferedConn) UnreadByte() error {
|
|
|
|
return c.r.UnreadByte()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *BufferedConn) Buffered() int {
|
|
|
|
return c.r.Buffered()
|
|
|
|
}
|
2023-01-16 01:42:03 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|