feat(counter): go-hua/single 迁入并更名 counter(键值计数器)

- 原包名 single 名不达意,实为 string→int64 并发计数器;类型 Single→Counter,
  方法签名不变(Init/Get/Incr/Set),附测试、例程与 README
This commit is contained in:
2026-09-20 12:20:51 +08:00
parent 9d7a512e18
commit 75f0b78d52
4 changed files with 170 additions and 0 deletions
+57
View File
@@ -0,0 +1,57 @@
package counter
import (
"sync"
"testing"
)
func TestIncrConcurrent(t *testing.T) {
var c Counter
c.Init()
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Incr("pv", 1)
}()
}
wg.Wait()
if got := c.Get("pv"); got != 100 {
t.Errorf("并发 100 次 Incr 后 = %d, want 100", got)
}
}
func TestSet(t *testing.T) {
var c Counter
c.Init()
c.Set("k", 10)
old := c.Set("k", 20)
if old != 10 {
t.Errorf("Set 返回旧值 = %d, want 10", old)
}
if got := c.Get("k"); got != 20 {
t.Errorf("Set 后 Get = %d, want 20", got)
}
}
func TestGetMissing(t *testing.T) {
var c Counter
c.Init()
if got := c.Get("not-exist"); got != 0 {
t.Errorf("不存在的 key Get = %d, want 0", got)
}
}
func TestKeysIndependent(t *testing.T) {
var c Counter
c.Init()
c.Incr("a", 1)
c.Incr("b", 2)
if c.Get("a") != 1 || c.Get("b") != 2 {
t.Errorf("不同 key 应相互独立: a=%d b=%d", c.Get("a"), c.Get("b"))
}
}