-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlv_transformer.c
74 lines (53 loc) · 1.31 KB
/
tlv_transformer.c
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
/**
* Copyright 2020 DriveX.Tech. All rights reserved.
*
* Licensed under the License.
*/
#include <string.h>
#include <assert.h>
#include "tlv_transformer.h"
int tlv_parse(const BYTE* data, tag_t* tag, WORD* len, BYTE* payload)
{
assert(data != NULL);
WORD _len;
int total_len = tlv_header_parse(data, tag, &_len);
if(len) {
*len = _len;
}
if(payload && _len > 0) {
memcpy(payload, data + 3, _len);
total_len += _len;
}
return total_len;
}
int tlv_generate(const tag_t tag, const WORD len, const BYTE* payload, BYTE* data)
{
assert(data != NULL);
int total_len = tlv_header_generate(tag, len, data);
if(payload && len > 0) {
memcpy(data + total_len, payload, len);
total_len += len;
}
return total_len;
}
int tlv_header_parse(const BYTE* data, tag_t* tag, WORD* len)
{
assert(data != NULL);
int total_len = -8;
if(tag) {
*tag = data[0];
}
WORD _len = data[1] + (data[2] << 8);
if(len) {
*len = _len;
}
return 3;
}
int tlv_header_generate(const tag_t tag, const WORD len, BYTE* data)
{
assert(data != NULL);
data[0] = tag;
data[1] = (BYTE)(len);
data[2] = (BYTE)(len >> 8);
return 3;
}