Skip to content

Commit ee90b90

Browse files
Merge branch 'main' into f/hugo-docs
2 parents b9703d6 + f93ee97 commit ee90b90

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

‎include/rfl/parsing/FieldVariantReader.hpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,12 @@ class FieldVariantReader {
4343
*/
4444
void read(const std::string_view& _disc_value,
4545
const InputVarType& _var) const noexcept {
46+
if (*field_variant_) {
47+
*field_variant_ = error(
48+
"Could not parse rfl::Variant: Expected the object to have "
49+
"exactly one field, but found more than one.");
50+
return;
51+
}
4652
try_matching_fields(
4753
_disc_value, _var,
4854
std::make_integer_sequence<int, sizeof...(FieldTypes)>());
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <gtest/gtest.h>
2+
3+
#include <rfl.hpp>
4+
#include <rfl/json.hpp>
5+
#include <string>
6+
7+
namespace test_field_variant_multiple_fields {
8+
9+
struct Circle {
10+
double radius;
11+
};
12+
13+
struct Rectangle {
14+
double height;
15+
double width;
16+
};
17+
18+
using Shapes =
19+
rfl::Variant<rfl::Field<"circle", Circle>, rfl::Field<"rectangle", Rectangle>>;
20+
21+
TEST(json, test_field_variant_multiple_fields) {
22+
const std::string faulty_string =
23+
R"({"circle":{"radius":2.0},"rectangle":{"height":10.0,"width":5.0}})";
24+
25+
const auto result = rfl::json::read<Shapes>(faulty_string);
26+
27+
EXPECT_TRUE(!result.has_value() && true);
28+
EXPECT_EQ(result.error().what(),
29+
"Could not parse rfl::Variant: Expected the object to have "
30+
"exactly one field, but found more than one.");
31+
}
32+
33+
TEST(json, test_field_variant_unknown_then_known_field) {
34+
const std::string faulty_string =
35+
R"({"triangle":{"base":3.0},"circle":{"radius":2.0}})";
36+
37+
const auto result = rfl::json::read<Shapes>(faulty_string);
38+
39+
EXPECT_TRUE(!result.has_value() && true);
40+
}
41+
42+
} // namespace test_field_variant_multiple_fields

0 commit comments

Comments
 (0)