From 0d765075e07b414a3940d643db273332ae79b404 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 25 Aug 2023 15:23:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20counter=20=E5=8C=85=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=AE=80=E5=8D=95=E5=8E=BB=E9=87=8D=E8=AE=A1=E6=95=B0=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/counter/simple_deduplication.go | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 utils/counter/simple_deduplication.go diff --git a/utils/counter/simple_deduplication.go b/utils/counter/simple_deduplication.go new file mode 100644 index 0000000..8819737 --- /dev/null +++ b/utils/counter/simple_deduplication.go @@ -0,0 +1,39 @@ +package counter + +import ( + "github.com/kercylan98/minotaur/utils/generic" + "sync" +) + +// NewSimpleDeduplication 创建一个简单去重计数器 +// - 该计数器不会记录每个 key 的计数,只会记录 key 的存在与否 +// - 当 key 不存在时,计数器会将 key 记录为存在,并将计数器增加特定的值 +func NewSimpleDeduplication[K comparable, V generic.Number]() *SimpleDeduplication[K, V] { + return &SimpleDeduplication[K, V]{ + r: make(map[K]struct{}), + } +} + +// SimpleDeduplication 简单去重计数器 +type SimpleDeduplication[K comparable, V generic.Number] struct { + c V + r map[K]struct{} + l sync.RWMutex +} + +// Add 添加计数,根据 key 判断是否重复计数 +func (slf *SimpleDeduplication[K, V]) Add(key K, value V) { + slf.l.Lock() + defer slf.l.Unlock() + if _, exist := slf.r[key]; !exist { + slf.r[key] = struct{}{} + slf.c += value + } +} + +// Get 获取计数 +func (slf *SimpleDeduplication[K, V]) Get() V { + slf.l.RLock() + defer slf.l.RUnlock() + return slf.c +}