lokinet/llarp/util/json.cpp

60 lines
1.2 KiB
C++
Raw Normal View History

2019-02-15 23:04:04 +00:00
#include <util/json.hpp>
#include <util/string_view.hpp>
#include <cstring>
#include <string>
#include <vector>
2018-10-25 17:03:25 +00:00
2019-02-15 23:04:04 +00:00
namespace llarp
2018-10-25 17:03:25 +00:00
{
namespace json
{
struct NlohmannJSONParser : public IParser
2018-10-25 17:03:25 +00:00
{
NlohmannJSONParser(size_t contentSize)
: m_Buf(contentSize + 1), m_Offset(0)
2018-10-25 17:03:25 +00:00
{
assert(contentSize != 0);
2018-10-25 17:03:25 +00:00
}
std::vector< char > m_Buf;
size_t m_Offset;
bool
2019-07-30 23:42:13 +00:00
FeedData(const char* buf, size_t sz) override
2018-10-25 17:03:25 +00:00
{
2018-10-26 13:03:10 +00:00
if(m_Offset + sz > m_Buf.size() - 1)
2018-10-25 17:03:25 +00:00
return false;
std::copy(buf, buf + sz, m_Buf.begin());
2018-10-25 17:03:25 +00:00
m_Offset += sz;
m_Buf[m_Offset] = 0;
2018-10-25 17:03:25 +00:00
return true;
}
Result
2019-07-30 23:42:13 +00:00
Parse(nlohmann::json& obj) const override
2018-10-25 17:03:25 +00:00
{
if(m_Offset < m_Buf.size() - 1)
2018-10-25 17:03:25 +00:00
return eNeedData;
try
{
obj = nlohmann::json::parse(m_Buf.data());
return eDone;
}
catch(const nlohmann::json::exception&)
{
2018-10-25 17:03:25 +00:00
return eParseError;
}
2018-10-25 17:03:25 +00:00
}
};
IParser*
MakeParser(size_t contentSize)
{
return new NlohmannJSONParser(contentSize);
2018-10-25 17:03:25 +00:00
}
} // namespace json
2019-02-15 23:04:04 +00:00
} // namespace llarp