-
Notifications
You must be signed in to change notification settings - Fork 6
/
redis.go
79 lines (62 loc) · 1.64 KB
/
redis.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
package bloom
import (
"github.com/garyburd/redigo/redis"
)
// RedisStorage is a struct representing the Redis backend for the bloom filter.
type RedisStorage struct {
pool *redis.Pool
key string
size uint
queue []uint
}
// NewRedisStorage creates a Redis backend storage to be used with the bloom filter.
func NewRedisStorage(pool *redis.Pool, key string, size uint) (*RedisStorage, error) {
var err error
store := RedisStorage{pool, key, size, make([]uint, 0)}
conn := store.pool.Get()
defer conn.Close()
exists, err := redis.Bool(conn.Do("EXISTS", key))
if err != nil {
return &store, err
}
if !exists {
if err := store.init(); err != nil {
return &store, err
}
}
return &store, nil
}
// init takes care of settings every bit to 0 in the Redis bitset.
func (s *RedisStorage) init() (err error) {
conn := s.pool.Get()
defer conn.Close()
var i uint
for i = 0; i < s.size; i++ {
conn.Send("SETBIT", s.key, i, 0)
}
err = conn.Flush()
return
}
// Append appends the bit, which is to be saved, to the queue.
func (s *RedisStorage) Append(bit uint) {
s.queue = append(s.queue, bit)
}
// Save pushes the bits from the queue to the storage backend, assigning the value 1 in the process.
func (s *RedisStorage) Save() {
conn := s.pool.Get()
defer conn.Close()
for _, bit := range s.queue {
conn.Send("SETBIT", s.key, bit, 1)
}
conn.Flush()
}
// Exists checks if the given bit exists in the Redis backend.
func (s *RedisStorage) Exists(bit uint) (ret bool, err error) {
conn := s.pool.Get()
defer conn.Close()
bitValue, err := redis.Int(conn.Do("GETBIT", s.key, bit))
if err != nil {
return
}
return bitValue == 1, err
}