forked from noahhai/bucket
/
memory.go
83 lines (65 loc) · 2.09 KB
/
memory.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package storage
import (
"errors"
"sync"
)
// Implement an in-memory datastore with a concurrent safe map protected by a RWmutex
type MemoryStorage struct {
mutex sync.RWMutex
buckets map[string]int
}
func (ms *MemoryStorage) Ping() error { return nil }
// Create an entry in the map if one does not exist for the given name. If an entry already exists return nil so that
// the bucket will share the entry.
func (ms *MemoryStorage) Create(name string, capacity int) error {
if ms.buckets == nil {
ms.buckets = map[string]int{}
}
ms.mutex.Lock()
defer ms.mutex.Unlock()
if _, exists := ms.buckets[name]; exists {
return nil
}
ms.buckets[name] = capacity
return nil
}
// Decrement the entry value unless the value < tokens. If value < tokens return an error else return nil.
// Note that we don't check if name exists as a key of the map, this is because storage.Take is called directly
// from it's parent method on Bucket where the name is derived from. A bucket can't exist to call if it doesn't already
// have a name...
func (ms *MemoryStorage) Take(bucketName string, tokens int) error {
ms.mutex.Lock()
defer ms.mutex.Unlock()
if ms.buckets[bucketName] < tokens {
return errors.New("Insufficient tokens.")
}
ms.buckets[bucketName] -= tokens
return nil
}
// get and return the token value, set the token value to zero
func (ms *MemoryStorage) TakeAll(bucketName string) (int, error) {
ms.mutex.Lock()
defer ms.mutex.Unlock()
count := ms.buckets[bucketName]
ms.buckets[bucketName] = 0
return count, nil
}
func (ms *MemoryStorage) Set(bucketName string, tokens int) error {
ms.mutex.Lock()
defer ms.mutex.Unlock()
ms.buckets[bucketName] = tokens
return nil
}
// Increment the entry value by the given tokens integer
func (ms *MemoryStorage) Put(bucketName string, tokens int) error {
ms.mutex.Lock()
defer ms.mutex.Unlock()
ms.buckets[bucketName] += tokens
return nil
}
// We only need a read lock here because we are only reading it.
func (ms *MemoryStorage) Count(bucketName string) (int, error) {
ms.mutex.RLock()
defer ms.mutex.RUnlock()
return ms.buckets[bucketName], nil
}