nps/lib/conn/snappy.go

47 lines
825 B
Go
Raw Normal View History

2019-02-09 01:07:47 -08:00
package conn
import (
"github.com/cnlh/nps/lib/pool"
2019-02-16 04:43:26 -08:00
"github.com/cnlh/nps/vender/github.com/golang/snappy"
"io"
2019-02-09 01:07:47 -08:00
)
type SnappyConn struct {
2019-03-28 19:41:57 -07:00
w *snappy.Writer
r *snappy.Reader
2019-02-09 01:07:47 -08:00
}
2019-03-28 19:44:12 -07:00
func NewSnappyConn(conn io.ReadWriteCloser) *SnappyConn {
2019-02-09 01:07:47 -08:00
c := new(SnappyConn)
c.w = snappy.NewBufferedWriter(conn)
c.r = snappy.NewReader(conn)
return c
}
2019-02-17 09:05:05 -08:00
//snappy压缩写
2019-02-09 01:07:47 -08:00
func (s *SnappyConn) Write(b []byte) (n int, err error) {
2019-02-17 09:05:05 -08:00
if n, err = s.w.Write(b); err != nil {
2019-02-09 01:07:47 -08:00
return
}
if err = s.w.Flush(); err != nil {
return
}
return
}
2019-02-17 09:05:05 -08:00
//snappy压缩读
2019-02-09 01:07:47 -08:00
func (s *SnappyConn) Read(b []byte) (n int, err error) {
buf := pool.BufPool.Get().([]byte)
defer pool.BufPool.Put(buf)
if n, err = s.r.Read(buf); err != nil {
return
}
2019-02-17 09:05:05 -08:00
copy(b, buf[:n])
2019-02-09 01:07:47 -08:00
return
}
func (s *SnappyConn) Close() error {
s.w.Close()
return s.w.Close()
}