2014-07-03 23:41:46 +08:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
2014-08-21 19:07:44 +08:00
|
|
|
"bytes"
|
|
|
|
"encoding"
|
|
|
|
"encoding/binary"
|
2014-11-17 03:05:19 +08:00
|
|
|
"fmt"
|
2015-03-27 12:12:15 +08:00
|
|
|
"io"
|
2014-11-17 03:05:19 +08:00
|
|
|
|
2015-04-27 12:55:01 +08:00
|
|
|
"github.com/anacrolix/torrent/bencode"
|
2014-07-03 23:41:46 +08:00
|
|
|
)
|
|
|
|
|
2014-08-21 19:07:44 +08:00
|
|
|
type CompactPeers []CompactPeer
|
2014-07-03 23:41:46 +08:00
|
|
|
|
|
|
|
func (me *CompactPeers) UnmarshalBencode(bb []byte) (err error) {
|
|
|
|
var b []byte
|
|
|
|
err = bencode.Unmarshal(bb, &b)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = me.UnmarshalBinary(b)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *CompactPeers) UnmarshalBinary(b []byte) (err error) {
|
|
|
|
for i := 0; i < len(b); i += 6 {
|
2014-08-21 19:07:44 +08:00
|
|
|
var p CompactPeer
|
2014-07-03 23:41:46 +08:00
|
|
|
err = p.UnmarshalBinary([]byte(b[i : i+6]))
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
*me = append(*me, p)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2014-08-21 19:07:44 +08:00
|
|
|
|
2015-03-27 12:12:15 +08:00
|
|
|
func (me CompactPeers) WriteBinary(w io.Writer) error {
|
|
|
|
return binary.Write(w, binary.BigEndian, me)
|
|
|
|
}
|
|
|
|
|
2014-08-21 19:07:44 +08:00
|
|
|
type CompactPeer struct {
|
|
|
|
IP [4]byte
|
|
|
|
Port uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ encoding.BinaryUnmarshaler = &CompactPeer{}
|
|
|
|
|
|
|
|
func (cp *CompactPeer) UnmarshalBinary(b []byte) (err error) {
|
2014-11-17 03:05:19 +08:00
|
|
|
r := bytes.NewReader(b)
|
|
|
|
err = binary.Read(r, binary.BigEndian, cp)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if r.Len() != 0 {
|
|
|
|
err = fmt.Errorf("%d bytes unused", r.Len())
|
|
|
|
}
|
2014-08-21 19:07:44 +08:00
|
|
|
return
|
|
|
|
}
|