10 qt "github.com/frankban/quicktest"
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
15 func BenchmarkDecodePieces(t *testing.B) {
16 const pieceLen = 1 << 14
21 Piece: make([]byte, pieceLen),
23 b := inputMsg.MustMarshalBinary()
24 t.SetBytes(int64(len(b)))
26 // Try to somewhat emulate what torrent.Client would do. But the goal is to get decoding as fast
27 // as possible and let consumers apply their own adjustments.
29 R: bufio.NewReaderSize(&r, 1<<10),
32 New: func() interface{} {
33 b := make([]byte, pieceLen)
41 for i := 0; i < t.N; i += 1 {
48 // This is very expensive, and should be discovered in tests rather than a benchmark.
50 c.Assert(msg, qt.DeepEquals, inputMsg)
53 d.Pool.Put(&msg.Piece)
57 func TestDecodeShortPieceEOF(t *testing.T) {
60 w.Write(Message{Type: Piece, Piece: make([]byte, 1)}.MustMarshalBinary())
64 R: bufio.NewReader(r),
66 Pool: &sync.Pool{New: func() interface{} {
72 require.NoError(t, d.Decode(&m))
73 assert.Len(t, m.Piece, 1)
74 assert.ErrorIs(t, d.Decode(&m), io.EOF)
77 func TestDecodeOverlongPiece(t *testing.T) {
80 w.Write(Message{Type: Piece, Piece: make([]byte, 3)}.MustMarshalBinary())
84 R: bufio.NewReader(r),
86 Pool: &sync.Pool{New: func() interface{} {
92 require.Error(t, d.Decode(&m))