-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
A map[string]int64 that is able to properly encode and decode according to the format being used by the steemd encoder.
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
} |