Merge pull request #208 from mrd0ll4r/refactor-udp-buffers

udp: use free list for response buffers
This commit is contained in:
Jimmy Zelinskie 2016-09-05 12:21:56 -04:00 committed by GitHub
commit f15ae55b3a

View file

@ -1,7 +1,6 @@
package udp
import (
"bytes"
"encoding/binary"
"fmt"
"io"
@ -17,11 +16,12 @@ func WriteError(w io.Writer, txID []byte, err error) {
err = fmt.Errorf("internal error occurred: %s", err.Error())
}
var buf bytes.Buffer
writeHeader(&buf, txID, errorActionID)
buf := newBuffer()
writeHeader(buf, txID, errorActionID)
buf.WriteString(err.Error())
buf.WriteRune('\000')
w.Write(buf.Bytes())
buf.free()
}
// WriteAnnounce encodes an announce response according to BEP 15.
@ -29,16 +29,16 @@ func WriteError(w io.Writer, txID []byte, err error) {
// whether v6 is set. The action ID will be 4, according to
// http://opentracker.blog.h3q.com/2007/12/28/the-ipv6-situation/.
func WriteAnnounce(w io.Writer, txID []byte, resp *bittorrent.AnnounceResponse, v6 bool) {
var buf bytes.Buffer
buf := newBuffer()
if v6 {
writeHeader(&buf, txID, announceV6ActionID)
writeHeader(buf, txID, announceV6ActionID)
} else {
writeHeader(&buf, txID, announceActionID)
writeHeader(buf, txID, announceActionID)
}
binary.Write(&buf, binary.BigEndian, uint32(resp.Interval/time.Second))
binary.Write(&buf, binary.BigEndian, uint32(resp.Incomplete))
binary.Write(&buf, binary.BigEndian, uint32(resp.Complete))
binary.Write(buf, binary.BigEndian, uint32(resp.Interval/time.Second))
binary.Write(buf, binary.BigEndian, uint32(resp.Incomplete))
binary.Write(buf, binary.BigEndian, uint32(resp.Complete))
peers := resp.IPv4Peers
if v6 {
@ -47,35 +47,38 @@ func WriteAnnounce(w io.Writer, txID []byte, resp *bittorrent.AnnounceResponse,
for _, peer := range peers {
buf.Write(peer.IP)
binary.Write(&buf, binary.BigEndian, peer.Port)
binary.Write(buf, binary.BigEndian, peer.Port)
}
w.Write(buf.Bytes())
buf.free()
}
// WriteScrape encodes a scrape response according to BEP 15.
func WriteScrape(w io.Writer, txID []byte, resp *bittorrent.ScrapeResponse) {
var buf bytes.Buffer
buf := newBuffer()
writeHeader(&buf, txID, scrapeActionID)
writeHeader(buf, txID, scrapeActionID)
for _, scrape := range resp.Files {
binary.Write(&buf, binary.BigEndian, scrape.Complete)
binary.Write(&buf, binary.BigEndian, scrape.Snatches)
binary.Write(&buf, binary.BigEndian, scrape.Incomplete)
binary.Write(buf, binary.BigEndian, scrape.Complete)
binary.Write(buf, binary.BigEndian, scrape.Snatches)
binary.Write(buf, binary.BigEndian, scrape.Incomplete)
}
w.Write(buf.Bytes())
buf.free()
}
// WriteConnectionID encodes a new connection response according to BEP 15.
func WriteConnectionID(w io.Writer, txID, connID []byte) {
var buf bytes.Buffer
buf := newBuffer()
writeHeader(&buf, txID, connectActionID)
writeHeader(buf, txID, connectActionID)
buf.Write(connID)
w.Write(buf.Bytes())
buf.free()
}
// writeHeader writes the action and transaction ID to the provided response