-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdatum.go
84 lines (74 loc) · 1.8 KB
/
datum.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
package rethinkgo
import (
"encoding/json"
p "github.com/christopherhesse/rethinkgo/ql2"
"strings"
)
func datumMarshal(v interface{}) (*p.Term, error) {
// convert arbitrary types to a datum tree using the json module
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
dataString := string(data)
datumTerm := &p.Term{
Type: p.Term_DATUM.Enum(),
Datum: &p.Datum{
Type: p.Datum_R_STR.Enum(),
RStr: &dataString,
},
}
term := &p.Term{
Type: p.Term_JSON.Enum(),
Args: []*p.Term{datumTerm},
}
return term, nil
}
func datumUnmarshal(datum *p.Datum, v interface{}) error {
// convert a datum tree into an arbitrary type using the json module
data, err := datumToJson(datum)
if err != nil {
return err
}
return json.Unmarshal(data, v)
}
func datumToJson(datum *p.Datum) ([]byte, error) {
switch datum.GetType() {
case p.Datum_R_NULL:
return json.Marshal(nil)
case p.Datum_R_BOOL:
return json.Marshal(datum.GetRBool())
case p.Datum_R_NUM:
return json.Marshal(datum.GetRNum())
case p.Datum_R_STR:
return json.Marshal(datum.GetRStr())
case p.Datum_R_ARRAY:
items := []string{}
for _, d := range datum.GetRArray() {
item, err := datumToJson(d)
if err != nil {
return nil, err
}
items = append(items, string(item))
}
return []byte("[" + strings.Join(items, ",") + "]"), nil
case p.Datum_R_OBJECT:
pairs := []string{}
for _, assoc := range datum.GetRObject() {
raw_key := assoc.GetKey()
raw_val := assoc.GetVal()
// convert to json form
key, err := json.Marshal(raw_key)
if err != nil {
return nil, err
}
val, err := datumToJson(raw_val)
if err != nil {
return nil, err
}
pairs = append(pairs, string(key)+":"+string(val))
}
return []byte("{" + strings.Join(pairs, ",") + "}"), nil
}
panic("unknown datum type")
}