Skip to content

Commit dd21f66

Browse files
committed
fix(max_counter): improve the Sub() method, considering the case of reduction.
1 parent 4749a84 commit dd21f66

2 files changed

Lines changed: 42 additions & 1 deletion

File tree

max_counter.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,15 @@ func (c *MaxCounter) Add(delta float64) bool {
131131
max := c.GetMax()
132132
realNum := c.Real()
133133

134-
if realNum >= max && delta >= 0 {
134+
if realNum >= max && delta > 0 {
135135
c.setDone()
136136
return false
137137
}
138138

139+
if realNum <= 0 && delta < 0 {
140+
return false
141+
}
142+
139143
return c.counter.Add(delta)
140144
}
141145

max_counter_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,43 @@ func TestMaxCounterSetAndGet(t *testing.T) {
6060
testGo(t, testMaxCounterSetAndGet, 10000)
6161
}
6262

63+
func TestMaxCounterAddAndSub(t *testing.T) {
64+
t.Parallel()
65+
66+
c := AcquireMaxCounter(50)
67+
defer ReleaseMaxCounter(c)
68+
69+
for i := 0; i < 100; i += 1 {
70+
ok := c.Add(1)
71+
if i >= 50 && ok {
72+
t.Error("should false, but true")
73+
74+
// check done
75+
can := c.Can()
76+
if can {
77+
t.Fatal("can not add")
78+
}
79+
}
80+
}
81+
82+
v := c.Get()
83+
if v != 50 {
84+
t.Fatalf("should %d, but %f", 50, v)
85+
}
86+
87+
for i := 0; i < 100; i += 1 {
88+
ok := c.Sub(1)
89+
if i >= 50 && ok {
90+
t.Error("should false, but true.")
91+
}
92+
}
93+
94+
v = c.Get()
95+
if v != 0 {
96+
t.Fatalf("should %d, but %f", 0, v)
97+
}
98+
}
99+
63100
func TestMaxCounter_Reset(t *testing.T) {
64101
t.Parallel()
65102

0 commit comments

Comments
 (0)