-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunks.go
95 lines (68 loc) · 1.67 KB
/
chunks.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
package polyline
import (
"math"
)
type chunks []int32
// Parse splices an integer into chunks
func (c *chunks) Parse(element int32) {
c.slice(element, 5)
}
// ParseLine converts and splices string into integer chunks
func (c *chunks) ParseLine(line string) {
var chunkSlice []int32
for index, letter := range line {
elementInt := int32(letter) - 63
if index != len(line)-1 {
elementInt = elementInt & 31
}
chunkSlice = append(chunkSlice, elementInt)
}
*c = chunkSlice
}
// String returns the chunks as polyline in base64
func (c *chunks) String() string {
c.or()
s := ""
for i := range *c {
s += string((*c)[i])
}
return s
}
// Coordinate converts integer chunks into a single coordinate
func (c *chunks) Coordinate(precision uint32) float64 {
resultInt := int32(0)
for i, element := range *c {
resultInt += element << uint32(i*5)
}
if resultInt&1 == 1 {
resultInt = ^resultInt
}
resultInt = resultInt >> 1
return float64(resultInt) / math.Pow10(int(precision))
}
// slice splits elements into group of "length" bits
func (c *chunks) slice(element int32, length int) {
if element == 0 {
*c = []int32{0}
return
}
chunkSlice := []int32{}
bitMask := int32(31)
for i := 0; int32(math.Pow(2, float64(i))) <= element; i += 5 {
group := (element >> uint(i)) & bitMask
chunkSlice = append(chunkSlice, group)
}
*c = chunkSlice
}
// or sets the 6th bit to 1 for every chunk except the last one
// as indicator bit for coordinate boundaries.
// It also adds 63 (decimal) to every group to ensure it is in
// ASCII range
func (c *chunks) or() {
for i := range *c {
if i < len(*c)-1 {
(*c)[i] = (*c)[i] | 0x20
}
(*c)[i] += 63
}
}