Skip to content
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

stop allocating on every byte read (for CIDs and varints) #220

Merged
merged 2 commits into from
Sep 7, 2021
Merged
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
29 changes: 16 additions & 13 deletions v2/internal/io/converter.go
Original file line number Diff line number Diff line change
@@ -17,15 +17,21 @@ var (
type (
readerPlusByte struct {
io.Reader

byteBuf [1]byte // escapes via io.Reader.Read; preallocate
}

readSeekerPlusByte struct {
io.ReadSeeker

byteBuf [1]byte // escapes via io.Reader.Read; preallocate
}

discardingReadSeekerPlusByte struct {
io.Reader
offset int64

byteBuf [1]byte // escapes via io.Reader.Read; preallocate
}

ByteReadSeeker interface {
@@ -43,15 +49,15 @@ func ToByteReader(r io.Reader) io.ByteReader {
if br, ok := r.(io.ByteReader); ok {
return br
}
return &readerPlusByte{r}
return &readerPlusByte{Reader: r}
}

func ToByteReadSeeker(r io.Reader) ByteReadSeeker {
if brs, ok := r.(ByteReadSeeker); ok {
return brs
}
if rs, ok := r.(io.ReadSeeker); ok {
return &readSeekerPlusByte{rs}
return &readSeekerPlusByte{ReadSeeker: rs}
}
return &discardingReadSeekerPlusByte{Reader: r}
}
@@ -63,16 +69,19 @@ func ToReaderAt(rs io.ReadSeeker) io.ReaderAt {
return &readSeekerAt{rs: rs}
}

func (rb readerPlusByte) ReadByte() (byte, error) {
return readByte(rb)
func (rb *readerPlusByte) ReadByte() (byte, error) {
_, err := io.ReadFull(rb, rb.byteBuf[:])
return rb.byteBuf[0], err
}

func (rsb readSeekerPlusByte) ReadByte() (byte, error) {
return readByte(rsb)
func (rsb *readSeekerPlusByte) ReadByte() (byte, error) {
_, err := io.ReadFull(rsb, rsb.byteBuf[:])
return rsb.byteBuf[0], err
}

func (drsb *discardingReadSeekerPlusByte) ReadByte() (byte, error) {
return readByte(drsb)
_, err := io.ReadFull(drsb, drsb.byteBuf[:])
return drsb.byteBuf[0], err
}

func (drsb *discardingReadSeekerPlusByte) Read(p []byte) (read int, err error) {
@@ -98,12 +107,6 @@ func (drsb *discardingReadSeekerPlusByte) Seek(offset int64, whence int) (int64,
}
}

func readByte(r io.Reader) (byte, error) {
var p [1]byte
_, err := io.ReadFull(r, p[:])
return p[0], err
}

func (rsa *readSeekerAt) ReadAt(p []byte, off int64) (n int, err error) {
rsa.mu.Lock()
defer rsa.mu.Unlock()