copy from an old project

This commit is contained in:
Mickael Bosch
2026-04-01 10:30:52 +02:00
commit 2813645669
3 changed files with 193 additions and 0 deletions

111
src/json.cpp Normal file
View File

@@ -0,0 +1,111 @@
#include <json.hpp>
static constexpr size_t BUF_SIZE = 64 + 1;
char _buf[BUF_SIZE];
size_t _idx;
size_t _indent;
JsonParser::HandlerBase* _handlers;
JsonParser::HandlerBase::HandlerBase()
{
_next = _handlers;
_handlers = this;
}
int JsonParser::json_printer(const char* bytes, size_t len, void* data)
{
// info("[[%d]]\n", len);
// for (size_t i = 0; i < len; i++)
// {
// info("%c", bytes[i]);
// }
// return 0;
for (size_t i = 0; i < len; i++)
{
bool nl = true;
if (bytes[i] == '}' || bytes[i] == ']')
{
nl = false;
_indent--;
info("\n");
for (size_t i = 0; i < _indent; i++)
{
info(" ");
}
}
info("%c", bytes[i]);
if (bytes[i] == '{' || bytes[i] == '[')
{
_indent++;
}
if (nl
&& (bytes[i] == ',' || bytes[i] == '{' || bytes[i] == '}'
|| bytes[i] == '[' || bytes[i] == ']'))
{
info("\n");
for (size_t i = 0; i < _indent; i++)
{
info(" ");
}
}
}
return 0;
}
void commit()
{
_buf[_idx] = '\0';
bool ok = false;
JsonParser::HandlerBase* h = _handlers;
while (h)
{
if (h->handle(_buf, _idx))
{
ok = true;
break;
}
h = h->_next;
};
_idx = 0;
if (!ok)
{
info("parse end error\n");
}
}
void flush_error()
{
_idx = 0;
error("input buffer overflow, flushing\n");
}
void JsonParser::init()
{
/* nothing to do */
}
void JsonParser::add_text(uint8_t* buf, size_t size)
{
for (size_t i = 0; i < size; i++)
{
if (buf[i] == ' ' || buf[i] == '\r' || buf[i] == '\n')
{
continue;
}
if (buf[i] == '}')
{
_buf[_idx] = buf[i];
_idx++;
commit();
continue;
}
_buf[_idx] = buf[i];
_idx++;
if (_idx >= BUF_SIZE)
{
flush_error();
}
}
}