-
Notifications
You must be signed in to change notification settings - Fork 0
/
stablemap.go
102 lines (91 loc) · 2.46 KB
/
stablemap.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package foundation
import (
"encoding/json"
"errors"
"sort"
"strings"
"github.com/insolar/insolar/insolar"
)
// StableMap is a `map[string]string` that can be deterministically serialized.
type StableMap map[string]string
// NewStableMapFromInterface tries to parse interface{} as [][]string and creates new StableMap.
func NewStableMapFromInterface(i interface{}) (StableMap, error) {
m := make(StableMap)
s, ok := i.([]interface{})
if !ok {
return nil, errors.New("bad interface content")
}
for _, e := range s {
elem, ok := e.([]interface{})
if !ok {
return nil, errors.New("failed to parse slice")
}
if len(elem) < 2 {
return nil, errors.New("wrong number of elements in pair")
}
k, ok := elem[0].(string)
if !ok {
return nil, errors.New("failed to parse key")
}
v, ok := elem[1].(string)
if !ok {
return nil, errors.New("failed to parse value")
}
m[k] = v
}
return m, nil
}
func newMapFromSlice(s [][2]string) StableMap {
m := make(StableMap)
for _, pair := range s {
m[pair[0]] = pair[1]
}
return m
}
func (m StableMap) slice() [][2]string {
res := make([][2]string, 0, len(m))
for k, v := range m {
res = append(res, [2]string{k, v})
}
sort.SliceStable(res, func(i, j int) bool { return strings.Compare(res[i][0], res[j][0]) == -1 })
return res
}
func (m StableMap) MarshalJSON() ([]byte, error) {
return json.Marshal(m.slice())
}
func (m StableMap) MarshalBinary() ([]byte, error) {
return insolar.Serialize(m.slice())
}
func (m *StableMap) UnmarshalJSON(data []byte) error {
res := make([][2]string, 0, len(*m))
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
*m = newMapFromSlice(res)
return nil
}
func (m *StableMap) UnmarshalBinary(data []byte) error {
res := make([][2]string, 0, len(*m))
err := insolar.Deserialize(data, &res)
if err != nil {
return err
}
*m = newMapFromSlice(res)
return nil
}