-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucks.go
52 lines (43 loc) · 887 Bytes
/
bucks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package bucks
import (
"sync"
"time"
)
type nowFunction func() time.Time
type TokenBucket struct {
capacity int
tokens int
refillRate int
lastRefill time.Time
mutex sync.Mutex
now nowFunction
}
func NewTokenBucket(capacity, refillRate int) *TokenBucket {
return &TokenBucket{
capacity: capacity,
tokens: capacity,
refillRate: refillRate,
lastRefill: time.Now(),
mutex: sync.Mutex{},
now: time.Now,
}
}
func (tb *TokenBucket) refill() {
now := tb.now()
elapsed := now.Sub(tb.lastRefill).Seconds()
tb.tokens += int(elapsed * float64(tb.refillRate))
if tb.tokens > tb.capacity {
tb.tokens = tb.capacity
}
tb.lastRefill = now
}
func (tb *TokenBucket) TakeToken(numTokens int) bool {
tb.mutex.Lock()
defer tb.mutex.Unlock()
tb.refill()
if tb.tokens > 0 {
tb.tokens -= numTokens
return true
}
return false
}