Files
syncthing/lib/protocol/counting.go
T

59 lines
1.1 KiB
Go
Raw Normal View History

2015-01-13 13:31:14 +01:00
// Copyright (C) 2014 The Protocol Authors.
2014-09-22 21:42:11 +02:00
package protocol
import (
"io"
"sync/atomic"
"time"
)
type countingReader struct {
io.Reader
2023-02-07 12:07:34 +01:00
tot atomic.Int64 // bytes
last atomic.Int64 // unix nanos
2014-09-22 21:42:11 +02:00
}
var (
2023-02-07 12:07:34 +01:00
totalIncoming atomic.Int64
totalOutgoing atomic.Int64
2014-09-22 21:42:11 +02:00
)
func (c *countingReader) Read(bs []byte) (int, error) {
n, err := c.Reader.Read(bs)
2023-02-07 12:07:34 +01:00
c.tot.Add(int64(n))
totalIncoming.Add(int64(n))
c.last.Store(time.Now().UnixNano())
2014-09-22 21:42:11 +02:00
return n, err
}
2023-02-07 12:07:34 +01:00
func (c *countingReader) Tot() int64 { return c.tot.Load() }
2014-09-22 21:42:11 +02:00
func (c *countingReader) Last() time.Time {
2023-02-07 12:07:34 +01:00
return time.Unix(0, c.last.Load())
2014-09-22 21:42:11 +02:00
}
type countingWriter struct {
io.Writer
2023-02-07 12:07:34 +01:00
tot atomic.Int64 // bytes
last atomic.Int64 // unix nanos
2014-09-22 21:42:11 +02:00
}
func (c *countingWriter) Write(bs []byte) (int, error) {
n, err := c.Writer.Write(bs)
2023-02-07 12:07:34 +01:00
c.tot.Add(int64(n))
totalOutgoing.Add(int64(n))
c.last.Store(time.Now().UnixNano())
2014-09-22 21:42:11 +02:00
return n, err
}
2023-02-07 12:07:34 +01:00
func (c *countingWriter) Tot() int64 { return c.tot.Load() }
2014-09-22 21:42:11 +02:00
func (c *countingWriter) Last() time.Time {
2023-02-07 12:07:34 +01:00
return time.Unix(0, c.last.Load())
2014-09-22 21:42:11 +02:00
}
2015-01-18 01:26:52 +01:00
func TotalInOut() (int64, int64) {
2023-02-07 12:07:34 +01:00
return totalIncoming.Load(), totalOutgoing.Load()
2014-09-22 21:42:11 +02:00
}