-
Notifications
You must be signed in to change notification settings - Fork 9
/
index_user.go
113 lines (92 loc) · 1.65 KB
/
index_user.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
package main
import (
"sync"
)
const (
usersPreallocCount = 1.2 * 1000 * 1000
)
type (
IndexUser struct {
users []User
usersExtra map[int32]*User
rwLock sync.RWMutex
}
)
func MakeIndexUser() *IndexUser {
return &IndexUser{
users: make([]User, usersPreallocCount),
usersExtra: make(map[int32]*User),
}
}
func (iu *IndexUser) Add(user *User) bool {
var ok bool
if user.Id < usersPreallocCount {
iu.rwLock.RLock()
if iu.users[user.Id].Id == user.Id {
ok = true
}
iu.rwLock.RUnlock()
if ok {
return false
}
iu.rwLock.Lock()
if iu.users[user.Id].Id == user.Id {
iu.rwLock.Unlock()
return false
}
iu.users[user.Id] = *user
iu.rwLock.Unlock()
return true
}
// id вне заранее выделенного диапазона. задействуем map
iu.rwLock.RLock()
_, ok = iu.usersExtra[user.Id]
iu.rwLock.RUnlock()
if ok {
return false
}
iu.rwLock.Lock()
if _, ok := iu.usersExtra[user.Id]; ok {
iu.rwLock.Unlock()
return false
}
iu.usersExtra[user.Id] = user
iu.rwLock.Unlock()
return true
}
func (iu *IndexUser) Update(id int32, update *User) bool {
var (
user *User
ok bool
)
iu.rwLock.RLock()
if id < usersPreallocCount {
user = &iu.users[id]
ok = user.Id == id
} else {
user, ok = iu.usersExtra[id]
}
iu.rwLock.RUnlock()
if !ok {
return false
}
return user.Update(update)
}
func (iu *IndexUser) Get(id int32) *User {
var (
user *User
ok bool
)
iu.rwLock.RLock()
if id < usersPreallocCount {
user = &iu.users[id]
ok = user.Id == id
} else {
user, ok = iu.usersExtra[id]
}
iu.rwLock.RUnlock()
if !ok {
return nil
}
return user
}