2016-03-12 11:52:13 +03:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2016-03-16 17:57:24 +03:00
|
|
|
"io"
|
2016-03-12 11:52:13 +03:00
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const defaultBufSize = 4096
|
|
|
|
|
2016-03-12 13:41:02 +03:00
|
|
|
var noDeadline = time.Time{}
|
2016-03-12 11:52:13 +03:00
|
|
|
|
|
|
|
type Conn struct {
|
2016-03-14 14:17:33 +03:00
|
|
|
NetConn net.Conn
|
2016-03-12 11:52:13 +03:00
|
|
|
Rd *bufio.Reader
|
|
|
|
Buf []byte
|
|
|
|
|
2016-03-15 15:04:35 +03:00
|
|
|
Inited bool
|
|
|
|
UsedAt time.Time
|
|
|
|
|
2016-03-12 11:52:13 +03:00
|
|
|
ReadTimeout time.Duration
|
|
|
|
WriteTimeout time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConn(netConn net.Conn) *Conn {
|
|
|
|
cn := &Conn{
|
2016-03-14 14:17:33 +03:00
|
|
|
NetConn: netConn,
|
2016-03-12 11:52:13 +03:00
|
|
|
Buf: make([]byte, defaultBufSize),
|
|
|
|
|
|
|
|
UsedAt: time.Now(),
|
|
|
|
}
|
|
|
|
cn.Rd = bufio.NewReader(cn)
|
|
|
|
return cn
|
|
|
|
}
|
|
|
|
|
2016-03-14 14:17:33 +03:00
|
|
|
func (cn *Conn) IsStale(timeout time.Duration) bool {
|
|
|
|
return timeout > 0 && time.Since(cn.UsedAt) > timeout
|
2016-03-12 13:41:02 +03:00
|
|
|
}
|
|
|
|
|
2016-03-12 11:52:13 +03:00
|
|
|
func (cn *Conn) Read(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.ReadTimeout != 0 {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetReadDeadline(cn.UsedAt.Add(cn.ReadTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetReadDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.Read(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) Write(b []byte) (int, error) {
|
|
|
|
cn.UsedAt = time.Now()
|
|
|
|
if cn.WriteTimeout != 0 {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetWriteDeadline(cn.UsedAt.Add(cn.WriteTimeout))
|
2016-03-12 11:52:13 +03:00
|
|
|
} else {
|
2016-03-14 14:17:33 +03:00
|
|
|
cn.NetConn.SetWriteDeadline(noDeadline)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.Write(b)
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Conn) RemoteAddr() net.Addr {
|
2016-03-14 14:17:33 +03:00
|
|
|
return cn.NetConn.RemoteAddr()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|
|
|
|
|
2016-03-16 17:57:24 +03:00
|
|
|
func (cn *Conn) ReadN(n int) ([]byte, error) {
|
|
|
|
if d := n - cap(cn.Buf); d > 0 {
|
|
|
|
cn.Buf = cn.Buf[:cap(cn.Buf)]
|
|
|
|
cn.Buf = append(cn.Buf, make([]byte, d)...)
|
|
|
|
} else {
|
|
|
|
cn.Buf = cn.Buf[:n]
|
|
|
|
}
|
|
|
|
_, err := io.ReadFull(cn.Rd, cn.Buf)
|
|
|
|
return cn.Buf, err
|
|
|
|
}
|
|
|
|
|
2016-03-15 15:04:35 +03:00
|
|
|
func (cn *Conn) Close() error {
|
|
|
|
return cn.NetConn.Close()
|
2016-03-12 11:52:13 +03:00
|
|
|
}
|