]> Sergey Matveev's repositories - btrtrc.git/blob - conn_stats.go
Add connection read stats
[btrtrc.git] / conn_stats.go
1 package torrent
2
3 import (
4         "io"
5         "sync"
6
7         pp "github.com/anacrolix/torrent/peer_protocol"
8 )
9
10 type ConnStats struct {
11         // Torrent "piece" messages, or data chunks.
12         ChunksWritten int64 // Num piece messages sent.
13         ChunksRead    int64
14         // Total bytes on the wire. Includes handshakes and encryption.
15         BytesWritten int64
16         BytesRead    int64
17         // Data bytes, actual torrent data.
18         DataBytesWritten int64
19         DataBytesRead    int64
20 }
21
22 func (cs *ConnStats) wroteMsg(msg *pp.Message) {
23         switch msg.Type {
24         case pp.Piece:
25                 cs.ChunksWritten++
26                 cs.DataBytesWritten += int64(len(msg.Piece))
27         }
28 }
29
30 func (cs *ConnStats) readMsg(msg *pp.Message) {
31         switch msg.Type {
32         case pp.Piece:
33                 cs.ChunksRead++
34                 cs.DataBytesRead += int64(len(msg.Piece))
35         }
36 }
37
38 func (cs *ConnStats) wroteBytes(n int64) {
39         cs.BytesWritten += n
40 }
41
42 func (cs *ConnStats) readBytes(n int64) {
43         cs.BytesRead += n
44 }
45
46 type connStatsReadWriter struct {
47         rw io.ReadWriter
48         l  sync.Locker
49         c  *connection
50 }
51
52 func (me connStatsReadWriter) Write(b []byte) (n int, err error) {
53         n, err = me.rw.Write(b)
54         me.l.Lock()
55         me.c.wroteBytes(int64(n))
56         me.l.Unlock()
57         return
58 }
59
60 func (me connStatsReadWriter) Read(b []byte) (n int, err error) {
61         n, err = me.rw.Read(b)
62         me.l.Lock()
63         me.c.readBytes(int64(n))
64         me.l.Unlock()
65         return
66 }