From cef601baa7feef3c9c32e03cabf93e58af72c14c Mon Sep 17 00:00:00 2001 From: Lixin Wei Date: Sun, 22 Mar 2026 23:17:23 +0800 Subject: [PATCH] Fix capnproto add_value_to_map overwriting all entries at index 0 add_value_to_map constructed a fresh OutputArrayType each call without using _parent->ix_++, so ix_ always defaulted to 0 and every map entry overwrote slot 0 in the Cap'n Proto entries list. Only the last entry survived serialization; on read-back the remaining default entries (with empty-string keys) triggered stoull errors. Fix by using designated initializers with .ix_ = _parent->ix_++, matching all other add_*_to_map methods in Writer.cpp. Also wrap the key _name in std::string() so add_value_to_object deduces T as std::string rather than std::string_view, which has no handling branch. Add test_map_value_types to exercise maps with primitive value types (std::map) through add_value_to_map. Made-with: Cursor --- include/rfl/capnproto/Writer.hpp | 7 ++++--- tests/capnproto/test_map_value_types.cpp | 25 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 tests/capnproto/test_map_value_types.cpp diff --git a/include/rfl/capnproto/Writer.hpp b/include/rfl/capnproto/Writer.hpp index c93f9621b..6764dcd8e 100644 --- a/include/rfl/capnproto/Writer.hpp +++ b/include/rfl/capnproto/Writer.hpp @@ -186,10 +186,11 @@ class RFL_API Writer { template OutputVarType add_value_to_map(const std::string_view& _name, const T& _var, OutputMapType* _parent) const { - auto entries = - OutputArrayType{_parent->val_.get("entries").as()}; + auto entries = OutputArrayType{ + .val_ = _parent->val_.get("entries").as(), + .ix_ = _parent->ix_++}; auto new_entry = add_object_to_array(2, &entries); - add_value_to_object("key", _name, &new_entry); + add_value_to_object("key", std::string(_name), &new_entry); return add_value_to_object("value", _var, &new_entry); } diff --git a/tests/capnproto/test_map_value_types.cpp b/tests/capnproto/test_map_value_types.cpp new file mode 100644 index 000000000..f53c375ff --- /dev/null +++ b/tests/capnproto/test_map_value_types.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map_value_types { + +struct PersonWithStringMap { + rfl::Rename<"firstName", std::string> first_name; + std::map nicknames; +}; + +TEST(capnproto, test_map_with_string_values) { + auto nicknames = std::map(); + nicknames["Bart"] = "El Barto"; + nicknames["Lisa"] = "Lis"; + nicknames["Maggie"] = "Mags"; + + const auto homer = PersonWithStringMap{.first_name = "Homer", + .nicknames = std::move(nicknames)}; + + write_and_read(homer); +} +} // namespace test_map_value_types