Add rfl::DefaultIfMissing; fixes #163, #167, #185 (#189)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-09-15 19:38:33 +02:00
committed by GitHub
parent dfc24ad932
commit 54c2a84650
12 changed files with 471 additions and 3 deletions
+2
View File
@@ -44,3 +44,5 @@ Now, the field "children" is missing for Bart, Lisa and Maggie:
```json
{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]}
```
**NOTE**: If you want to explicitly set default values for your fields and/or you want all fields to be optional, please consider using the `rfl::DefaultIfMissing` processor. You will find more information in the section on processors in this documentation.
+42 -1
View File
@@ -34,6 +34,7 @@ The resulting JSON string looks like this:
reflect-cpp currently supports the following processors:
- `rfl::AddStructName`
- `rfl::DefaultIfMissing`
- `rfl::NoFieldNames`
- `rfl::NoOptionals`
- `rfl::UnderlyingEnums`
@@ -42,7 +43,7 @@ reflect-cpp currently supports the following processors:
### `rfl::AddStructName`
It is also possible to add the struct name as an addtional field, like this:
It is also possible to add the struct name as an additional field, like this:
```cpp
const auto json_string =
@@ -58,6 +59,46 @@ The resulting JSON string looks like this:
{"type":"Person","first_name":"Homer","last_name":"Simpson","age":45}
```
### `rfl::DefaultIfMissing`
The `rfl::DefaultIfMissing` processor is only relevant for reading data. For writing data, it will make no difference.
Usually, when fields are missing in the input data, this will lead to an error
(unless they are optional fields).
But if you pass the `rfl::DefaultIfMissing` processor, then missing fields will be
replaced by their default value.
For instance, consider the following struct:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town;
};
```
Suppose you are reading a JSON like this:
```json
{"first_name":"Homer"}
```
```cpp
rfl::json::read<Person, rfl::DefaultIfMissing>(json_string);
```
Then the resulting struct will be equivalent to what you would
have gotten had you read the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","town":""}
```
`last_name` and `town` have been replaced by the default values.
Because you have not passed a default value to town, the default value
of the type is used instead.
### `rfl::NoFieldNames`
We can also remove the field names altogether:
+1
View File
@@ -14,6 +14,7 @@
#include "rfl/Binary.hpp"
#include "rfl/Box.hpp"
#include "rfl/Bytestring.hpp"
#include "rfl/DefaultIfMissing.hpp"
#include "rfl/Description.hpp"
#include "rfl/ExtraFields.hpp"
#include "rfl/Field.hpp"
+19
View File
@@ -0,0 +1,19 @@
#ifndef RFL_DEFAULTIFMISSING_HPP_
#define RFL_DEFAULTIFMISSING_HPP_
namespace rfl {
/// This is a "fake" processor - it doesn't do much in itself, but its
/// inclusion instructs the parsers to use the default values for missing
/// fields.
struct DefaultIfMissing {
public:
template <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};
} // namespace rfl
#endif
+6
View File
@@ -3,6 +3,7 @@
#include <type_traits>
#include "internal/is_default_if_missing_v.hpp"
#include "internal/is_no_field_names_v.hpp"
#include "internal/is_no_optionals_v.hpp"
#include "internal/is_underlying_enums_v.hpp"
@@ -15,6 +16,7 @@ struct Processors;
template <>
struct Processors<> {
static constexpr bool all_required_ = false;
static constexpr bool default_if_missing_ = false;
static constexpr bool no_field_names_ = false;
static constexpr bool underlying_enums_ = false;
@@ -30,6 +32,10 @@ struct Processors<Head, Tail...> {
std::disjunction_v<internal::is_no_optionals<Head>,
internal::is_no_optionals<Tail>...>;
static constexpr bool default_if_missing_ =
std::disjunction_v<internal::is_default_if_missing<Head>,
internal::is_default_if_missing<Tail>...>;
static constexpr bool no_field_names_ =
std::disjunction_v<internal::is_no_field_names<Head>,
internal::is_no_field_names<Tail>...>;
@@ -0,0 +1,29 @@
#ifndef RFL_INTERNAL_ISDEFAULTIFMISSING_HPP_
#define RFL_INTERNAL_ISDEFAULTIFMISSING_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "../DefaultIfMissing.hpp"
namespace rfl {
namespace internal {
template <class T>
class is_default_if_missing;
template <class T>
class is_default_if_missing : public std::false_type {};
template <>
class is_default_if_missing<DefaultIfMissing> : public std::true_type {};
template <class T>
constexpr bool is_default_if_missing_v =
is_default_if_missing<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;
} // namespace internal
} // namespace rfl
#endif
+48 -1
View File
@@ -23,6 +23,8 @@
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "ViewReader.hpp"
#include "ViewReaderWithDefault.hpp"
#include "ViewReaderWithDefaultAndStrippedFieldNames.hpp"
#include "ViewReaderWithStrippedFieldNames.hpp"
#include "is_empty.hpp"
#include "is_required.hpp"
@@ -48,6 +50,12 @@ struct NamedTupleParser {
ViewReaderWithStrippedFieldNames<R, W, NamedTupleType, ProcessorsType>,
ViewReader<R, W, NamedTupleType, ProcessorsType>>;
using ViewReaderWithDefaultType = std::conditional_t<
_no_field_names,
ViewReaderWithDefaultAndStrippedFieldNames<R, W, NamedTupleType,
ProcessorsType>,
ViewReaderWithDefault<R, W, NamedTupleType, ProcessorsType>>;
using InputObjectOrArrayType =
std::conditional_t<_no_field_names, typename R::InputArrayType,
typename R::InputObjectType>;
@@ -84,7 +92,7 @@ struct NamedTupleParser {
return *ptr;
}
/// Reads the data into a view.
/// Reads the data into a view assuming no default values.
static std::optional<Error> read_view(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...>* _view) noexcept {
@@ -103,6 +111,25 @@ struct NamedTupleParser {
}
}
/// Reads the data into a view assuming default values.
static std::optional<Error> read_view_with_default(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...>* _view) noexcept {
if constexpr (_no_field_names) {
auto arr = _r.to_array(_var);
if (!arr) [[unlikely]] {
return arr.error();
}
return read_object_or_array_with_default(_r, *arr, _view);
} else {
auto obj = _r.to_object(_var);
if (!obj) [[unlikely]] {
return obj.error();
}
return read_object_or_array_with_default(_r, *obj, _view);
}
}
template <class P>
static void write(const W& _w, const NamedTuple<FieldTypes...>& _tup,
const P& _parent) noexcept {
@@ -277,6 +304,26 @@ struct NamedTupleParser {
}
return std::nullopt;
}
static std::optional<Error> read_object_or_array_with_default(
const R& _r, const InputObjectOrArrayType& _obj_or_arr,
NamedTupleType* _view) noexcept {
std::vector<Error> errors;
const auto reader = ViewReaderWithDefaultType(&_r, _view, &errors);
std::optional<Error> err;
if constexpr (_no_field_names) {
err = _r.read_array(reader, _obj_or_arr);
} else {
err = _r.read_object(reader, _obj_or_arr);
}
if (err) {
return err;
}
if (errors.size() != 0) {
return to_single_error_message(errors);
}
return std::nullopt;
}
};
} // namespace parsing
+23 -1
View File
@@ -68,7 +68,11 @@ struct Parser {
return Parser<R, W, ReflectionType, ProcessorsType>::read(_r, _var)
.and_then(wrap_in_t);
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
return read_struct(_r, _var);
if constexpr (ProcessorsType::default_if_missing_) {
return read_struct_with_default(_r, _var);
} else {
return read_struct(_r, _var);
}
} else if constexpr (std::is_enum_v<T>) {
if constexpr (ProcessorsType::underlying_enums_) {
return static_cast<T>(*_r.template to_basic_type<std::underlying_type_t<T>>(_var));
@@ -262,6 +266,24 @@ struct Parser {
return std::move(*ptr);
}
/// This is actually more straight-forward than the standard case - we just
/// allocate a struct and then fill it. But it is less efficient and it
/// assumes that all values on the struct have a default constructor, so we
/// only use it when the DefaultIfMissing preprocessor is added.
static Result<T> read_struct_with_default(const R& _r,
const InputVarType& _var) {
auto t = T{};
auto view = ProcessorsType::template process<T>(to_view(t));
using ViewType = std::remove_cvref_t<decltype(view)>;
const auto err =
Parser<R, W, ViewType, ProcessorsType>::read_view_with_default(_r, _var,
&view);
if (err) [[unlikely]] {
return *err;
}
return t;
}
static std::string replace_non_alphanumeric(std::string _str) {
for (auto& ch : _str) {
ch = std::isalnum(ch) ? ch : '_';
@@ -0,0 +1,137 @@
#ifndef RFL_PARSING_VIEWREADERWITHDEFAULT_HPP_
#define RFL_PARSING_VIEWREADERWITHDEFAULT_HPP_
#include <array>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
#include "../Result.hpp"
#include "../Tuple.hpp"
#include "../internal/is_array.hpp"
namespace rfl::parsing {
template <class R, class W, class ViewType, class ProcessorsType>
class ViewReaderWithDefault {
private:
using InputVarType = typename R::InputVarType;
static constexpr size_t size_ = ViewType::size();
public:
ViewReaderWithDefault(const R* _r, ViewType* _view,
std::vector<Error>* _errors)
: r_(_r), view_(_view), errors_(_errors) {}
~ViewReaderWithDefault() = default;
/// Assigns the parsed version of _var to the field signified by _name, if
/// such a field exists in the underlying view.
void read(const std::string_view& _name, const InputVarType& _var) const {
assign_to_matching_field(*r_, _name, _var, view_, errors_,
std::make_integer_sequence<int, size_>());
}
private:
template <int i>
static void assign_if_field_matches(const R& _r,
const std::string_view& _current_name,
const auto& _var, auto* _view,
auto* _errors, bool* _already_assigned) {
using FieldType = tuple_element_t<i, typename ViewType::Fields>;
using OriginalType = typename FieldType::Type;
using T =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
constexpr auto name = FieldType::name();
if (!(*_already_assigned) && _current_name == name) {
*_already_assigned = true;
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
if (!res) {
_errors->emplace_back(Error("Failed to parse field '" +
std::string(name) +
"': " + std::move(res.error()->what())));
return;
}
if constexpr (std::is_pointer_v<OriginalType>) {
move_to(rfl::get<i>(*_view), &(*res));
} else {
rfl::get<i>(*_view) = std::move(*res);
}
}
}
template <int _pos>
static void assign_to_extra_fields(const R& _r,
const std::string_view& _current_name,
const auto& _var, auto* _view,
auto* _errors) {
auto* extra_fields = _view->template get<_pos>();
using ExtraFieldsType =
std::remove_cvref_t<std::remove_pointer_t<decltype(extra_fields)>>;
using T = std::remove_cvref_t<
std::remove_pointer_t<typename ExtraFieldsType::Type>>;
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
if (!res) {
_errors->emplace_back(Error("Failed to parse field '" +
std::string(_current_name) +
"': " + std::move(res.error()->what())));
return;
}
extra_fields->emplace(std::string(_current_name), std::move(*res));
}
template <int... is>
static void assign_to_matching_field(const R& _r,
const std::string_view& _current_name,
const auto& _var, auto* _view,
auto* _errors,
std::integer_sequence<int, is...>) {
bool already_assigned = false;
(assign_if_field_matches<is>(_r, _current_name, _var, _view, _errors,
&already_assigned),
...);
if constexpr (ViewType::pos_extra_fields() != -1) {
constexpr int pos = ViewType::pos_extra_fields();
if (!already_assigned) {
assign_to_extra_fields<pos>(_r, _current_name, _var, _view, _errors);
}
}
}
template <class Target, class Source>
static void move_to(Target* _t, Source* _s) {
if constexpr (std::is_const_v<Target>) {
return move_to(const_cast<std::remove_const_t<Target>*>(_t), _s);
} else if constexpr (!rfl::internal::is_array_v<Source> &&
!std::is_array_v<Target>) {
*_t = Target(std::move(*_s));
} else if constexpr (rfl::internal::is_array_v<Source>) {
static_assert(std::is_array_v<Target>,
"Expected target to be a c-array.");
for (size_t i = 0; i < _s->arr_.size(); ++i) {
move_to(&((*_t)[i]), &(_s->arr_[i]));
}
} else {
for (size_t i = 0; i < _s->size(); ++i) {
move_to(&((*_t)[i]), &((*_s)[i]));
}
}
}
private:
/// The underlying reader.
const R* r_;
/// The underlying view.
ViewType* view_;
/// Collects any errors we may have come across.
std::vector<Error>* errors_;
};
} // namespace rfl::parsing
#endif
@@ -0,0 +1,111 @@
#ifndef RFL_PARSING_VIEWREADERWITHDEFAULTANDSTRIPPEDFIELDNAMES_HPP_
#define RFL_PARSING_VIEWREADERWITHDEFAULTANDSTRIPPEDFIELDNAMES_HPP_
#include <array>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
#include "../Result.hpp"
#include "../Tuple.hpp"
#include "../internal/is_array.hpp"
namespace rfl::parsing {
template <class R, class W, class ViewType, class ProcessorsType>
class ViewReaderWithDefaultAndStrippedFieldNames {
private:
using InputVarType = typename R::InputVarType;
static constexpr size_t size_ = ViewType::size();
public:
ViewReaderWithDefaultAndStrippedFieldNames(const R* _r, ViewType* _view,
std::vector<Error>* _errors)
: i_(0), r_(_r), view_(_view), errors_(_errors) {}
~ViewReaderWithDefaultAndStrippedFieldNames() = default;
/// Assigns the parsed version of _var to the field signified by i_, to be
/// used when the field names are stripped.
std::optional<Error> read(const InputVarType& _var) const {
if (i_ == size_) {
return Error("Expected a maximum of " + std::to_string(size_) +
" fields, but got at least one more.");
}
assign_to_field_i(*r_, _var, view_, errors_, i_,
std::make_integer_sequence<int, size_>());
++i_;
return std::nullopt;
}
private:
template <int i>
static void assign_if_field_is_field_i(const R& _r, const auto& _var,
auto* _view, auto* _errors, int _i) {
using FieldType = tuple_element_t<i, typename ViewType::Fields>;
using OriginalType = typename FieldType::Type;
using T =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
constexpr auto name = FieldType::name();
if (_i == i) {
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
if (!res) {
_errors->emplace_back(Error("Failed to parse field '" +
std::string(name) +
"': " + std::move(res.error()->what())));
return;
}
if constexpr (std::is_pointer_v<OriginalType>) {
move_to(rfl::get<i>(*_view), &(*res));
} else {
rfl::get<i>(*_view) = std::move(*res);
}
}
}
template <int... is>
static void assign_to_field_i(const R& _r, const auto& _var, auto* _view,
auto* _errors, int _i,
std::integer_sequence<int, is...>) {
(assign_if_field_is_field_i<is>(_r, _var, _view, _errors, _i), ...);
}
// TODO: Unnecessary code duplication.
template <class Target, class Source>
static void move_to(Target* _t, Source* _s) {
if constexpr (std::is_const_v<Target>) {
return move_to(const_cast<std::remove_const_t<Target>*>(_t), _s);
} else if constexpr (!rfl::internal::is_array_v<Source> &&
!std::is_array_v<Target>) {
*_t = Target(std::move(*_s));
} else if constexpr (rfl::internal::is_array_v<Source>) {
static_assert(std::is_array_v<Target>,
"Expected target to be a c-array.");
for (size_t i = 0; i < _s->arr_.size(); ++i) {
move_to(&((*_t)[i]), &(_s->arr_[i]));
}
} else {
for (size_t i = 0; i < _s->size(); ++i) {
move_to(&((*_t)[i]), &((*_s)[i]));
}
}
}
private:
/// Indicates the current field.
mutable int i_;
/// The underlying reader.
const R* r_;
/// The underlying view.
ViewType* view_;
/// Collects any errors we may have come across.
std::vector<Error>* errors_;
};
} // namespace rfl::parsing
#endif
+26
View File
@@ -0,0 +1,26 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_default_if_missing {
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town;
};
TEST(json, test_default_if_missing) {
auto homer = rfl::json::read<Person, rfl::DefaultIfMissing>(
R"({"first_name":"Homer"})")
.value();
EXPECT_EQ(homer.first_name, "Homer");
EXPECT_EQ(homer.last_name, "Simpson");
EXPECT_EQ(homer.town, "");
}
} // namespace test_default_if_missing
@@ -0,0 +1,27 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_default_if_missing_no_field_names {
struct Person {
std::string first_name;
std::string last_name = "Simpson";
std::string town;
};
TEST(json, test_default_if_missing_no_field_names) {
auto homer =
rfl::json::read<Person, rfl::DefaultIfMissing, rfl::NoFieldNames>(
R"(["Homer"])")
.value();
EXPECT_EQ(homer.first_name, "Homer");
EXPECT_EQ(homer.last_name, "Simpson");
EXPECT_EQ(homer.town, "");
}
} // namespace test_default_if_missing_no_field_names