peer_protocol: Use faster form for Integer.{UnmarshalBinary,Read}

This commit is contained in:
Matt Joiner 2021-09-30 10:24:03 +10:00
parent 60a622ff4b
commit 73696fd215
2 changed files with 10 additions and 10 deletions

View File

@ -20,7 +20,7 @@ type Decoder struct {
// io.EOF is returned if the source terminates cleanly on a message boundary. // io.EOF is returned if the source terminates cleanly on a message boundary.
func (d *Decoder) Decode(msg *Message) (err error) { func (d *Decoder) Decode(msg *Message) (err error) {
var length Integer var length Integer
err = length.ReadFrom(d.R) err = length.Read(d.R)
if err != nil { if err != nil {
return fmt.Errorf("reading message length: %w", err) return fmt.Errorf("reading message length: %w", err)
} }

View File

@ -1,27 +1,27 @@
package peer_protocol package peer_protocol
import ( import (
"bytes"
"encoding/binary" "encoding/binary"
"io" "io"
"github.com/pkg/errors"
) )
type Integer uint32 type Integer uint32
func (i *Integer) Read(r io.Reader) error {
return binary.Read(r, binary.BigEndian, i)
}
func (i *Integer) UnmarshalBinary(b []byte) error { func (i *Integer) UnmarshalBinary(b []byte) error {
return i.Read(bytes.NewReader(b)) if len(b) != 4 {
return errors.New("expected 4 bytes")
}
*i = Integer(binary.BigEndian.Uint32(b))
return nil
} }
func (i *Integer) ReadFrom(r io.Reader) error { func (i *Integer) Read(r io.Reader) error {
var b [4]byte var b [4]byte
n, err := r.Read(b[:]) n, err := r.Read(b[:])
if n == 4 { if n == 4 {
*i = Integer(binary.BigEndian.Uint32(b[:])) return i.UnmarshalBinary(b[:])
return nil
} }
if err == nil { if err == nil {
return io.ErrUnexpectedEOF return io.ErrUnexpectedEOF