-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
67 lines (57 loc) · 1.07 KB
/
sync.go
File metadata and controls
67 lines (57 loc) · 1.07 KB
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
package jdb
import (
"math/rand"
"sync"
)
type clientList struct {
data map[int64]Client
mu sync.Mutex
}
func newClientList() *clientList {
return &clientList{
data: make(map[int64]Client),
mu: sync.Mutex{},
}
}
func (c *clientList) GetByID(id int64) (Client, bool) {
c.mu.Lock()
defer c.mu.Unlock()
cl, ok := c.data[id]
return cl, ok
}
func (c *clientList) AddClient(client Client) int64 {
c.mu.Lock()
defer c.mu.Unlock()
var uid int64
for {
// Generate Unique ID
uid = rand.Int63()
// Only exit if ID is not already assigned
if _, ok := c.data[uid]; !ok {
break
}
}
client.SetUID(uid)
c.data[uid] = client
return uid
}
func (c *clientList) RemoveClient(client Client) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.data, client.UID())
}
func (c *clientList) Has(client Client) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.data[client.UID()]
return ok
}
func (c *clientList) Clients() []Client {
c.mu.Lock()
defer c.mu.Unlock()
clients := []Client{}
for _, cl := range c.data {
clients = append(clients, cl)
}
return clients
}