From 64ce9457013e77deb62c325250ba46a741c0b321 Mon Sep 17 00:00:00 2001 From: Bjoern Kalkbrenner Date: Wed, 18 Sep 2024 20:06:50 +0200 Subject: [PATCH] fix: reuse buffer to reduce memory usage: https://github.com/jpillora/chisel/pull/475 --- share/cnet/conn_ws.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/share/cnet/conn_ws.go b/share/cnet/conn_ws.go index 9639e991..44ac44e9 100644 --- a/share/cnet/conn_ws.go +++ b/share/cnet/conn_ws.go @@ -1,6 +1,7 @@ package cnet import ( + "bytes" "net" "time" @@ -9,26 +10,27 @@ import ( type wsConn struct { *websocket.Conn - buff []byte + buff *bytes.Buffer } -//NewWebSocketConn converts a websocket.Conn into a net.Conn +// NewWebSocketConn converts a websocket.Conn into a net.Conn func NewWebSocketConn(websocketConn *websocket.Conn) net.Conn { c := wsConn{ Conn: websocketConn, + buff: &bytes.Buffer{}, } return &c } -//Read is not threadsafe though thats okay since there -//should never be more than one reader +// Read is not threadsafe though thats okay since there +// should never be more than one reader func (c *wsConn) Read(dst []byte) (int, error) { ldst := len(dst) //use buffer or read new message var src []byte - if len(c.buff) > 0 { - src = c.buff - c.buff = nil + if c.buff.Len() > 0 { + src = c.buff.Bytes() + c.buff.Reset() } else if _, msg, err := c.Conn.ReadMessage(); err == nil { src = msg } else { @@ -41,9 +43,7 @@ func (c *wsConn) Read(dst []byte) (int, error) { n = copy(dst, src[:ldst]) //copy remainder into buffer r := src[ldst:] - lr := len(r) - c.buff = make([]byte, lr) - copy(c.buff, r) + c.buff.Write(r) } else { //copy all of src into dst n = copy(dst, src)