...
1 package gmeasure
2
3 import "encoding/json"
4
5 type enumSupport struct {
6 toString map[uint]string
7 toEnum map[string]uint
8 maxEnum uint
9 }
10
11 func newEnumSupport(toString map[uint]string) enumSupport {
12 toEnum, maxEnum := map[string]uint{}, uint(0)
13 for k, v := range toString {
14 toEnum[v] = k
15 if maxEnum < k {
16 maxEnum = k
17 }
18 }
19 return enumSupport{toString: toString, toEnum: toEnum, maxEnum: maxEnum}
20 }
21
22 func (es enumSupport) String(e uint) string {
23 if e > es.maxEnum {
24 return es.toString[0]
25 }
26 return es.toString[e]
27 }
28
29 func (es enumSupport) UnmarshJSON(b []byte) (uint, error) {
30 var dec string
31 if err := json.Unmarshal(b, &dec); err != nil {
32 return 0, err
33 }
34 out := es.toEnum[dec]
35 return out, nil
36 }
37
38 func (es enumSupport) MarshJSON(e uint) ([]byte, error) {
39 if e == 0 || e > es.maxEnum {
40 return json.Marshal(nil)
41 }
42 return json.Marshal(es.toString[e])
43 }
44
View as plain text