From bc4e624732bd51c0dd1e9529cf228e8c23127732 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 13 Apr 2024 13:40:59 +0200 Subject: Adding upstream version 1.1.1. Signed-off-by: Daniel Baumann --- pkg/com/counter.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 pkg/com/counter.go (limited to 'pkg/com/counter.go') diff --git a/pkg/com/counter.go b/pkg/com/counter.go new file mode 100644 index 0000000..52f9f7f --- /dev/null +++ b/pkg/com/counter.go @@ -0,0 +1,48 @@ +package com + +import ( + "sync" + "sync/atomic" +) + +// Counter implements an atomic counter. +type Counter struct { + value uint64 + mu sync.Mutex // Protects total. + total uint64 +} + +// Add adds the given delta to the counter. +func (c *Counter) Add(delta uint64) { + atomic.AddUint64(&c.value, delta) +} + +// Inc increments the counter by one. +func (c *Counter) Inc() { + c.Add(1) +} + +// Reset resets the counter to 0 and returns its previous value. +// Does not reset the total value returned from Total. +func (c *Counter) Reset() uint64 { + c.mu.Lock() + defer c.mu.Unlock() + + v := atomic.SwapUint64(&c.value, 0) + c.total += v + + return v +} + +// Total returns the total counter value. +func (c *Counter) Total() uint64 { + c.mu.Lock() + defer c.mu.Unlock() + + return c.total + c.Val() +} + +// Val returns the current counter value. +func (c *Counter) Val() uint64 { + return atomic.LoadUint64(&c.value) +} -- cgit v1.2.3