Skip to content

Commit

Permalink
Optimize NewBufioReaderWithBytes
Browse files Browse the repository at this point in the history
  • Loading branch information
bddjr committed Dec 3, 2024
1 parent 98270bd commit db75a3a
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions src_bufio.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,34 @@ package hlfhr
import (
"bufio"
"io"
"reflect"
"unsafe"
)

const brMinBufSize = 16

const brFieldBufIndex = 0
const brFieldWIndex = 3

func NewBufioReaderWithBytes(buf []byte, contentLength int, rd io.Reader) *bufio.Reader {
br := &bufio.Reader{}
rv := reflect.ValueOf(br).Elem()

// fill buffer
if len(buf) < brMinBufSize {
nb := make([]byte, brMinBufSize)
copy(nb, buf)
buf = nb
// copy from bufio.Reader
type br struct {
buf []byte
rd io.Reader // reader provided by the client
r, w int // buf read and write positions
err error
lastByte int // last byte read for UnreadByte; -1 means invalid
lastRuneSize int // size of last rune read for UnreadRune; -1 means invalid
}
*(*[]byte)(unsafe.Pointer(rv.Field(brFieldBufIndex).UnsafeAddr())) = buf

// fill reader
br.Reset(rd)
// copy from bufio.minReadBufferSize
const minReadBufferSize = 16

// fill length
if contentLength > 0 {
*(*int)(unsafe.Pointer(rv.Field(brFieldWIndex).UnsafeAddr())) =
min(contentLength, len(buf))
if len(buf) < minReadBufferSize {
nb := make([]byte, minReadBufferSize)
copy(nb, buf)
buf = nb
}

return br
return (*bufio.Reader)(unsafe.Pointer(&br{
buf: buf,
rd: rd,
w: contentLength,
lastByte: -1,
lastRuneSize: -1,
}))
}

0 comments on commit db75a3a

Please sign in to comment.