-
Notifications
You must be signed in to change notification settings - Fork 12
/
timezone.go
235 lines (208 loc) · 5.21 KB
/
timezone.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package timezoneLookup
import (
"bufio"
"encoding/binary"
"errors"
"os"
"time"
mmapgo "github.com/edsrzf/mmap-go"
"github.com/evanoberholster/timezoneLookup/v2/geo"
)
var (
endian = binary.LittleEndian
ErrCoordinatesNotValid = errors.New("Latitude and/or Longitude are not valid")
)
type Timezonecache struct {
data mmapgo.MMap
arr []uint32
name []string
rt geo.RTree
dataOffset uint32
dataLength uint32
bufOffset int64
}
func (tzc *Timezonecache) AddTimezone(tz Timezone) {
for _, p := range tz.Polygons {
var offset uint32
id := uint(len(tzc.arr)) // next id
buf := p.ToByteSlice()
tzc.data = append(tzc.data, buf...)
if id == 0 {
offset += tzc.dataOffset
} else {
offset += tzc.arr[id-1]
}
offset += uint32(len(buf))
tzc.arr = append(tzc.arr, offset)
tzc.name = append(tzc.name, tz.Name)
tzc.rt.InsertPolygon(p, id)
}
}
func (tzc *Timezonecache) buf(id uint) []byte {
offset := uint32(tzc.bufOffset)
if id == 0 {
return tzc.data[offset : offset+tzc.arr[id]]
}
if id <= uint(len(tzc.arr)) {
return tzc.data[offset+tzc.arr[id-1] : offset+tzc.arr[id]]
}
return nil
}
func (tzc *Timezonecache) Search(lat, lng float64) (Result, error) {
var name string
start := time.Now()
ll := geo.NewLatLng(lat, lng)
if !ll.Valid() {
return Result{}, ErrCoordinatesNotValid
}
tzc.rt.SearchLatLng(ll, func(min geo.LatLng, max geo.LatLng, value interface{}) bool {
if id, ok := value.(uint); ok {
p := geo.NewPolygon()
p.FromByteSlice(tzc.buf(id))
if p.ContainsLatLng(ll) {
name = tzc.name[id]
return true
}
}
return false
})
return Result{Name: name, Coordinates: ll, Elapsed: time.Since(start)}, nil
}
// Result is a timezone lookup result
type Result struct {
Name string
Coordinates geo.LatLng
Elapsed time.Duration
}
func (tzc *Timezonecache) Save(filename string) error {
f2, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, os.FileMode(0666))
if err != nil {
return err
}
defer f2.Close()
bw := bufio.NewWriter(f2)
buf := make([]byte, 256)
var n, written int
if n, err = bw.Write(tzc.encodeHeader(buf)); err != nil {
return err
}
written += n
for i := 0; i < len(tzc.name); i++ {
if n, err = bw.Write(tzc.encodeItem(buf, i)); err != nil {
return err
}
written += n
}
if err = bw.Flush(); err != nil {
return err
}
if n, err = f2.WriteAt(tzc.data, int64(written)); err != nil {
return err
}
written += n
return bw.Flush()
}
func (tzc *Timezonecache) encodeItem(buf []byte, i int) []byte {
name := tzc.name[i]
if len(buf) >= 5+len(name) {
endian.PutUint32(buf, tzc.arr[i])
buf[4] = uint8(len(name))
copy(buf[5:5+len(name)], name)
}
return buf[:5+len(name)]
}
func (tzc *Timezonecache) encodeHeader(b []byte) []byte {
headerLength := 10
if len(b) >= 10 {
for i := 0; i < len(tzc.name); i++ {
headerLength += 5 + len(tzc.name)
}
endian.PutUint32(b[:4], uint32(headerLength))
endian.PutUint32(b[4:8], uint32(len(tzc.data)))
endian.PutUint16(b[8:10], uint16(len(tzc.arr)))
}
return b[:10]
}
func (tzc *Timezonecache) decodeHeader(b []byte) (n int, err error) {
if len(b) > 10 {
tzc.dataOffset = endian.Uint32(b[:4])
tzc.dataLength = endian.Uint32(b[4:8])
items := endian.Uint16(b[8:10])
tzc.arr = make([]uint32, 0, items)
tzc.name = make([]string, 0, items)
return 10, nil
}
return 0, errors.New("error []byte insufficient for header")
}
func (tzc *Timezonecache) decodeItem(b []byte) (n int, err error) {
if len(b) > 4 && len(b) >= (5+int(b[4])) {
tzc.arr = append(tzc.arr, endian.Uint32(b[:4]))
tzc.name = append(tzc.name, string(b[5:5+b[4]]))
return (5 + int(b[4])), nil
}
return 0, errors.New("error []byte insufficient for an item")
}
func (tzc *Timezonecache) Load(f *os.File) (err error) {
var d, discarded int
var b []byte
br := bufio.NewReader(f)
if b, err = br.Peek(256); err != nil {
return err
}
if d, err = tzc.decodeHeader(b); err != nil {
return err
}
if d, err = br.Discard(d); err != nil {
return err
}
discarded += d
for i := 0; i < cap(tzc.name); i++ {
if b, err = br.Peek(256); err != nil {
return err
}
if d, err = tzc.decodeItem(b); err != nil {
return err
}
if d, err = br.Discard(d); err != nil {
return err
}
discarded += d
}
tzc.bufOffset = int64(discarded)
if tzc.data, err = mmap(f, 0, int64(tzc.dataLength+uint32(tzc.bufOffset))); err != nil {
return err
}
tzc.BuildRtree()
return err
}
func (tzc *Timezonecache) Close() error {
if tzc.data != nil {
err := munmap(tzc.data)
tzc.data = nil
return err
}
return errors.New("error timezone data is nil")
}
func (tzc *Timezonecache) BuildRtree() {
for i, _ := range tzc.arr {
id := uint(i)
p := geo.NewPolygonFromBytes(tzc.buf(id))
tzc.rt.InsertPolygon(p, id)
}
}
func mmap(f *os.File, offset, length int64) (mmapgo.MMap, error) {
if f == nil {
return nil, errors.New("error file not open")
}
return mmapgo.MapRegion(f, int(length), mmapgo.RDONLY, 0, offset)
}
func munmap(data mmapgo.MMap) (err error) {
if data != nil {
err = data.Unmap()
data = nil
return
}
return errors.New("error munmap data is nil")
}
// [8]items [8*items]offset [1*items]offsetstring
// [4]dataoffset [2]items [4]offset [1]stringlength [...]string ... []