1
1
Fork 0
mirror of https://github.com/oxen-io/lokinet synced 2023-12-14 06:53:00 +01:00
lokinet/llarp/util/json.cpp

60 lines
1.2 KiB
C++
Raw Normal View History

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