2
0
mirror of synced 2025-02-24 06:38:14 +00:00

Drop xerrors and reflection dependency

Nothing wrong with missinggo.CopyExact -- but fewer dependencies is better IMO.  Also changed String() to use a consistent receiver name -- not a big deal.
This commit is contained in:
YenForYang 2021-09-04 01:30:14 -05:00 committed by Matt Joiner
parent c76bb42c07
commit 99ba75f458

View File

@ -2,12 +2,11 @@ package peer_protocol
import ( import (
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"io" "io"
"strconv"
"golang.org/x/xerrors"
"github.com/anacrolix/missinggo/v2"
"github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/metainfo"
) )
@ -34,8 +33,8 @@ type (
PeerExtensionBits [8]byte PeerExtensionBits [8]byte
) )
func (me PeerExtensionBits) String() string { func (pex PeerExtensionBits) String() string {
return hex.EncodeToString(me[:]) return hex.EncodeToString(pex[:])
} }
func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) { func NewPeerExtensionBytes(bits ...ExtensionBit) (ret PeerExtensionBits) {
@ -98,7 +97,7 @@ func Handshake(
// Wait until writes complete before returning from handshake. // Wait until writes complete before returning from handshake.
err = <-writeDone err = <-writeDone
if err != nil { if err != nil {
err = fmt.Errorf("error writing: %s", err) err = fmt.Errorf("error writing: %w", err)
} }
}() }()
@ -119,16 +118,21 @@ func Handshake(
var b [68]byte var b [68]byte
_, err = io.ReadFull(sock, b[:68]) _, err = io.ReadFull(sock, b[:68])
if err != nil { if err != nil {
err = xerrors.Errorf("while reading: %w", err) return res, fmt.Errorf("while reading: %w", err)
return
} }
if string(b[:20]) != Protocol { if string(b[:20]) != Protocol {
err = xerrors.Errorf("unexpected protocol string") return res, errors.New("unexpected protocol string")
return
} }
missinggo.CopyExact(&res.PeerExtensionBits, b[20:28])
missinggo.CopyExact(&res.Hash, b[28:48]) copyExact := func(dst []byte, src []byte) {
missinggo.CopyExact(&res.PeerID, b[48:68]) if dstLen, srcLen := uint64(len(dst)), uint64(len(src)); dstLen != srcLen {
panic("dst len " + strconv.FormatUint(dstLen,10) + " != src len " + strconv.FormatUint(srcLen,10))
}
copy(dst, src)
}
copyExact(res.PeerExtensionBits[:], b[20:28])
copyExact(res.Hash[:], b[28:48])
copyExact(res.PeerID[:], b[48:68])
// peerExtensions.Add(res.PeerExtensionBits.String(), 1) // peerExtensions.Add(res.PeerExtensionBits.String(), 1)
// TODO: Maybe we can just drop peers here if we're not interested. This // TODO: Maybe we can just drop peers here if we're not interested. This