This repository has been archived by the owner on Mar 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.go
79 lines (75 loc) · 1.82 KB
/
map.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
package cbor
import (
"bytes"
"fmt"
"reflect"
)
// EncodeMap encodes a map using arbitrary types as keys and values to a cbor value
func EncodeMap(in interface{}) []byte {
val := reflect.ValueOf(in)
length := val.Len()
l := EncodeUint(uint64(length))
l[0] = l[0] | 0xA0 // Major type 5
out := bytes.NewBuffer(l)
iter := val.MapRange()
for iter.Next() {
out.Write(encode(iter.Key().Interface()))
out.Write(encode(iter.Value().Interface()))
}
return out.Bytes()
}
// DecodeMap decodes a cbor value to a map using arbitrary types as keys and values
func DecodeMap(fb byte, r *bytes.Reader) (map[interface{}]interface{}, error) {
fb = fb & 0x1F
if fb == 31 {
return decodeIndefiniteMap(r)
}
l, err := DecodeUint(fb, r)
if err != nil {
return nil, err
}
out := make(map[interface{}]interface{}, l)
for i := 0; i < int(l); i++ {
fb, err := r.ReadByte()
if err != nil {
return nil, fmt.Errorf("could not read key: %s", err.Error())
}
key, err := decode(fb, r)
if err != nil {
return nil, err
}
fb, err = r.ReadByte()
if err != nil {
return nil, fmt.Errorf("could not read value: %s", err.Error())
}
value, err := decode(fb, r)
if err != nil {
return nil, err
}
out[key] = value
}
return out, nil
}
func decodeIndefiniteMap(r *bytes.Reader) (map[interface{}]interface{}, error) {
out := make(map[interface{}]interface{})
fb, err := r.ReadByte()
for ; err == nil && fb != 0xFF; fb, err = r.ReadByte() {
key, err := decode(fb, r)
if err != nil {
return nil, err
}
fb, err = r.ReadByte()
if err != nil {
return nil, fmt.Errorf("could not read value: %s", err.Error())
}
value, err := decode(fb, r)
if err != nil {
return nil, err
}
out[key] = value
}
if err != nil {
return nil, fmt.Errorf("failed to parse indefinite length map: %s", err.Error())
}
return out, nil
}