From 2c387cc21344ec69f648661d635afb04ac70aa8e Mon Sep 17 00:00:00 2001 From: 9seconds Date: Mon, 2 Jul 2018 10:33:25 +0300 Subject: [PATCH] Add bytesrwc --- mtproto/{bufferpool => }/bufferpool.go | 6 ++-- mtproto/rpc/rpc_proxy_request.go | 6 ++-- mtproto/rwc.go | 48 ++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 6 deletions(-) rename mtproto/{bufferpool => }/bufferpool.go (78%) create mode 100644 mtproto/rwc.go diff --git a/mtproto/bufferpool/bufferpool.go b/mtproto/bufferpool.go similarity index 78% rename from mtproto/bufferpool/bufferpool.go rename to mtproto/bufferpool.go index f58a88e..2c8c246 100644 --- a/mtproto/bufferpool/bufferpool.go +++ b/mtproto/bufferpool.go @@ -1,4 +1,4 @@ -package bufferpool +package mtproto import ( "bytes" @@ -9,14 +9,14 @@ const bufferPoolSize = 4 * 1024 var bufferPool sync.Pool -func Get() *bytes.Buffer { +func GetBuffer() *bytes.Buffer { buf := bufferPool.Get().(*bytes.Buffer) buf.Reset() return buf } -func Return(buf *bytes.Buffer) { +func ReturnBuffer(buf *bytes.Buffer) { bufferPool.Put(buf) } diff --git a/mtproto/rpc/rpc_proxy_request.go b/mtproto/rpc/rpc_proxy_request.go index f9df232..e7d0a4a 100644 --- a/mtproto/rpc/rpc_proxy_request.go +++ b/mtproto/rpc/rpc_proxy_request.go @@ -6,9 +6,9 @@ import ( "encoding/binary" "net" - "github.com/9seconds/mtg/mtproto" - "github.com/9seconds/mtg/mtproto/bufferpool" "github.com/juju/errors" + + "github.com/9seconds/mtg/mtproto" ) const ( @@ -33,7 +33,7 @@ type RPCProxyRequest struct { } func (r *RPCProxyRequest) Bytes() *bytes.Buffer { - buf := bufferpool.Get() + buf := mtproto.GetBuffer() flags := r.Flags if r.Extras.QuickAck { diff --git a/mtproto/rwc.go b/mtproto/rwc.go new file mode 100644 index 0000000..ad14b8c --- /dev/null +++ b/mtproto/rwc.go @@ -0,0 +1,48 @@ +package mtproto + +import ( + "bytes" + "io" +) + +type BytesRWC interface { + Write(*bytes.Buffer) (int, error) + Read([]byte) (int, error) + Close() error +} + +type StartBytesRWC struct { + conn BytesRWC +} + +func (s *StartBytesRWC) Write(p []byte) (int, error) { + buf := GetBuffer() + buf.Write(p) + defer ReturnBuffer(buf) + + return s.conn.Write(buf) +} + +func (s *StartBytesRWC) Read(p []byte) (int, error) { + return s.conn.Read(p) +} + +func (s *StartBytesRWC) Close() error { + return s.conn.Close() +} + +type FinishBytesRWC struct { + conn io.ReadWriteCloser +} + +func (f *FinishBytesRWC) Write(buf *bytes.Buffer) (int, error) { + return f.conn.Write(buf.Bytes()) +} + +func (f *FinishBytesRWC) Read(p []byte) (int, error) { + return f.conn.Read(p) +} + +func (f *FinishBytesRWC) Close() error { + return f.conn.Close() +}