Skip to content

Commit

Permalink
[yaml] Fix round-trip bugs with variant<string,...> (#19954)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwnimmer-tri authored Aug 7, 2023
1 parent fe4ed1b commit d717790
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 1 deletion.
3 changes: 3 additions & 0 deletions common/yaml/test/yaml_read_archive_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,9 @@ TEST_P(YamlReadArchiveTest, Variant) {
EXPECT_EQ(x.value, expected) << doc;
};

test("doc:\n value: \"\"", "");
test("doc:\n value: foo", "foo");
test("doc:\n value: \"foo\"", "foo");
test("doc:\n value: !!str foo", "foo");
test("doc:\n value: !!float 1.0", 1.0);
test("doc:\n value: !DoubleStruct { value: 1.0 }", DoubleStruct{1.0});
Expand Down
1 change: 1 addition & 0 deletions common/yaml/test/yaml_write_archive_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ TEST_F(YamlWriteArchiveTest, Variant) {
EXPECT_EQ(Save(x), WrapDoc(expected));
};

test(Variant4(std::string()), "\"\"");
test(Variant4(std::string("foo")), "foo");
test(Variant4(DoubleStruct{1.0}), "!DoubleStruct\n value: 1.0");
test(Variant4(EigenVecStruct{Eigen::Vector2d(1.0, 2.0)}),
Expand Down
2 changes: 1 addition & 1 deletion common/yaml/yaml_read_archive.h
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ class YamlReadArchive final {
Variant* storage) {
// For the first type declared in the variant<> (I == 0), the tag can be
// absent; otherwise, the tag must match one of the variant's types.
if (((I == 0) && (tag.empty() || (tag == "?"))) ||
if (((I == 0) && (tag.empty() || (tag == "?") || (tag == "!"))) ||
IsTagMatch(drake::NiceTypeName::GetFromStorage<T>(), tag)) {
T& typed_storage = storage->template emplace<I>();
this->Visit(drake::MakeNameValue(name, &typed_storage));
Expand Down
6 changes: 6 additions & 0 deletions systems/sensors/test/camera_config_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ GTEST_TEST(CameraConfigTest, SerializeBackgroundRgba) {
EXPECT_EQ(yaml, "background:\n rgba: [0.1, 0.2, 0.3, 0.4]\n");
}

GTEST_TEST(CameraConfigTest, SerializationDefaultRoundTrip) {
const CameraConfig original;
const std::string yaml = SaveYamlString<CameraConfig>(original);
EXPECT_NO_THROW(LoadYamlString<CameraConfig>(yaml)) << "with yaml:\n" << yaml;
}

// Various tests to support the documented examples in the documentation. The
// number of each parsed config should correspond to the number in the docs for
// the renderer_class field.
Expand Down

0 comments on commit d717790

Please sign in to comment.