-
Notifications
You must be signed in to change notification settings - Fork 1
/
neighbor.go
93 lines (81 loc) · 1.9 KB
/
neighbor.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
package georedis
import (
"fmt"
"reflect"
log "github.com/sirupsen/logrus"
)
// Neighbor is member with the distance and geohash
type Neighbor struct {
Member
Dist float64
Hash int64
}
// NewNeighbor transfers the raw value from GEOREDIUS to Member
func NewNeighbor(raw reflect.Value, opts ...Option) (*Neighbor, error) {
// no option, only slice of string
if len(opts) == 0 {
name, err := toString(unpackValue(raw))
return &Neighbor{Member: Member{Name: name}}, err
}
if raw.Kind() != reflect.Slice {
log.WithFields(log.Fields{
"type": raw.Kind(),
"raw data": raw,
}).Error("wrong type, want slice")
return nil, fmt.Errorf("new neighbor data fail: %v", raw.Kind())
}
nb := &Neighbor{}
transformers := []func(v reflect.Value) error{
func(v reflect.Value) error { // name
name, err := toString(unpackValue(v))
log.Debugf("convert to name, raw: %v, error: %v", v, err)
if err != nil {
return err
}
nb.Name = name
return nil
},
func(v reflect.Value) error { // distance
dist, err := toFloat64(unpackValue(v))
log.Debugf("convert to distance, raw: %v, error: %v", v, err)
if err != nil {
return err
}
nb.Dist = dist
return nil
},
func(v reflect.Value) error { // hash (int)
// TODO: handle panic when convert fail
hash := toInt64(unpackValue(v))
log.Debugf("convert to distance, raw: %v", v)
nb.Hash = hash
return nil
},
func(v reflect.Value) error { // coordinate
coord, err := toCoordinate(unpackValue(v))
log.Debugf("convert to coordinate, raw: %v, error: %v", v, err)
if err != nil {
return err
}
nb.Coord = coord
return nil
},
}
ckTab := make([]bool, 4)
ckTab[0] = true
for _, opt := range opts {
ckTab[opt+1] = true
}
i := 0
for fi, ok := range ckTab {
if !ok {
continue
}
err := transformers[fi](raw.Index(i))
if err != nil {
return nil, err
}
i++
}
return nb, nil
}