forked from atercattus/bicycle-mrhlc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_location.go
113 lines (92 loc) · 1.95 KB
/
index_location.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 (
locationsPreallocCount = 800 * 1000
)
type (
IndexLocation struct {
locations []Location
locationsExtra map[int32]*Location // для тех, чей id не вписывается в норму
rwLock sync.RWMutex
}
)
func MakeIndexLocation() *IndexLocation {
return &IndexLocation{
locations: make([]Location, locationsPreallocCount),
locationsExtra: make(map[int32]*Location),
}
}
func (il *IndexLocation) Add(location *Location) bool {
var ok bool
if location.Id < locationsPreallocCount {
il.rwLock.RLock()
if il.locations[location.Id].Id == location.Id {
ok = true
}
il.rwLock.RUnlock()
if ok {
return false
}
il.rwLock.Lock()
if il.locations[location.Id].Id == location.Id {
il.rwLock.Unlock()
return false
}
il.locations[location.Id] = *location
il.rwLock.Unlock()
return true
}
// id вне заранее выделенного диапазона. задействуем map
il.rwLock.RLock()
_, ok = il.locationsExtra[location.Id]
il.rwLock.RUnlock()
if ok {
return false
}
il.rwLock.Lock()
if _, ok = il.locationsExtra[location.Id]; ok {
il.rwLock.Unlock()
return false
}
il.locationsExtra[location.Id] = location
il.rwLock.Unlock()
return true
}
func (il *IndexLocation) Update(id int32, update *Location) bool {
var (
location *Location
ok bool
)
il.rwLock.RLock()
if id < locationsPreallocCount {
location = &il.locations[id]
ok = location.Id == id
} else {
location, ok = il.locationsExtra[id]
}
il.rwLock.RUnlock()
if !ok {
return false
}
return location.Update(update)
}
func (il *IndexLocation) Get(id int32) *Location {
var (
location *Location
ok bool
)
il.rwLock.RLock()
if id < locationsPreallocCount {
location = &il.locations[id]
ok = location.Id == id
} else {
location, ok = il.locationsExtra[id]
}
il.rwLock.RUnlock()
if !ok {
return nil
}
return location
}