peer_protocol: Use faster form for Integer.{UnmarshalBinary,Read}
This commit is contained in:
parent
60a622ff4b
commit
73696fd215
|
@ -20,7 +20,7 @@ type Decoder struct {
|
|||
// io.EOF is returned if the source terminates cleanly on a message boundary.
|
||||
func (d *Decoder) Decode(msg *Message) (err error) {
|
||||
var length Integer
|
||||
err = length.ReadFrom(d.R)
|
||||
err = length.Read(d.R)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading message length: %w", err)
|
||||
}
|
||||
|
|
|
@ -1,27 +1,27 @@
|
|||
package peer_protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
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 {
|
||||
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
|
||||
n, err := r.Read(b[:])
|
||||
if n == 4 {
|
||||
*i = Integer(binary.BigEndian.Uint32(b[:]))
|
||||
return nil
|
||||
return i.UnmarshalBinary(b[:])
|
||||
}
|
||||
if err == nil {
|
||||
return io.ErrUnexpectedEOF
|
||||
|
|
Loading…
Reference in New Issue