Skip to content

Commit

Permalink
Add Reader/Writer constructors with custom buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
VirrageS authored and philhofer committed Oct 21, 2020
1 parent 87c1ec4 commit 8825d3f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
5 changes: 5 additions & 0 deletions msgp/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ func NewReaderSize(r io.Reader, sz int) *Reader {
return &Reader{R: fwd.NewReaderSize(r, sz)}
}

// NewReaderBuf returns a *Reader with a provided buffer.
func NewReaderBuf(r io.Reader, buf []byte) *Reader {
return &Reader{R: fwd.NewReaderBuf(r, buf)}
}

// Reader wraps an io.Reader and provides
// methods to read MessagePack-encoded values
// from it. Readers are buffered.
Expand Down
24 changes: 20 additions & 4 deletions msgp/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import (
"time"
)

const (
// min buffer size for the writer
minWriterSize = 18
)

// Sizer is an interface implemented
// by types that can estimate their
// size when MessagePack encoded.
Expand Down Expand Up @@ -120,16 +125,27 @@ func NewWriter(w io.Writer) *Writer {

// NewWriterSize returns a writer with a custom buffer size.
func NewWriterSize(w io.Writer, sz int) *Writer {
// we must be able to require() 18
// we must be able to require() 'minWriterSize'
// contiguous bytes, so that is the
// practical minimum buffer size
if sz < 18 {
sz = 18
if sz < minWriterSize {
sz = minWriterSize
}
buf := make([]byte, sz)
return NewWriterBuf(w, buf)
}

// NewWriterBuf returns a writer with a provided buffer.
// 'buf' is not used when the capacity is smaller than 18,
// custom buffer is allocated instead.
func NewWriterBuf(w io.Writer, buf []byte) *Writer {
if cap(buf) < minWriterSize {
buf = make([]byte, minWriterSize)
}
buf = buf[:cap(buf)]
return &Writer{
w: w,
buf: make([]byte, sz),
buf: buf,
}
}

Expand Down

0 comments on commit 8825d3f

Please sign in to comment.