-
Notifications
You must be signed in to change notification settings - Fork 9
/
index_visit.go
113 lines (92 loc) · 1.71 KB
/
index_visit.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 (
visitsPreallocCount = 12 * 1000 * 1000
)
type (
IndexVisit struct {
visits []Visit
visitsExtra map[int32]*Visit
rwLock sync.RWMutex
}
)
func MakeIndexVisit() *IndexVisit {
return &IndexVisit{
visits: make([]Visit, visitsPreallocCount),
visitsExtra: make(map[int32]*Visit),
}
}
func (iv *IndexVisit) Add(visit *Visit) bool {
var ok bool
if visit.Id < visitsPreallocCount {
iv.rwLock.RLock()
if iv.visits[visit.Id].Id == visit.Id {
ok = true
}
iv.rwLock.RUnlock()
if ok {
return false
}
iv.rwLock.Lock()
if iv.visits[visit.Id].Id == visit.Id {
iv.rwLock.Unlock()
return false
}
iv.visits[visit.Id] = *visit
iv.rwLock.Unlock()
return true
}
// id вне заранее выделенного диапазона. задействуем map
iv.rwLock.RLock()
_, ok = iv.visitsExtra[visit.Id]
iv.rwLock.RUnlock()
if ok {
return false
}
iv.rwLock.Lock()
if _, ok := iv.visitsExtra[visit.Id]; ok {
iv.rwLock.Unlock()
return false
}
iv.visitsExtra[visit.Id] = visit
iv.rwLock.Unlock()
return true
}
func (iv *IndexVisit) Update(id int32, update *Visit) bool {
var (
visit *Visit
ok bool
)
iv.rwLock.RLock()
if id < visitsPreallocCount {
visit = &iv.visits[id]
ok = visit.Id == id
} else {
visit, ok = iv.visitsExtra[id]
}
iv.rwLock.RUnlock()
if !ok {
return false
}
return visit.Update(update)
}
func (iv *IndexVisit) Get(id int32) *Visit {
var (
visit *Visit
ok bool
)
iv.rwLock.RLock()
if id < visitsPreallocCount {
visit = &iv.visits[id]
ok = visit.Id == id
} else {
visit, ok = iv.visitsExtra[id]
}
iv.rwLock.RUnlock()
if !ok {
return nil
}
return visit
}