This repository was 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
Expand file tree
/
Copy patharray.go
More file actions
61 lines (57 loc) · 1.37 KB
/
array.go
File metadata and controls
61 lines (57 loc) · 1.37 KB
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
package cbor
import (
"bytes"
"fmt"
"reflect"
)
// EncodeArray encodes an array of arbitrary types to a cbor value
func EncodeArray(arr interface{}) []byte {
val := reflect.ValueOf(arr)
length := val.Len()
l := EncodeUint(uint64(length))
l[0] = l[0] | 0x80 // Major type 4
out := bytes.NewBuffer(l)
for i := 0; i < length; i++ {
out.Write(encode(val.Index(i)))
}
return out.Bytes()
}
// DecodeArray decodes a cbor value to an array of arbitrary types
func DecodeArray(fb byte, r *bytes.Reader) ([]interface{}, error) {
fb = fb & 0x1F
if fb == 31 {
return decodeIndefiniteArray(r)
}
l, err := DecodeUint(fb, r)
if err != nil {
return nil, err
}
out := make([]interface{}, l)
for i := 0; i < int(l); i++ {
fb, err := r.ReadByte()
if err != nil {
return nil, fmt.Errorf("expected %d more element(s) in array but input ends after item %d", int(l)-i-1, i+1)
}
v, err := decode(fb, r)
if err != nil {
return nil, err
}
out[i] = v
}
return out, nil
}
func decodeIndefiniteArray(r *bytes.Reader) ([]interface{}, error) {
out := make([]interface{}, 0, 10)
fb, err := r.ReadByte()
for ; err == nil && fb != 0xFF; fb, err = r.ReadByte() {
v, err := decode(fb, r)
if err != nil {
return nil, err
}
out = append(out, v)
}
if err != nil {
return nil, fmt.Errorf("failed to parse indefinite length array: %s", err.Error())
}
return out, nil
}