-
Notifications
You must be signed in to change notification settings - Fork 14
/
tlv.go
91 lines (67 loc) · 1.32 KB
/
tlv.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
package ykoath
import (
"fmt"
)
type tv struct {
tag byte
value []byte
}
type tvs []tv
// read will read a number of tagged values from a buffer
func read(buf []byte) (tvs tvs) {
var (
idx int
length int
tag byte
value []byte
)
for {
if len(buf)-idx == 0 {
return tvs
}
// read the tag
tag = buf[idx]
idx++
// read the length
length = int(buf[idx])
idx++
// read the value
value = buf[idx : idx+length]
idx = idx + length
// append the result
tvs = append(tvs, tv{
tag: tag,
value: value,
})
}
}
// Write produces a tlv or lv packet (if the tag is 0)
func write(tag byte, values ...[]byte) []byte {
var (
buf []byte
length int
data []byte
)
for _, value := range values {
// skip nil values (useful for optional tlv segments)
if value == nil {
continue
}
buf = append(buf, value...)
length = length + len(value)
}
// write the tag unless we skip it (useful for reusing Write for sending the
// APDU)
if tag != 0x00 {
data = append(data, tag)
}
// write some length unless this is a one byte value (e.g. for the PUT
// instruction's "property" byte)
if length > 1 {
data = append(data, byte(length))
}
if length > 255 {
panic(fmt.Sprintf("too much data too send (%d bytes)", length))
}
return append(data, buf...)
}