Wiki
cbor-lite / Home
Welcome
Welcome to your CBOR-lite wiki!
This wiki is intended to provide documentation and other useful information concerning the use of CBOR-lite.
This wiki presently allows anyone to edit it... but if it gets spammed or otherwise abused, it will get locked down.
See also:
CBOR-lite Example
Consider the C++ structure representing an application protocol data unit:
struct Message {
enum class Type { request = 0, response };
Type type = Type::request;
bool accepted = false;
std::vector<unsigned char> id;
std::vector<char> payload;
}
This could be encoded as a CBOR array of 4 items, a unsigned integer, a boolean, a byte string, and a text string, as follows:
using CborLite;
template <typename Buffer>
size_t encodeMessage(Buffer& buffer, const Message& m) {
auto len = encodeArraySize(buffer, 4);
len += encodeUnsigned(buffer, static_cast<unsigned long>(m.type));
len += encodeBool(buffer, m.accepted);
len += encodeBytes(buffer, m.id);
len += encodeText(buffer, m.payload);
return len;
}
and decoded:
using CborLite;
template <typename InputIterator>
size_t decodeMessage(InputIterator& pos, InputIterator end, Message& m, Flags flags = Flag::none) {
size_t nItems = 0;
auto len = decodeArraySize(pos, end, nItems, flags);
if (nItems != 4) throw Exception("not the right number of items");
unsigned long type;
len += decodeUnsigned(pos, end, type, flags);
m.type = static_cast<Message::Type>(type);
len += decodeBool(pos, end, m.accepted, flags);
len += decodeBytes(pos, end, m.id);
len += decodeText(pos, end, m.payload, flags);
return len;
}
Note this example doesn't include as much input checking as one would find in a robust decoder.
Updated