2020-10-20 22:13:35 +02:00
|
|
|
/** A simple buffer for encoding streamed JSON messages.
|
2018-08-22 11:29:39 +02:00
|
|
|
*
|
2022-12-14 17:39:07 +01:00
|
|
|
* @author Steffen Vogel <post@steffenvogel.de>
|
2022-03-15 09:05:42 -04:00
|
|
|
* @copyright 2014-2022, Institute for Automation of Complex Power Systems, EONERC
|
2022-05-19 17:40:10 +02:00
|
|
|
* @license Apache License 2.0
|
2018-08-22 11:29:39 +02:00
|
|
|
*********************************************************************************/
|
|
|
|
|
2019-10-27 20:23:47 +01:00
|
|
|
#include <villas/compat.hpp>
|
|
|
|
#include <villas/buffer.hpp>
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2019-10-27 20:23:47 +01:00
|
|
|
using namespace villas;
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2020-10-20 22:13:35 +02:00
|
|
|
json_t * Buffer::decode()
|
2018-08-22 11:29:39 +02:00
|
|
|
{
|
2020-10-20 22:13:35 +02:00
|
|
|
json_t *j;
|
|
|
|
json_error_t err;
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2020-10-20 22:13:35 +02:00
|
|
|
j = json_loadb(data(), size(), JSON_DISABLE_EOF_CHECK, &err);
|
|
|
|
if (!j)
|
|
|
|
return nullptr;
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2022-12-02 17:16:44 +01:00
|
|
|
// Remove decoded JSON document from beginning
|
2020-10-20 22:13:35 +02:00
|
|
|
erase(begin(), begin() + err.position);
|
|
|
|
|
|
|
|
return j;
|
2018-08-22 11:29:39 +02:00
|
|
|
}
|
|
|
|
|
2020-10-20 22:13:35 +02:00
|
|
|
int Buffer::encode(json_t *j, int flags)
|
2018-08-22 11:29:39 +02:00
|
|
|
{
|
2020-10-20 22:13:35 +02:00
|
|
|
return json_dump_callback(j, callback, this, flags);
|
2018-08-22 11:29:39 +02:00
|
|
|
}
|
|
|
|
|
2020-10-20 22:13:35 +02:00
|
|
|
int Buffer::callback(const char *data, size_t len, void *ctx)
|
2018-08-22 11:29:39 +02:00
|
|
|
{
|
2020-10-20 22:13:35 +02:00
|
|
|
Buffer *b = static_cast<Buffer *>(ctx);
|
2018-08-22 11:29:39 +02:00
|
|
|
|
2022-12-02 17:16:44 +01:00
|
|
|
// Append junk of JSON to buffer
|
2020-10-20 22:13:35 +02:00
|
|
|
b->insert(b->end(), &data[0], &data[len]);
|
2018-08-22 11:29:39 +02:00
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|