diff options
Diffstat (limited to 'source/RapidJsonHelper.hpp')
-rw-r--r-- | source/RapidJsonHelper.hpp | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/source/RapidJsonHelper.hpp b/source/RapidJsonHelper.hpp new file mode 100644 index 0000000..ac1f664 --- /dev/null +++ b/source/RapidJsonHelper.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include <rapidjson/document.h> +#include <cstring> +#include <string> +#include <string_view> + +#define BRUSSEL_JSON_GET(object, name, type, out, failAction) \ + { \ + auto it = (object).FindMember(name); \ + if (it == (object).MemberEnd()) failAction; \ + auto& value = it->value; \ + if (!value.Is<type>()) failAction; \ + (out) = value.Get<type>(); \ + } + +#define BRUSSEL_JSON_GET_DEFAULT(object, name, type, out, theDefault) \ + do { \ + auto it = (object).FindMember(name); \ + if (it == (object).MemberEnd()) { \ + (out) = theDefault; \ + break; \ + } \ + auto& value = it->value; \ + if (!value.Is<type>()) { \ + (out) = theDefault; \ + break; \ + } \ + (out) = value.Get<type>(); \ + } while (0); + +namespace rapidjson { + +inline const Value* GetProperty(const Value& value, Type type, std::string_view name) { + for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) { + if (it->name.GetStringLength() != name.size()) continue; + if (std::memcmp(it->name.GetString(), name.data(), name.size())) continue; + + return &it->value; + } + return nullptr; +} + +inline std::string_view AsStringView(const Value& value) { + return std::string_view(value.GetString(), value.GetStringLength()); +} + +inline std::string_view AsStringView(const GenericStringRef<char>& strRef) { + return std::string_view(strRef.s, strRef.length); +} + +inline std::string AsString(const Value& value) { + return std::string(value.GetString(), value.GetStringLength()); +} + +inline std::string AsString(const GenericStringRef<char>& strRef) { + return std::string(strRef.s, strRef.length); +} + +// RapidJson itself already provides std::string and const char* overloads +inline GenericStringRef<char> StringRef(std::string_view str) { + return GenericStringRef<char>( + str.data() ? str.data() : "", + str.size()); +} + +} // namespace rapidjson |