-
Notifications
You must be signed in to change notification settings - Fork 3
/
namescache.go
128 lines (109 loc) · 2.31 KB
/
namescache.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"encoding/json"
"sync"
"sync/atomic"
)
type namesCache struct {
users map[Userid]*User
marshallednames []byte
connectioncount uint32
ircnames [][]string
sync.RWMutex
}
type namesOut struct {
Users []*SimplifiedUser `json:"users"`
Connections uint32 `json:"connectioncount"`
}
var namescache = namesCache{
users: make(map[Userid]*User),
RWMutex: sync.RWMutex{},
}
func (nc *namesCache) updateNames() {
users := make([]*SimplifiedUser, 0, len(nc.users))
for _, u := range nc.users {
u.RLock()
n := atomic.LoadInt32(&u.connections)
u.RUnlock()
if n <= 0 {
// should not happen anymore since we remove users with 0 connections now.
continue
}
users = append(users, u.simplified)
}
n := namesOut{
Users: users,
Connections: nc.connectioncount,
}
var err error
nc.marshallednames, err = json.Marshal(n)
if err != nil {
B(err)
}
}
func (nc *namesCache) getNames() []byte {
nc.RLock()
defer nc.RUnlock()
return nc.marshallednames
}
func (nc *namesCache) get(id Userid) *User {
nc.RLock()
defer nc.RUnlock()
u := nc.users[id]
return u
}
func (nc *namesCache) add(user *User) *User {
nc.Lock()
defer nc.Unlock()
nc.connectioncount++
if u, ok := nc.users[user.id]; ok {
atomic.AddInt32(&u.connections, 1)
} else {
atomic.AddInt32(&user.connections, 1)
su := &SimplifiedUser{
Nick: user.nick,
Features: user.simplified.Features,
}
user.simplified = su
nc.users[user.id] = user
entities.AddNick(user.nick)
}
nc.updateNames()
return nc.users[user.id]
}
func (nc *namesCache) disconnect(user *User) {
nc.Lock()
defer nc.Unlock()
if user != nil {
nc.connectioncount--
if u, ok := nc.users[user.id]; ok {
conncount := atomic.AddInt32(&u.connections, -1)
if conncount <= 0 {
delete(nc.users, user.id)
entities.RemoveNick(u.nick)
}
}
} else {
nc.connectioncount--
}
nc.updateNames()
}
func (nc *namesCache) refresh(user *User) {
nc.RLock()
defer nc.RUnlock()
if u, ok := nc.users[user.id]; ok {
u.Lock()
u.simplified.Nick = user.nick
u.simplified.Features = user.simplified.Features
u.nick = user.nick
u.features = user.features
u.Unlock()
nc.updateNames()
}
}
func (nc *namesCache) addConnection() {
nc.Lock()
defer nc.Unlock()
nc.connectioncount++
nc.updateNames()
}