Files
trmnl_server_cpp/helpers.cpp

121 lines
1.8 KiB
C++

#include "helpers.h"
#include <fstream>
using nlohmann::json;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istream;
using std::ostream;
using std::string;
bool read_file_json(json& j, const string& filename, ostream* log)
{
ifstream file(filename);
if (!file.is_open())
{
if (nullptr != log)
{
*log << "Could not open file to read - " << filename << endl;
}
return false;
}
return read_stream_json(j, file, log);
}
bool read_stream_json(json& j, istream& in, ostream* log)
{
// Parse with comments
try
{
j = json::parse(in, nullptr, true, true);
}
catch (const std::exception &e)
{
if (nullptr != log)
{
*log << e.what() << endl;
}
return false;
}
return true;
}
bool write_file_json(const json& j, const string& filename, ostream* log)
{
ofstream file(filename);
if (!file.is_open())
{
if (nullptr != log)
{
*log << "Could not open file to write - " << filename << endl;
}
return false;
}
file << j.dump(4) << endl;
return true;
}
bool json_extract(const json& j, const string& key, string& out)
{
bool result = false;
if (j.contains(key) && j[key].is_string())
{
out = j[key];
result = true;
}
return result;
}
bool json_extract(const json& j, const string& key, int& out)
{
bool result = false;
if (j.contains(key) && j[key].is_number_integer())
{
out = j[key];
result = true;
}
return result;
}
bool json_extract(const json& j, const string& key, bool& out)
{
bool result = false;
if (j.contains(key) && j[key].is_boolean())
{
out = j[key];
result = true;
}
return result;
}
bool json_extract(const json& j, const string& key, uint16_t& out)
{
bool result = false;
if (j.contains(key) && j[key].is_number_integer())
{
if ((j[key] >= 0) && (j[key] <= UINT16_MAX))
{
out = j[key];
result = true;
}
}
return result;
}