Bugfix: DefaultIfMissing and XML arrays; #367 (#371)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-03-02 01:25:33 +08:00
committed by GitHub
parent 37dbcef95a
commit 1da93be27f
2 changed files with 38 additions and 6 deletions
+14 -6
View File
@@ -23,14 +23,16 @@ class ViewReaderWithDefault {
public:
ViewReaderWithDefault(const R* _r, ViewType* _view,
std::vector<Error>* _errors)
: r_(_r), view_(_view), errors_(_errors) {}
: r_(_r), view_(_view), errors_(_errors) {
found_->fill(false);
}
~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_,
assign_to_matching_field(*r_, _name, _var, view_, errors_, found_.get(),
std::make_integer_sequence<int, size_>());
}
@@ -39,13 +41,16 @@ class ViewReaderWithDefault {
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) {
auto* _errors, auto* _found,
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) {
if (!(*_already_assigned) && !std::get<i>(*_found) &&
_current_name == name) {
std::get<i>(*_found) = true;
*_already_assigned = true;
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
if (!res) {
@@ -88,12 +93,12 @@ class ViewReaderWithDefault {
static void assign_to_matching_field(const R& _r,
const std::string_view& _current_name,
const auto& _var, auto* _view,
auto* _errors,
auto* _errors, auto* _found,
std::integer_sequence<int, is...>) {
bool already_assigned = false;
(assign_if_field_matches<is>(_r, _current_name, _var, _view, _errors,
&already_assigned),
_found, &already_assigned),
...);
if constexpr (ViewType::pos_extra_fields() != -1) {
@@ -139,6 +144,9 @@ class ViewReaderWithDefault {
/// The underlying view.
ViewType* view_;
/// Indicates that a certain field has been found.
rfl::Ref<std::array<bool, size_>> found_;
/// Collects any errors we may have come across.
std::vector<Error>* errors_;
};
+24
View File
@@ -0,0 +1,24 @@
#include <cassert>
#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 name;
std::vector<std::string> children;
};
TEST(xml, test_default_if_missing) {
const auto homer =
Person{.name = "Homer",
.children = std::vector<std::string>({"Bart", "Lisa", "Maggie"})};
write_and_read<"Person", rfl::DefaultIfMissing>(homer);
}
} // namespace test_default_if_missing