-
Notifications
You must be signed in to change notification settings - Fork 9
/
index_country.go
55 lines (49 loc) · 1.02 KB
/
index_country.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
package main
import (
"bytes"
"sync"
)
type (
IndexCountry struct {
names [][]byte
rwLock sync.RWMutex
}
)
func MakeIndexCountry() *IndexCountry {
index := &IndexCountry{}
index.names = make([][]byte, 0, 300)
index.names = append(index.names, nil) // резервирую 0 индекс, чтобы не выдавался
return index
}
func (ic *IndexCountry) Add(name []byte) (int, bool) {
ic.rwLock.Lock()
for idx, n := range ic.names {
if bytes.Equal(n, name) {
ic.rwLock.Unlock()
return idx, false
}
}
ic.names = append(ic.names, name)
idx := len(ic.names) - 1
ic.rwLock.Unlock()
return idx, true
}
func (ic *IndexCountry) Find(name []byte) (idx int) { // 0 - если не найден
ic.rwLock.RLock()
for i, n := range ic.names {
if bytes.Equal(n, name) {
idx = i
break
}
}
ic.rwLock.RUnlock()
return
}
func (ic *IndexCountry) GetByIdx(idx int) (name []byte) {
ic.rwLock.RLock()
if (idx >= 0) && (idx < len(ic.names)) {
name = ic.names[idx]
}
ic.rwLock.RUnlock()
return
}