-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsets.go
78 lines (64 loc) · 1.93 KB
/
sets.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
package redis
import "sync"
type RedisSet map[string]bool
var (
allSets map[string]RedisSet = make(map[string]RedisSet)
setCounts map[string]int = make(map[string]int)
setsMu sync.RWMutex
)
// Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members.
// An error is returned when the value stored at key is not a set.
//
// Return value
// Integer reply: the number of elements that were added to the set, not including all the elements already present into the set.
func Sadd(key string, member ...string) (additions int) {
setsMu.Lock()
defer setsMu.Unlock()
s, exists := allSets[key]
if !exists {
setCounts[key] = 0
allSets[key] = RedisSet{}
s = allSets[key]
}
for _, m := range member {
_, existed := s[m]
if !existed {
additions++
setCounts[key]++
}
s[m] = true
}
// Publish as an array (not the internal storage hash representation)
//
var out []string
for k, _ := range allSets[key] {
out = append(out, k)
}
publish <- notice{"set", key, "", out}
return
}
// Returns all the members of the set value stored at key.
// This has the same effect as running SINTER with one argument key.
//
// Return value
// Array reply: all elements of the set.
func Smembers(key string) (out []string) {
setsMu.RLock()
defer setsMu.RUnlock()
s, _ := allSets[key]
for k, _ := range s {
out = append(out, k)
}
return
}
// Returns all the members of the set value stored at key.
// This has the same effect as running SINTER with one argument key.
//
// Return value
// Array reply: all elements of the set.
func Scard(key string) (count int) {
setsMu.RLock()
defer setsMu.RUnlock()
count, _ = setCounts[key]
return
}