Use peerID type more, and make its Stringer output nicer

This commit is contained in:
Matt Joiner 2018-01-06 12:34:31 +11:00
parent a0f8f246e5
commit c44ee5fec4
5 changed files with 39 additions and 4 deletions

View File

@ -43,7 +43,7 @@ type Client struct {
config Config
halfOpenLimit int
peerID [20]byte
peerID peerID
defaultStorage *storage.Client
onClose []func()
tcpListener net.Listener

View File

@ -73,7 +73,7 @@ type connection struct {
sentHaves []bool
// Stuff controlled by the remote peer.
PeerID [20]byte
PeerID peerID
PeerInterested bool
PeerChoked bool
PeerRequests map[request]struct{}
@ -194,7 +194,7 @@ func (cn *connection) String() string {
func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
// \t isn't preserved in <pre> blocks?
fmt.Fprintf(w, "%+q: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
fmt.Fprintf(w, "%-40s: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
fmt.Fprintf(w, " last msg: %s, connected: %s, last useful chunk: %s\n",
eventAgeString(cn.lastMessageReceived),
eventAgeString(cn.completedHandshake),

View File

@ -36,7 +36,6 @@ func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
type (
peerExtensionBytes [8]byte
peerID [20]byte
)
func (pex peerExtensionBytes) SupportsExtended() bool {

14
peerid.go Normal file
View File

@ -0,0 +1,14 @@
package torrent
import (
"encoding/hex"
)
type peerID [20]byte
func (me peerID) String() string {
if me[0] == '-' && me[7] == '-' {
return string(me[:8]) + hex.EncodeToString(me[8:])
}
return hex.EncodeToString(me[:])
}

22
peerid_test.go Normal file
View File

@ -0,0 +1,22 @@
package torrent
import (
"testing"
"github.com/anacrolix/missinggo"
"github.com/stretchr/testify/assert"
)
func TestPeerIdString(t *testing.T) {
for _, _case := range []struct {
id string
s string
}{
{"\x1cNJ}\x9c\xc7\xc4o\x94<\x9b\x8c\xc2!I\x1c\a\xec\x98n", "1c4e4a7d9cc7c46f943c9b8cc221491c07ec986e"},
{"-FD51W\xe4-LaZMk0N8ZLA7", "-FD51W\xe4-4c615a4d6b304e385a4c4137"},
} {
var pi peerID
missinggo.CopyExact(&pi, _case.id)
assert.EqualValues(t, _case.s, pi.String())
}
}