-
Notifications
You must be signed in to change notification settings - Fork 1
/
singleton.go
77 lines (66 loc) · 1.64 KB
/
singleton.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
package chash
import (
"sync"
)
var (
mu sync.Mutex
// singleton is a pointer to a CHash instance, which will be created when necessary.
singleton *CHash
)
// CreateGroup creates a new group in the CHash instance and returns a pointer to
// the Group object. If the group already exists, it returns an error.
func CreateGroup(groupName string, replicas int) (*Group, error) {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
// If singleton is nil, we create a new instance of CHash using the New()
// function and assign it to the singleton variable.
singleton = New()
}
return singleton.CreateGroup(groupName, replicas)
}
// RemoveGroup removes the specified group from the CHash instance.
func RemoveGroup(groupName string) {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
return
}
singleton.RemoveGroup(groupName)
}
// RemoveAllGroup removes all groups from the CHash instance.
func RemoveAllGroup() {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
return
}
singleton.RemoveAllGroup()
}
// GetGroup retrieves the specified group from the CHash instance.
func GetGroup(groupName string) (*Group, error) {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
singleton = New()
}
return singleton.GetGroup(groupName)
}
// Serialize serializes the entire CHash object to a byte slice.
func Serialize() ([]byte, error) {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
singleton = New()
}
return singleton.Serialize()
}
// Restore restores the CHash object from serialized data.
func Restore(data []byte) error {
mu.Lock()
defer mu.Unlock()
if singleton == nil {
singleton = New()
}
return singleton.Restore(data)
}