From a73c423c8a429fd698ec9eaa1c05ca363e4b36bf Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Wed, 5 Oct 2022 13:18:08 -0700 Subject: [PATCH] net/tunstats: add Counts.Add (#5848) The Counts.Add method merges two Counts together. Signed-off-by: Joe Tsai --- net/tunstats/stats.go | 9 +++++++++ net/tunstats/stats_test.go | 9 ++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/net/tunstats/stats.go b/net/tunstats/stats.go index cbc6a0820..d2e17cd96 100644 --- a/net/tunstats/stats.go +++ b/net/tunstats/stats.go @@ -29,6 +29,15 @@ type Counts struct { RxBytes uint64 `json:"rxBytes,omitempty"` } +// Add adds the counts from both c1 and c2. +func (c1 Counts) Add(c2 Counts) Counts { + c1.TxPackets += c2.TxPackets + c1.TxBytes += c2.TxBytes + c1.RxPackets += c2.RxPackets + c1.RxBytes += c2.RxBytes + return c1 +} + // UpdateTx updates the counters for a transmitted IP packet // The source and destination of the packet directly correspond with // the source and destination in flowtrack.Tuple. diff --git a/net/tunstats/stats_test.go b/net/tunstats/stats_test.go index fadcd419b..ce9a37d1d 100644 --- a/net/tunstats/stats_test.go +++ b/net/tunstats/stats_test.go @@ -111,13 +111,8 @@ func TestConcurrent(t *testing.T) { func mergeMaps(dst map[flowtrack.Tuple]Counts, srcs ...map[flowtrack.Tuple]Counts) { for _, src := range srcs { - for tuple, cntsSrc := range src { - cntsDst := dst[tuple] - cntsDst.TxPackets += cntsSrc.TxPackets - cntsDst.TxBytes += cntsSrc.TxBytes - cntsDst.RxPackets += cntsSrc.RxPackets - cntsDst.RxBytes += cntsSrc.RxBytes - dst[tuple] = cntsDst + for tuple, cnts := range src { + dst[tuple] = dst[tuple].Add(cnts) } } }