Files

378 lines
14 KiB
C++

#pragma once
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <map>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// Small, dependency-free JSON value/parser for DUO-RDP's local config and
// newline-delimited pipe protocol. It deliberately supports the complete JSON
// grammar used by the product, while keeping the native service self-contained.
namespace duo {
class Json final {
public:
enum class Type { Null, Bool, Number, String, Array, Object };
using Array = std::vector<Json>;
using Object = std::map<std::string, Json, std::less<>>;
Json() = default;
Json(std::nullptr_t) : type_(Type::Null) {}
Json(bool value) : type_(Type::Bool), bool_(value) {}
Json(int value) : type_(Type::Number), number_(static_cast<double>(value)) {}
Json(std::int64_t value) : type_(Type::Number), number_(static_cast<double>(value)) {}
Json(double value) : type_(Type::Number), number_(value) {}
Json(const char* value) : type_(Type::String), string_(value ? value : "") {}
Json(std::string value) : type_(Type::String), string_(std::move(value)) {}
Json(Array value) : type_(Type::Array), array_(std::move(value)) {}
Json(Object value) : type_(Type::Object), object_(std::move(value)) {}
[[nodiscard]] Type type() const noexcept { return type_; }
[[nodiscard]] bool is_null() const noexcept { return type_ == Type::Null; }
[[nodiscard]] bool is_bool() const noexcept { return type_ == Type::Bool; }
[[nodiscard]] bool is_number() const noexcept { return type_ == Type::Number; }
[[nodiscard]] bool is_string() const noexcept { return type_ == Type::String; }
[[nodiscard]] bool is_array() const noexcept { return type_ == Type::Array; }
[[nodiscard]] bool is_object() const noexcept { return type_ == Type::Object; }
[[nodiscard]] bool bool_or(bool fallback = false) const noexcept {
return is_bool() ? bool_ : fallback;
}
[[nodiscard]] int int_or(int fallback = 0) const noexcept {
if (!is_number() || !std::isfinite(number_)) return fallback;
return static_cast<int>(number_);
}
[[nodiscard]] std::string string_or(std::string fallback = {}) const {
return is_string() ? string_ : fallback;
}
[[nodiscard]] const Array& array_or_empty() const noexcept {
static const Array empty;
return is_array() ? array_ : empty;
}
[[nodiscard]] const Object& object_or_empty() const noexcept {
static const Object empty;
return is_object() ? object_ : empty;
}
[[nodiscard]] const Json* find(std::string_view key) const noexcept {
if (!is_object()) return nullptr;
const auto it = object_.find(key);
return it == object_.end() ? nullptr : &it->second;
}
[[nodiscard]] Json* find(std::string_view key) noexcept {
if (!is_object()) return nullptr;
const auto it = object_.find(key);
return it == object_.end() ? nullptr : &it->second;
}
Json& operator[](const std::string& key) {
if (!is_object()) {
type_ = Type::Object;
object_.clear();
string_.clear();
array_.clear();
}
return object_[key];
}
[[nodiscard]] std::string dump() const {
std::string out;
dump_into(out);
return out;
}
static Json parse(const std::string& input) {
Parser parser(input);
Json value = parser.parse_value();
parser.skip_space();
if (!parser.at_end()) throw std::runtime_error("trailing JSON input");
return value;
}
private:
class Parser final {
public:
explicit Parser(const std::string& input) : input_(input) {}
void skip_space() {
while (pos_ < input_.size() && std::isspace(static_cast<unsigned char>(input_[pos_]))) ++pos_;
}
[[nodiscard]] bool at_end() const noexcept { return pos_ >= input_.size(); }
Json parse_value() {
skip_space();
if (at_end()) throw std::runtime_error("unexpected end of JSON");
switch (input_[pos_]) {
case 'n': consume_literal("null"); return Json();
case 't': consume_literal("true"); return Json(true);
case 'f': consume_literal("false"); return Json(false);
case '"': return Json(parse_string());
case '[': return parse_array();
case '{': return parse_object();
default: return Json(parse_number());
}
}
private:
void consume_literal(std::string_view literal) {
if (input_.compare(pos_, literal.size(), literal) != 0) throw std::runtime_error("invalid JSON literal");
pos_ += literal.size();
}
char take() {
if (at_end()) throw std::runtime_error("unexpected end of JSON");
return input_[pos_++];
}
void expect(char expected) {
if (take() != expected) throw std::runtime_error("invalid JSON syntax");
}
static unsigned hex_value(char c) {
if (c >= '0' && c <= '9') return static_cast<unsigned>(c - '0');
if (c >= 'a' && c <= 'f') return static_cast<unsigned>(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return static_cast<unsigned>(c - 'A' + 10);
throw std::runtime_error("invalid JSON unicode escape");
}
unsigned parse_u16() {
unsigned value = 0;
for (int i = 0; i < 4; ++i) value = (value << 4U) | hex_value(take());
return value;
}
static void append_utf8(std::string& out, std::uint32_t cp) {
if (cp <= 0x7fU) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7ffU) {
out.push_back(static_cast<char>(0xc0U | (cp >> 6U)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
} else if (cp <= 0xffffU) {
out.push_back(static_cast<char>(0xe0U | (cp >> 12U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
} else {
out.push_back(static_cast<char>(0xf0U | (cp >> 18U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 12U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
}
}
std::string parse_string() {
expect('"');
std::string out;
while (!at_end()) {
const char c = take();
if (c == '"') return out;
if (static_cast<unsigned char>(c) < 0x20U) throw std::runtime_error("control character in JSON string");
if (c != '\\') {
out.push_back(c);
continue;
}
switch (take()) {
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
case '/': out.push_back('/'); break;
case 'b': out.push_back('\b'); break;
case 'f': out.push_back('\f'); break;
case 'n': out.push_back('\n'); break;
case 'r': out.push_back('\r'); break;
case 't': out.push_back('\t'); break;
case 'u': {
std::uint32_t cp = parse_u16();
if (cp >= 0xd800U && cp <= 0xdbffU) {
if (take() != '\\' || take() != 'u') throw std::runtime_error("unpaired JSON surrogate");
const std::uint32_t low = parse_u16();
if (low < 0xdc00U || low > 0xdfffU) throw std::runtime_error("invalid JSON surrogate");
cp = 0x10000U + ((cp - 0xd800U) << 10U) + (low - 0xdc00U);
}
append_utf8(out, cp);
break;
}
default: throw std::runtime_error("invalid JSON escape");
}
}
throw std::runtime_error("unterminated JSON string");
}
double parse_number() {
const size_t start = pos_;
if (input_[pos_] == '-') ++pos_;
if (pos_ >= input_.size()) throw std::runtime_error("invalid JSON number");
if (input_[pos_] == '0') {
++pos_;
} else {
if (!std::isdigit(static_cast<unsigned char>(input_[pos_]))) throw std::runtime_error("invalid JSON number");
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
}
if (pos_ < input_.size() && input_[pos_] == '.') {
++pos_;
const size_t fraction = pos_;
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
if (fraction == pos_) throw std::runtime_error("invalid JSON fraction");
}
if (pos_ < input_.size() && (input_[pos_] == 'e' || input_[pos_] == 'E')) {
++pos_;
if (pos_ < input_.size() && (input_[pos_] == '+' || input_[pos_] == '-')) ++pos_;
const size_t exponent = pos_;
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
if (exponent == pos_) throw std::runtime_error("invalid JSON exponent");
}
const std::string token = input_.substr(start, pos_ - start);
char* end = nullptr;
const double value = std::strtod(token.c_str(), &end);
if (!end || *end != '\0' || !std::isfinite(value)) throw std::runtime_error("invalid JSON number");
return value;
}
Json parse_array() {
expect('[');
Array result;
skip_space();
if (!at_end() && input_[pos_] == ']') {
++pos_;
return Json(std::move(result));
}
for (;;) {
result.emplace_back(parse_value());
skip_space();
const char separator = take();
if (separator == ']') break;
if (separator != ',') throw std::runtime_error("invalid JSON array");
}
return Json(std::move(result));
}
Json parse_object() {
expect('{');
Object result;
skip_space();
if (!at_end() && input_[pos_] == '}') {
++pos_;
return Json(std::move(result));
}
for (;;) {
skip_space();
if (at_end() || input_[pos_] != '"') throw std::runtime_error("invalid JSON object key");
std::string key = parse_string();
skip_space();
expect(':');
result[std::move(key)] = parse_value();
skip_space();
const char separator = take();
if (separator == '}') break;
if (separator != ',') throw std::runtime_error("invalid JSON object");
}
return Json(std::move(result));
}
const std::string& input_;
size_t pos_ = 0;
};
static void append_escaped(std::string& out, const std::string& value) {
out.push_back('"');
static constexpr char hex[] = "0123456789abcdef";
for (const unsigned char c : value) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20U) {
out += "\\u00";
out.push_back(hex[(c >> 4U) & 0x0fU]);
out.push_back(hex[c & 0x0fU]);
} else {
out.push_back(static_cast<char>(c));
}
}
}
out.push_back('"');
}
void dump_into(std::string& out) const {
switch (type_) {
case Type::Null: out += "null"; break;
case Type::Bool: out += bool_ ? "true" : "false"; break;
case Type::Number: {
const std::string number = std::to_string(number_);
const size_t point = number.find('.');
if (point == std::string::npos) {
out += number;
} else {
size_t end = number.size();
while (end > point + 1 && number[end - 1] == '0') --end;
if (end == point + 1) --end;
out.append(number, 0, end);
}
break;
}
case Type::String: append_escaped(out, string_); break;
case Type::Array:
out.push_back('[');
for (size_t i = 0; i < array_.size(); ++i) {
if (i) out.push_back(',');
array_[i].dump_into(out);
}
out.push_back(']');
break;
case Type::Object:
out.push_back('{');
for (auto it = object_.begin(); it != object_.end(); ++it) {
if (it != object_.begin()) out.push_back(',');
append_escaped(out, it->first);
out.push_back(':');
it->second.dump_into(out);
}
out.push_back('}');
break;
}
}
Type type_ = Type::Null;
bool bool_ = false;
double number_ = 0.0;
std::string string_;
Array array_;
Object object_;
};
inline const Json* json_member(const Json& value, std::string_view key) noexcept {
return value.find(key);
}
inline bool json_bool(const Json& value, std::string_view key, bool fallback = false) noexcept {
const Json* member = value.find(key);
return member ? member->bool_or(fallback) : fallback;
}
inline int json_int(const Json& value, std::string_view key, int fallback = 0) noexcept {
const Json* member = value.find(key);
return member ? member->int_or(fallback) : fallback;
}
inline std::string json_string(const Json& value, std::string_view key, std::string fallback = {}) {
const Json* member = value.find(key);
return member ? member->string_or(std::move(fallback)) : fallback;
}
} // namespace duo