-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoder.go
More file actions
135 lines (103 loc) · 2.6 KB
/
encoder.go
File metadata and controls
135 lines (103 loc) · 2.6 KB
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
package luaparser
import(
"fmt"
"strconv"
"errors"
"regexp"
)
type Encoder struct {
}
func Marshal(v interface{}) (string,error) {
enc := &Encoder{}
return enc.Encode(v)
}
func (self *Encoder) Encode(v interface{}) (string,error) {
s:=""
switch v.(type) {
case map[string]interface{}:
val,_ := v.(map[string]interface{})
sub,err := self.EncodeMap(val)
if err != nil {
return "",err
}
s=sub
default:
sub,err := self.EncodePrimitive(v)
if err != nil {
return "",err
}
s=sub
}
return s,nil
}
func (self *Encoder) EncodeMap(m map[string]interface{}) (string,error) {
s:="{"
allowed,err := regexp.Compile("^[A-Z|a-z|0-9|_]*$")
if err != nil {
return "",errors.New("Invalid check regex")
}
for k,v := range m {
_,err := strconv.ParseInt(k,10,32)
var key string
if err == nil {
key=fmt.Sprintf("[%s]",k)
} else if ! allowed.Match([]byte(k)) {
key=fmt.Sprintf("[\"%s\"]",k)
} else {
key=k
}
s+=key+"="
sub,err := self.Encode(v)
if err != nil {
return "",err
}
s+=sub
s+=","
}
if len(s) > 1 {
b:=[]byte(s)
b[len(b)-1]='}'
s=string(b)
} else {
s+="}"
}
return s,nil
}
func (self *Encoder) EncodePrimitive(v interface{}) (string,error) {
s:=""
switch v.(type) {
case int:
val,_:=v.(int)
s=strconv.FormatInt(int64(val),10)
case int32:
val,_:=v.(int32)
s=strconv.FormatInt(int64(val),10)
case int64:
val,_:=v.(int64)
s=strconv.FormatInt(val,10)
case uint:
val,_:=v.(uint)
s=strconv.FormatUint(uint64(val),10)
case uint32:
val,_:=v.(uint32)
s=strconv.FormatUint(uint64(val),10)
case uint64:
val,_:=v.(uint64)
s=strconv.FormatUint(val,10)
case float32:
val,_:=v.(float32)
s=strconv.FormatFloat(float64(val),'f',10,32)
case float64:
val,_:=v.(float64)
s=strconv.FormatFloat(val,'f',10,64)
case bool:
val,_:=v.(bool)
s=strconv.FormatBool(val)
case string:
val,_:=v.(string)
s="\""+val+"\""
default:
return "",errors.New(fmt.Sprintf("Unknown type %T",v))
}
return s,nil
}