Include already encoded CBOR #550
-
Is there a way to include already encoded CBOR, e.g.:
Maybe the encoder class is the wrong utility for this, but it is the only way I know to encode CBOR. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I have found a possibility to achieve this myself:
Probably quite obvious but this solution has not immediately occured to me. |
Beta Was this translation helpful? Give feedback.
-
The supported way is to regenerate the events from buf1 and feed them to encoder2, e.g. std::vector<uint8_t> buf1;
cbor::cbor_bytes_encoder encoder1(buf1);
encoder1.string_value("test1");
encoder1.flush();
std::vector<uint8_t> buf2;
cbor::cbor_bytes_encoder encoder2(buf2);
encoder2.begin_array(2); // will also work for indefinite array (omitting length)
encoder2.string_value("test2");
cbor::cbor_bytes_reader reader(buf1, encoder2); // feeds the string_value event into buf2
reader.read();
encoder2.end_array();
encoder2.flush();
auto j = cbor::decode_cbor<jsoncons::json>(buf2);
std::cout << j << "\n"; Output:
But if nobody's looking :-), you could always do a hack. For a definite or indefinite array, you can insert a 1 byte value, and then overwrite it with buf1, e.g. std::vector<uint8_t> buf1;
cbor::cbor_bytes_encoder encoder1(buf1);
encoder1.string_value("test1");
encoder1.flush();
std::vector<uint8_t> buf2;
cbor::cbor_bytes_encoder encoder2(buf2);
encoder2.begin_array(2);
encoder2.string_value("test2");
encoder2.null_value(); // insert one byte dummy value to track array length
buf2.insert(buf2.end() - 1, buf1.begin(), buf1.end()); // override dummy value
encoder2.end_array();
encoder2.flush(); For an object, you can just append buf1 after a key. |
Beta Was this translation helpful? Give feedback.
The supported way is to regenerate the events from buf1 and feed them to encoder2, e.g.
Output:
But …