-
Notifications
You must be signed in to change notification settings - Fork 0
/
CborExample.cpp
50 lines (39 loc) · 1.35 KB
/
CborExample.cpp
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
// SPDX-License-Identifier: BSD-3-Clause
#include <iomanip>
#include <iostream>
#include <kargmap/CborSerializer.hpp>
using namespace entazza;
int main(int argc, char **argv) {
KArgMap m;
m.set("count", uint16_t(1234));
m.set("name", "Glenn");
// Echo as JSON
std::cout << m << std::endl;
// Allocate space for cbor serialization
uint8_t cborBuffer[64];
CborSerializer cborEncoder(cborBuffer, sizeof(cborBuffer));
// Initiate encoding into the buffer
cborEncoder.encode(m);
auto encodingError =
cborEncoder.getResult(); // 0 for success, non-zero insufficient space
auto payloadBytes =
cborEncoder.bytesSerialized(); // number of bytes serialized
auto bytesRequired =
cborEncoder.bytesNeeded(); // bytes needed (if insufficient space)
std::cout << "CBOR Payload size = " << payloadBytes
<< ", error=" << cborEncoder.getResult()
<< ", bytes required = " << bytesRequired << std::endl;
// Dump in hex
std::cout << "hex: ";
for (auto i = 0; i < payloadBytes; i++) {
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< int(cborBuffer[i]);
}
std::cout << std::endl;
// Deserialize a CBOR binary array into a KArgMap.
CborSerializer cborDecoder(cborBuffer, payloadBytes);
auto m2 = cborDecoder.decode();
// Echo as JSON
std::cout << m2 << std::endl;
return 0;
}