File: counting.go

package info (click to toggle)
syncthing 1.19.2~ds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 21,484 kB
  • sloc: javascript: 36,375; sh: 1,804; xml: 1,049; makefile: 67
file content (62 lines) | stat: -rw-r--r-- 1,401 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (C) 2014 The Protocol Authors.

package protocol

import (
	"io"
	"sync/atomic"
	"time"
)

type countingReader struct {
	io.Reader
	tot  int64 // bytes (atomic, must remain 64-bit aligned)
	last int64 // unix nanos (atomic, must remain 64-bit aligned)
}

var (
	totalIncoming int64
	totalOutgoing int64
)

func (c *countingReader) Read(bs []byte) (int, error) {
	n, err := c.Reader.Read(bs)
	atomic.AddInt64(&c.tot, int64(n))
	atomic.AddInt64(&totalIncoming, int64(n))
	atomic.StoreInt64(&c.last, time.Now().UnixNano())
	return n, err
}

func (c *countingReader) Tot() int64 {
	return atomic.LoadInt64(&c.tot)
}

func (c *countingReader) Last() time.Time {
	return time.Unix(0, atomic.LoadInt64(&c.last))
}

type countingWriter struct {
	io.Writer
	tot  int64 // bytes (atomic, must remain 64-bit aligned)
	last int64 // unix nanos (atomic, must remain 64-bit aligned)
}

func (c *countingWriter) Write(bs []byte) (int, error) {
	n, err := c.Writer.Write(bs)
	atomic.AddInt64(&c.tot, int64(n))
	atomic.AddInt64(&totalOutgoing, int64(n))
	atomic.StoreInt64(&c.last, time.Now().UnixNano())
	return n, err
}

func (c *countingWriter) Tot() int64 {
	return atomic.LoadInt64(&c.tot)
}

func (c *countingWriter) Last() time.Time {
	return time.Unix(0, atomic.LoadInt64(&c.last))
}

func TotalInOut() (int64, int64) {
	return atomic.LoadInt64(&totalIncoming), atomic.LoadInt64(&totalOutgoing)
}