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

Optimize discarding in ScanForLinks #36

Merged
merged 1 commit into from
Aug 11, 2020
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: 28 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,33 @@ import (
const maxCidLength = 100
const maxHeaderSize = 9

// discard is a helper function to discard data from a reader, special-casing
// the most common readers we encounter in this library for a significant
// performance boost.
func discard(br io.Reader, n int) error {
switch r := br.(type) {
case *bytes.Buffer:
buf := r.Next(n)
if len(buf) < n {
return io.ErrUnexpectedEOF
}
return nil
case *bytes.Reader:
if r.Len() < n {
_, _ = r.Seek(0, io.SeekEnd)
return io.ErrUnexpectedEOF
}
_, err := r.Seek(int64(n), io.SeekCurrent)
return err
case *bufio.Reader:
_, err := r.Discard(n)
return err
default:
_, err := io.CopyN(ioutil.Discard, br, int64(n))
return err
}
}

func ScanForLinks(br io.Reader, cb func(cid.Cid)) error {
scratch := make([]byte, maxCidLength)
for remaining := uint64(1); remaining > 0; remaining-- {
Expand All @@ -27,7 +54,7 @@ func ScanForLinks(br io.Reader, cb func(cid.Cid)) error {
switch maj {
case MajUnsignedInt, MajNegativeInt, MajOther:
case MajByteString, MajTextString:
_, err := io.CopyN(ioutil.Discard, br, int64(extra))
err := discard(br, int(extra))
if err != nil {
return err
}
Expand Down