2014-07-12 22:45:33 +00:00
|
|
|
// Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
|
|
|
|
// All rights reserved. Use of this source code is governed by an MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
2014-06-01 20:50:14 +00:00
|
|
|
|
2014-04-21 10:49:47 +00:00
|
|
|
package protocol
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"sync/atomic"
|
2014-07-28 09:31:22 +00:00
|
|
|
"time"
|
2014-04-21 10:49:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type countingReader struct {
|
|
|
|
io.Reader
|
2014-07-28 09:31:22 +00:00
|
|
|
tot uint64 // bytes
|
|
|
|
last int64 // unix nanos
|
2014-04-21 10:49:47 +00:00
|
|
|
}
|
|
|
|
|
2014-05-24 19:34:11 +00:00
|
|
|
var (
|
|
|
|
totalIncoming uint64
|
|
|
|
totalOutgoing uint64
|
|
|
|
)
|
|
|
|
|
2014-04-21 10:49:47 +00:00
|
|
|
func (c *countingReader) Read(bs []byte) (int, error) {
|
|
|
|
n, err := c.Reader.Read(bs)
|
|
|
|
atomic.AddUint64(&c.tot, uint64(n))
|
2014-05-24 19:34:11 +00:00
|
|
|
atomic.AddUint64(&totalIncoming, uint64(n))
|
2014-07-28 09:31:22 +00:00
|
|
|
atomic.StoreInt64(&c.last, time.Now().UnixNano())
|
2014-04-21 10:49:47 +00:00
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *countingReader) Tot() uint64 {
|
|
|
|
return atomic.LoadUint64(&c.tot)
|
|
|
|
}
|
|
|
|
|
2014-07-28 09:31:22 +00:00
|
|
|
func (c *countingReader) Last() time.Time {
|
|
|
|
return time.Unix(0, atomic.LoadInt64(&c.last))
|
|
|
|
}
|
|
|
|
|
2014-04-21 10:49:47 +00:00
|
|
|
type countingWriter struct {
|
|
|
|
io.Writer
|
2014-07-28 09:31:22 +00:00
|
|
|
tot uint64 // bytes
|
|
|
|
last int64 // unix nanos
|
2014-04-21 10:49:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *countingWriter) Write(bs []byte) (int, error) {
|
|
|
|
n, err := c.Writer.Write(bs)
|
|
|
|
atomic.AddUint64(&c.tot, uint64(n))
|
2014-05-24 19:34:11 +00:00
|
|
|
atomic.AddUint64(&totalOutgoing, uint64(n))
|
2014-07-28 09:31:22 +00:00
|
|
|
atomic.StoreInt64(&c.last, time.Now().UnixNano())
|
2014-04-21 10:49:47 +00:00
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *countingWriter) Tot() uint64 {
|
|
|
|
return atomic.LoadUint64(&c.tot)
|
|
|
|
}
|
2014-05-24 19:34:11 +00:00
|
|
|
|
2014-07-28 09:31:22 +00:00
|
|
|
func (c *countingWriter) Last() time.Time {
|
|
|
|
return time.Unix(0, atomic.LoadInt64(&c.last))
|
|
|
|
}
|
|
|
|
|
2014-05-24 19:34:11 +00:00
|
|
|
func TotalInOut() (uint64, uint64) {
|
|
|
|
return atomic.LoadUint64(&totalIncoming), atomic.LoadUint64(&totalOutgoing)
|
|
|
|
}
|