Using std::optional in the fields array; fixes the test and increases safety

This commit is contained in:
Patrick Urbanke
2023-11-11 23:33:15 +01:00
parent 5efa9df16e
commit 2a948e809a
4 changed files with 184 additions and 186 deletions
+2 -2
View File
@@ -85,9 +85,9 @@ struct Reader {
}
template <size_t size, class FunctionType>
std::array<InputVarType, size> to_fields_array(
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
std::array<InputVarType, size> f_arr;
std::array<std::optional<InputVarType>, size> f_arr;
const auto keys = _obj.Keys();
const auto values = _obj.Values();
+122 -123
View File
@@ -22,153 +22,152 @@ namespace rfl {
namespace json {
struct Reader {
struct YYJSONInputArray {
YYJSONInputArray(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputArray {
YYJSONInputArray(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputObject {
YYJSONInputObject(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputObject {
YYJSONInputObject(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputVar {
YYJSONInputVar() : val_(nullptr) {}
YYJSONInputVar(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputVar {
YYJSONInputVar() : val_(nullptr) {}
YYJSONInputVar(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
using InputArrayType = YYJSONInputArray;
using InputObjectType = YYJSONInputObject;
using InputVarType = YYJSONInputVar;
using InputArrayType = YYJSONInputArray;
using InputObjectType = YYJSONInputObject;
using InputVarType = YYJSONInputVar;
template <class T, class = void>
struct has_from_json_obj : std::false_type {};
template <class T, class = void>
struct has_from_json_obj : std::false_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
T, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<
T,
std::enable_if_t<std::is_invocable_r<
T, decltype(T::from_json_obj), typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
static constexpr bool has_custom_constructor = has_from_json_obj<T>::value;
template <class T>
static constexpr bool has_custom_constructor = has_from_json_obj<T>::value;
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str()));
if (!var.val_) {
return rfl::Error("Object contains no field named '" + _name +
"'.");
}
return var;
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str()));
if (!var.val_) {
return rfl::Error("Object contains no field named '" + _name + "'.");
}
return var;
}
bool is_empty(const InputVarType _var) const noexcept {
return !_var.val_ || yyjson_is_null(_var.val_);
}
bool is_empty(const InputVarType _var) const noexcept {
return !_var.val_ || yyjson_is_null(_var.val_);
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
const auto r = yyjson_get_str(_var.val_);
if (r == NULL) {
return rfl::Error("Could not cast to string.");
}
return std::string(r);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!yyjson_is_bool(_var.val_)) {
return rfl::Error("Could not cast to boolean.");
}
return yyjson_get_bool(_var.val_);
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!yyjson_is_num(_var.val_)) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(yyjson_get_num(_var.val_));
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!yyjson_is_int(_var.val_)) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_int(_var.val_));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
const auto r = yyjson_get_str(_var.val_);
if (r == NULL) {
return rfl::Error("Could not cast to string.");
}
return std::string(r);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!yyjson_is_bool(_var.val_)) {
return rfl::Error("Could not cast to boolean.");
}
return yyjson_get_bool(_var.val_);
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!yyjson_is_num(_var.val_)) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(yyjson_get_num(_var.val_));
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!yyjson_is_int(_var.val_)) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_int(_var.val_));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(
const InputVarType _var) const noexcept {
if (!yyjson_is_arr(_var.val_)) {
return rfl::Error("Could not cast to array!");
}
return InputArrayType(_var.val_);
rfl::Result<InputArrayType> to_array(const InputVarType _var) const noexcept {
if (!yyjson_is_arr(_var.val_)) {
return rfl::Error("Could not cast to array!");
}
return InputArrayType(_var.val_);
}
template <size_t size, class FunctionType>
std::array<InputVarType, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<InputVarType, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const char* k = yyjson_get_str(key);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_arr;
template <size_t size, class FunctionType>
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<std::optional<InputVarType>, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const char* k = yyjson_get_str(key);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_arr;
}
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
auto p = std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace_back(std::move(p));
}
return m;
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
auto p = std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace_back(std::move(p));
}
return m;
}
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
if (!yyjson_is_obj(_var.val_)) {
return rfl::Error("Could not cast to object!");
}
return InputObjectType(_var.val_);
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
if (!yyjson_is_obj(_var.val_)) {
return rfl::Error("Could not cast to object!");
}
return InputObjectType(_var.val_);
}
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
std::vector<InputVarType> vec;
yyjson_val* val;
yyjson_arr_iter iter;
yyjson_arr_iter_init(_arr.val_, &iter);
while ((val = yyjson_arr_iter_next(&iter))) {
vec.push_back(InputVarType(val));
}
return vec;
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
std::vector<InputVarType> vec;
yyjson_val* val;
yyjson_arr_iter iter;
yyjson_arr_iter_init(_arr.val_, &iter);
while ((val = yyjson_arr_iter_next(&iter))) {
vec.push_back(InputVarType(val));
}
return vec;
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
try {
return T::from_json_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
try {
return T::from_json_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
}
};
} // namespace json
+44 -47
View File
@@ -5,6 +5,7 @@
#include <concepts>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
@@ -19,62 +20,58 @@ concept IsReader = requires(R r, std::string name,
typename R::InputArrayType arr,
typename R::InputObjectType obj,
typename R::InputVarType var) {
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Retrieves a particular field from an object.
{
r.get_field(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Retrieves a particular field from an object.
{
r.get_field(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{ r.template to_basic_type<T>(var) } -> std::same_as<rfl::Result<T>>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{ r.template to_basic_type<T>(var) } -> std::same_as<rfl::Result<T>>;
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
{
r.template to_fields_array<6>(fct, obj)
} -> std::same_as<std::array<typename R::InputVarType, 6>>;
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
{
r.template to_fields_array<6>(fct, obj)
} -> std::same_as<std::array<std::optional<typename R::InputVarType>, 6>>;
/// Casts var as an InputArrayType.
{
r.to_array(var)
} -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Casts var as an InputArrayType.
{ r.to_array(var) } -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
{
r.to_map(obj)
} -> std::same_as<
std::vector<std::pair<std::string, typename R::InputVarType>>>;
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
{
r.to_map(obj)
} -> std::same_as<
std::vector<std::pair<std::string, typename R::InputVarType>>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Iterates through an array and writes the contained vars into
/// a vector.
{ r.to_vec(arr) } -> std::same_as<std::vector<typename R::InputVarType>>;
/// Iterates through an array and writes the contained vars into
/// a vector.
{ r.to_vec(arr) } -> std::same_as<std::vector<typename R::InputVarType>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{
r.template use_custom_constructor<T>(var)
} -> std::same_as<rfl::Result<T>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{ r.template use_custom_constructor<T>(var) } -> std::same_as<rfl::Result<T>>;
};
} // namespace parsing
+16 -14
View File
@@ -370,7 +370,8 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
template <class... Args>
static Result<NamedTuple<FieldTypes...>> build_named_tuple_recursively(
const R& _r,
const std::array<InputVarType, sizeof...(FieldTypes)>& _fields_vec,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
Args&&... _args) noexcept {
constexpr auto i = sizeof...(Args);
@@ -382,32 +383,32 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<i>(_fields_vec);
const auto& f = std::get<i>(_fields_arr);
if (_r.is_empty(f)) {
if (!f) {
if constexpr (is_required<ValueType>()) {
const auto key = FieldType::name_.str();
return collect_errors<i + 1>(
_r, _fields_vec,
_r, _fields_arr,
std::vector<Error>(
{Error("Field named '" + key + "' not found!")}));
} else {
return build_named_tuple_recursively(
_r, _fields_vec, std::move(_args)..., FieldType(ValueType()));
_r, _fields_arr, std::move(_args)..., FieldType(ValueType()));
}
}
const auto build = [&](auto&& _value) {
return build_named_tuple_recursively(
_r, _fields_vec, std::move(_args)..., FieldType(std::move(_value)));
_r, _fields_arr, std::move(_args)..., FieldType(std::move(_value)));
};
const auto handle_error = [&](Error&& _error) {
return collect_errors<i + 1>(_r, _fields_vec,
return collect_errors<i + 1>(_r, _fields_arr,
std::vector<Error>({std::move(_error)}));
};
return get_value<FieldType>(_r, f).or_else(handle_error).and_then(build);
return get_value<FieldType>(_r, *f).or_else(handle_error).and_then(build);
}
}
@@ -416,7 +417,8 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
template <int _i>
static Error collect_errors(
const R& _r,
const std::array<InputVarType, sizeof...(FieldTypes)>& _fields_vec,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
std::vector<Error> _errors) noexcept {
if constexpr (_i == sizeof...(FieldTypes)) {
if (_errors.size() == 1) {
@@ -435,14 +437,14 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<_i>(_fields_vec);
const auto& f = std::get<_i>(_fields_arr);
if (_r.is_empty(f)) {
if (!f) {
if constexpr (is_required<ValueType>()) {
const auto key = FieldType::name_.str();
_errors.emplace_back(Error("Field named '" + key + "' not found."));
}
return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors));
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
}
const auto add_error_if_applicable =
@@ -451,9 +453,9 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
return _error;
};
get_value<FieldType>(_r, f).or_else(add_error_if_applicable);
get_value<FieldType>(_r, *f).or_else(add_error_if_applicable);
return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors));
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
}
}