Skip to content

Reuse buffer #475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions share/cnet/conn_ws.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cnet

import (
"bytes"
"net"
"time"

Expand All @@ -9,41 +10,41 @@ 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 {
return 0, err
}

//copy src->dest
var n int
if len(src) > ldst {
//copy as much as possible of src into dst
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)
Expand Down