From 480ea8d5aa679785adc416357b34897e78a101ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Kupka?= Date: Sat, 19 Aug 2017 16:17:12 +0200 Subject: [PATCH] types: Add StringInt64Map A map[string]int64 that is able to properly encode and decode according to the format being used by the steemd encoder. --- types/map.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 types/map.go diff --git a/types/map.go b/types/map.go new file mode 100644 index 0000000..35721cf --- /dev/null +++ b/types/map.go @@ -0,0 +1,57 @@ +package types + +import ( + "encoding/json" + "errors" +) + +type StringInt64Map map[string]int64 + +func (m StringInt64Map) MarshalJSON() ([]byte, error) { + xs := make([]interface{}, len(m)) + for k, v := range m { + xs = append(xs, []interface{}{k, v}) + } + return json.Marshal(xs) +} + +func (m *StringInt64Map) UnmarshalJSON(data []byte) error { + var xs [][]interface{} + if err := json.Unmarshal(data, &xs); err != nil { + return err + } + + var invalid bool + mp := make(map[string]int64, len(xs)) + for _, kv := range xs { + if len(kv) != 2 { + invalid = true + break + } + + k, ok := kv[0].(string) + if !ok { + invalid = true + break + } + + var v int64 + switch t := kv[1].(type) { + case float64: + v = int64(t) + case int64: + v = t + default: + invalid = true + break + } + + mp[k] = v + } + if invalid { + return errors.New("invalid map encoding") + } + + *m = mp + return nil +}