Skip to content

Commit

Permalink
fix: optimize utility functions for CborReader
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Mar 22, 2022
1 parent da8b264 commit 174d96c
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const (
// 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 {
func discard(br io.Reader, n int) (_err error) {
// If we're expecting no bytes, don't even try to read. Otherwise, we may read an EOF.
if n == 0 {
return nil
Expand All @@ -47,12 +47,45 @@ func discard(br io.Reader, n int) error {
}
_, err := r.Seek(int64(n), io.SeekCurrent)
return err
case *peeker:
// Discard the buffered byte, if any.
discarded := false

defer func() {
if discarded && _err == io.EOF {
_err = io.ErrUnexpectedEOF
}
}()

if r.peekState == peekUnread {
r.peekState = peekSet
n--
discarded = true
}
switch n {
case 0:
// Nothing else to read.
return nil
case 1:
// Only read one byte.
default:
// Read all but the last byte
err := discard(r.reader, n-1)
if err != nil {
return err
}
discarded = true
}
_, err := r.ReadByte()
return err
case *bufio.Reader:
discarded, err := r.Discard(n)
if discarded != 0 && discarded < n && err == io.EOF {
return io.ErrUnexpectedEOF
}
return err
case *CborReader:
return discard(r.r, n)
default:
discarded, err := io.CopyN(ioutil.Discard, br, int64(n))
if discarded != 0 && discarded < int64(n) && err == io.EOF {
Expand Down Expand Up @@ -246,6 +279,8 @@ func readByte(r io.Reader) (byte, error) {
return r.ReadByte()
case *peeker:
return r.ReadByte()
case *CborReader:
return r.ReadByte()
case io.ByteReader:
return r.ReadByte()
}
Expand Down Expand Up @@ -331,6 +366,8 @@ func readByteBuf(r io.Reader, scratch []byte) (byte, error) {
return r.ReadByte()
case *peeker:
return r.ReadByte()
case *CborReader:
return r.ReadByte()
case io.ByteReader:
return r.ReadByte()
}
Expand Down

0 comments on commit 174d96c

Please sign in to comment.