Skip to content

Commit

Permalink
reduce buffer allocs
Browse files Browse the repository at this point in the history
  • Loading branch information
lxzan committed Aug 7, 2023
1 parent 7c1bb91 commit 9f0ea5b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
13 changes: 13 additions & 0 deletions internal/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
Expand Down Expand Up @@ -197,3 +198,15 @@ func ToBinaryNumber[T Integer](n T) T {
}
return x
}

type Buffer struct {
buf []byte
off int
lastRead int8
}

//go:nosplit
func ResetBuffer(b *bytes.Buffer, p []byte) {
buffer := (*Buffer)(unsafe.Pointer(b))
buffer.buf = p
}
8 changes: 8 additions & 0 deletions internal/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,11 @@ func TestGetIntersectionElem(t *testing.T) {
assert.Equal(t, "", GetIntersectionElem(b, nil))
}
}

func TestResetBuffer(t *testing.T) {
var buf = bytes.NewBufferString("hello")
var p = buf.Bytes()
p = append(p, "world"...)
ResetBuffer(buf, p)
assert.Equal(t, "helloworld", buf.String())
}
4 changes: 2 additions & 2 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"errors"
"fmt"

"github.com/lxzan/gws/internal"
)

Expand Down Expand Up @@ -109,7 +108,8 @@ func (c *Conn) readMessage() error {
}

if fin && opcode != OpcodeContinuation {
return c.emitMessage(&Message{index: index, Opcode: opcode, Data: bytes.NewBuffer(p)}, compressed)
internal.ResetBuffer(buf, p)
return c.emitMessage(&Message{index: index, Opcode: opcode, Data: buf}, compressed)
}

if !fin && opcode != OpcodeContinuation {
Expand Down

0 comments on commit 9f0ea5b

Please sign in to comment.