-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderedmap.go
339 lines (288 loc) · 7.54 KB
/
orderedmap.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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package orderedmap
import (
"bytes"
"encoding/json"
"errors"
"sort"
"strings"
"fmt"
)
var errEOA = errors.New("End of Array")
// An OrderedMap is a map where the keys keep the order that they're added.
// It is similar to indexed arrays. You can get the strings by key or by position.
// The OrderedMap is not safe for concurrent use.
type OrderedMap struct {
// for preserving the order of key
keys []string
values map[string]interface{}
}
// New create a new OrderedMap.
func New() *OrderedMap {
return &OrderedMap{keys:[]string{}, values:make(map[string]interface{})}
}
// Filter filters an OrderedMap if the provided function return true.
// Returns a new OrderedMap.
func (om *OrderedMap) Filter(f func(key string, value interface{}) bool) *OrderedMap {
retOm := New() //retOm: returned OrderedMap
if om == nil {
return retOm
}
for _, key := range om.keys {
val := om.values[key]
if f(key, val) { // if the function returns tru, add it to the result.
retOm.Set(key, val)
}
}
return retOm
}
// Get returns the value of the map based on its key.
// It will return nil if it doesn't exist.
func (om *OrderedMap) Get(key string) (interface{}, bool) {
val, exists := om.values[key]
return val, exists
}
// GetAt returns the value based on the provided pos.
func (om *OrderedMap) GetAt(pos int) (val interface{}, ok bool) {
if om.values == nil {
return nil, false
}
if pos >= len(om.keys) {
val = nil
} else {
val, ok = om.values[om.keys[pos]]
return val, ok
}
return
}
// Set sets the key/value of the map based on key and value.
// If the value already exists, the value will be replaced.
func (om *OrderedMap) Set(key string, value interface{}) {
_, exists := om.values[key]
if !exists { //not exists
//add it to the keys array
om.keys = append(om.keys, key)
}
om.values[key] = value
}
// SetAt sets the given key to the given value at the specified index.
// 1. If (index == -1 || index >= len(orderedmap)), then put it at the end.
// 2. If index is negative, index < -len(orderedmap), then put it at the beginning.
// 3 If index == -1, -2, ..., put it from the last, last - 1, etc...
func (om *OrderedMap) SetAt(index int, key string, val interface{}) {
valLen := len(om.values)
if index == -1 || index >= valLen {
om.Set(key, val)
}
if om.values == nil {
om.values = make(map[string]interface{})
}
if _, ok := om.values[key]; !ok { //if key not exists
if index < -valLen {
index = 0 // set at the begining
}
if index < 0 {
index = valLen + index + 1
}
om.keys = append(om.keys, "") //assume the key is empty
copy(om.keys[index+1:], om.keys[index:]) //shift the keys array
om.keys[index] = key // reassign the key.
}
om.values[key] = val
}
// Delete remove an item from the map by the supplied key.
// If the key does not exist, nothing happens.
func (om *OrderedMap) Delete(key string) {
_, ok := om.values[key]
if !ok { // key not exists, do nothing.
return
}
// remove from keys
for i, k := range om.keys {
if k == key {
om.keys = append(om.keys[:i], om.keys[i+1:]...)
break
}
}
// remove from values
delete(om.values, key)
}
// DeleteAt delete the key/value pair from the map by the supplied offset.
// If the offset is outside the range of the ordered map, nothing happens.
func (om *OrderedMap) DeleteAt(offset int) {
if offset < 0 || offset >= len(om.keys) {
return
}
om.Delete(om.keys[offset])
}
// Keys return the keys of the map in the order they were added.
func (om *OrderedMap) Keys() []string {
ret := make([]string, len(om.keys))
copy(ret, om.keys)
return ret
}
// Values returns a slice of the values in the order they were added.
func (om *OrderedMap) Values() []interface{} {
vals := make([]interface{}, len(om.keys))
for idx, v := range om.keys {
vals[idx] = om.values[v]
}
return vals
}
// Reverse reverse key & value of a map.
// The value must be a string.
// Returns a new OrderedMap.
func (om *OrderedMap) Reverse() *OrderedMap {
h := New()
for _, key := range om.keys {
val := om.values[key]
h.Set(val.(string), key)
}
return h
}
// Exists test whether the key exists or not.
func (om *OrderedMap) Exists(key string) (ok bool) {
if om.values == nil {
return false
}
_, ok = om.values[key]
return
}
// Index returns the offset of the key in the ordered map.
// If the key could not be found, -1 is returned.
func (om *OrderedMap) Index(key string) int {
for idx, k := range om.keys {
if k == key {
return idx
}
}
return -1
}
// Blelow three functions implement sort.Interface.
// Len returns the length of the map.
func (om *OrderedMap) Len() int {
return len(om.keys)
}
func (om *OrderedMap) Less(i, j int) bool {
return om.keys[i] < om.keys[j]
}
func (om *OrderedMap) Swap(i, j int) {
om.keys[i], om.keys[j] = om.keys[j], om.keys[i]
}
// Sort the given orderedmap.
func (om *OrderedMap) Sort() { sort.Sort(om) }
// String returns the JSON serialized string representation.
func (om *OrderedMap) String() string {
json, _ := om.MarshalJSON()
return string(json)
}
// MarshalJSON implements the json.Marshaller interface, so it could be serialized.
// When serializing, the keys of the map will keep the order they are added.
func (om OrderedMap) MarshalJSON() ([]byte, error) {
var out bytes.Buffer
out.WriteString("{")
for idx, key:= range om.keys {
if idx > 0 {
out.WriteString(",")
}
esc := strings.Replace(key, `"`, `\"`, -1)
out.WriteString(`"` + esc + `"`)
out.WriteString(":")
//marshal the value
b, err := json.Marshal(om.values[key])
if err != nil {
return []byte{}, err
}
out.WriteString(string(b))
} //end for
out.WriteString("}")
return out.Bytes(), nil
}
// UnmarshalJSON implements the json.Unmarshaller interface.
// so it could be use like below:
// o := New()
// err := json.Unmarshal([]byte(jsonString), &o)
func (om *OrderedMap) UnmarshalJSON(b []byte) error {
//Using Decoder to parse the bytes.
in := bytes.TrimSpace(b)
dec := json.NewDecoder(bytes.NewReader(in))
t, err := dec.Token()
if err != nil {
return err
}
// must open with a delim token '{'
if delim, ok := t.(json.Delim); !ok || delim != '{' {
return fmt.Errorf("expect JSON object open with '{'")
}
om.parseObject(dec)
t, err = dec.Token() //'}'
if err != nil {
return err
}
if delim, ok := t.(json.Delim); !ok || delim != '}' {
return fmt.Errorf("expect JSON object close with '}'")
}
return nil
}
func (om *OrderedMap) parseObject(dec *json.Decoder) error {
for dec.More() { // Loop until it has no more tokens
t, err := dec.Token()
if err != nil {
return err
}
key, ok := t.(string)
if !ok {
return fmt.Errorf("key must be a string, got %T\n", t)
}
val, err := parseValue(dec)
if err != nil {
return err
}
om.Set(key, val)
}
return nil
}
func parseValue(dec *json.Decoder) (interface{}, error) {
t, err := dec.Token()
if err != nil {
return nil, err
}
switch tok := t.(type) {
case json.Delim:
switch tok {
case '[': // If it's an array
return parseArray(dec)
case '{': // If it's a map
om := New()
err := om.parseObject(dec)
if err != nil {
return nil, err
}
_, err = dec.Token() // }
if err != nil {
return nil, err
}
return om, nil
case ']':
return nil, errEOA
case '}':
return nil, errors.New("unexpected '}'")
default:
return nil, fmt.Errorf("Unexpected delimiter: %q", tok)
}
default:
return tok, nil
}
}
func parseArray(dec *json.Decoder) ([]interface{}, error) {
ret :=[]interface{}{}
for {
v, err := parseValue(dec)
if err == errEOA {
return ret, nil
}
if err != nil {
return nil, err
}
ret = append(ret, v)
}
}