From 70ac675d1c01dbf1cef6a6549962ce82daf62f23 Mon Sep 17 00:00:00 2001 From: HolyK <45712321+hazby2002@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:02:23 +0800 Subject: [PATCH 1/2] Add opt-in string map keys for enums and custom reflectors --- docs/content/processors.md | 41 ++++++ include/rfl.hpp | 1 + include/rfl/StringifyMapKeys.hpp | 17 +++ include/rfl/internal/stringify_map_keys_v.hpp | 32 +++++ include/rfl/parsing/MapParser.hpp | 20 ++- include/rfl/parsing/MapReader.hpp | 8 +- include/rfl/parsing/StringMapKey.hpp | 67 ++++++++++ include/rfl/parsing/TypedMapReader.hpp | 10 +- include/rfl/parsing/VectorParser.hpp | 7 +- .../test_stringify_map_keys.cpp | 15 +++ tests/cbor/test_stringify_map_keys.cpp | 15 +++ tests/generic/test_stringify_map_keys.cpp | 16 +++ tests/json/test_stringify_map_keys.cpp | 90 +++++++++++++ tests/test_stringify_map_keys.hpp | 125 ++++++++++++++++++ tests/yaml/test_stringify_map_keys.cpp | 26 ++++ 15 files changed, 483 insertions(+), 7 deletions(-) create mode 100644 include/rfl/StringifyMapKeys.hpp create mode 100644 include/rfl/internal/stringify_map_keys_v.hpp create mode 100644 include/rfl/parsing/StringMapKey.hpp create mode 100644 tests/boost_serialization/test_stringify_map_keys.cpp create mode 100644 tests/cbor/test_stringify_map_keys.cpp create mode 100644 tests/generic/test_stringify_map_keys.cpp create mode 100644 tests/json/test_stringify_map_keys.cpp create mode 100644 tests/test_stringify_map_keys.hpp create mode 100644 tests/yaml/test_stringify_map_keys.cpp diff --git a/docs/content/processors.md b/docs/content/processors.md index 64c75dd52..9a1096d1e 100644 --- a/docs/content/processors.md +++ b/docs/content/processors.md @@ -44,6 +44,7 @@ reflect-cpp currently supports the following processors: - `rfl::NoExtraFields` - `rfl::NoFieldNames` - `rfl::NoOptionals` +- `rfl::StringifyMapKeys` - `rfl::UnderlyingEnums` - `rfl::SnakeCaseToCamelCase` - `rfl::SnakeCaseToPascalCase` @@ -555,3 +556,43 @@ struct MyOwnProcessor { static auto process(auto&& _named_tuple) {...} }; ``` + +### `rfl::StringifyMapKeys` + +Use `rfl::StringifyMapKeys` to represent `std::map` and `std::unordered_map` +with enum keys or string-reflected keys as maps (JSON objects, YAML mappings), +instead of arrays of key/value pairs. This is opt-in and applies to nested maps +as well. Pass the processor to both `read` and `write`. + +```cpp +enum class Colour { Red, Green, Blue }; +using Dictionary = std::map; + +const Dictionary dictionary{{Colour::Red, "Rojo"}, {Colour::Blue, "Azul"}}; +const auto json = rfl::json::write(dictionary); +// {"Red":"Rojo","Blue":"Azul"} +const auto decoded = + rfl::json::read(json); +``` + +For any key type `T` with a custom `rfl::Reflector` whose `ReflType` is +`std::string`, writing uses `Reflector::from` and reading uses +`Reflector::to`. This includes both enums and user-defined classes. A +reflector takes precedence over the built-in enum name conversion. +`Reflector::to` may return `rfl::Result` or throw a `std::exception` to report +an invalid key. Writing requires `from`; reading requires `to` for non-enum +string-reflected keys. As with other string-keyed maps, distinct keys should +have distinct string representations to preserve round trips. + +Without a custom reflector, enum keys use the ordinary enum name conversion. +`rfl::EnumNamesOnly` also applies to keys: it rejects numeric strings as enum +names. `rfl::UnderlyingEnums` retains the array representation for enums without +a reflector, since those keys serialize as integers. String reflectors still +take precedence when both processors are present. Reflectors with a non-string +`ReflType` retain their existing representation. + +Existing string, numeric and `ReflectionType`-based map keys keep their behavior. +Multimaps remain arrays of pairs, preserving duplicate keys. JSON Schema generated +with the processor describes these additional maps as objects, just like +`std::map`. The processor changes map keys only; enum values +elsewhere keep their ordinary representation. diff --git a/include/rfl.hpp b/include/rfl.hpp index 2663929a3..6bb2d446f 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -50,6 +50,7 @@ #include "rfl/SnakeCaseToCamelCase.hpp" #include "rfl/SnakeCaseToKebabCase.hpp" #include "rfl/SnakeCaseToPascalCase.hpp" +#include "rfl/StringifyMapKeys.hpp" #include "rfl/TaggedUnion.hpp" #include "rfl/Timestamp.hpp" #include "rfl/ToAllCaps.hpp" diff --git a/include/rfl/StringifyMapKeys.hpp b/include/rfl/StringifyMapKeys.hpp new file mode 100644 index 000000000..0986e93cf --- /dev/null +++ b/include/rfl/StringifyMapKeys.hpp @@ -0,0 +1,17 @@ +#ifndef RFL_STRINGIFYMAPKEYS_HPP_ +#define RFL_STRINGIFYMAPKEYS_HPP_ + +namespace rfl { + +/// Represents maps with string-reflected keys or enum names as string-keyed +/// maps. Without this processor these additional key types use arrays of pairs. +struct StringifyMapKeys { + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/internal/stringify_map_keys_v.hpp b/include/rfl/internal/stringify_map_keys_v.hpp new file mode 100644 index 000000000..9b9b0ed05 --- /dev/null +++ b/include/rfl/internal/stringify_map_keys_v.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_INTERNAL_STRINGIFYMAPKEYS_HPP_ +#define RFL_INTERNAL_STRINGIFYMAPKEYS_HPP_ + +#include + +#include "../Processors.hpp" +#include "../StringifyMapKeys.hpp" + +namespace rfl::internal { + +template +class stringify_map_keys; + +template +class stringify_map_keys : public std::false_type {}; + +template <> +class stringify_map_keys : public std::true_type {}; + +template +struct stringify_map_keys> { + static constexpr bool value = (stringify_map_keys::value || ... || + stringify_map_keys::value); +}; + +template +constexpr bool stringify_map_keys_v = + stringify_map_keys>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index ed4cb7454..b97ade70d 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -11,6 +11,7 @@ #include "MapReader.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "StringMapKey.hpp" #include "SupportsTypedMapReader.hpp" #include "SupportsTypedMapWriter.hpp" #include "TypedMapReader.hpp" @@ -125,7 +126,12 @@ struct MapParser { auto entry = _w.map_entry(map); const auto parent = typename ParentType::template MapEntry< typename W::OutputMapEntryType>{&entry}; - Parser::write(_w, key, parent); + if constexpr (StringMapKey::enabled) { + const auto name = StringMapKey::write(key); + Parser::write(_w, name, parent); + } else { + Parser::write(_w, key, parent); + } Parser::write(_w, value, parent); } }; @@ -148,7 +154,11 @@ struct MapParser { typename ParentType::template Map; for (const auto& [k, v] : _m) { - if constexpr (internal::has_reflection_type_v) { + if constexpr (StringMapKey::enabled) { + const auto name = StringMapKey::write(k); + const auto new_parent = ParentMapType{name, &m}; + Parser::write(_w, v, new_parent); + } else if constexpr (internal::has_reflection_type_v) { using ReflT = typename KeyType::ReflectionType; if constexpr (std::is_integral_v || @@ -183,7 +193,11 @@ struct MapParser { static void write_object(const W& _w, const MapType& _m, const P& _parent) { auto obj = ParentType::add_object(_w, _m.size(), _parent); for (const auto& [k, v] : _m) { - if constexpr (internal::has_reflection_type_v) { + if constexpr (StringMapKey::enabled) { + const auto name = StringMapKey::write(k); + const auto new_parent = typename ParentType::Object{name, &obj}; + Parser::write(_w, v, new_parent); + } else if constexpr (internal::has_reflection_type_v) { using ReflT = typename KeyType::ReflectionType; if constexpr (std::is_integral_v || diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index fe1e8ffdc..a98328ec2 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -11,6 +11,7 @@ #include "../always_false.hpp" #include "../internal/has_reflection_type_v.hpp" #include "Parser_base.hpp" +#include "StringMapKey.hpp" #include "wrap_error.hpp" namespace rfl::parsing { @@ -84,8 +85,11 @@ class MapReader { } }; - if constexpr (std::is_integral_v || - std::is_floating_point_v) { + if constexpr (StringMapKey::enabled) { + return StringMapKey::read(_pair.first) + .and_then(to_pair); + } else if constexpr (std::is_integral_v || + std::is_floating_point_v) { return key_to_numeric(_pair).and_then(to_pair); } else if constexpr (internal::has_reflection_type_v) { diff --git a/include/rfl/parsing/StringMapKey.hpp b/include/rfl/parsing/StringMapKey.hpp new file mode 100644 index 000000000..70421cccc --- /dev/null +++ b/include/rfl/parsing/StringMapKey.hpp @@ -0,0 +1,67 @@ +#ifndef RFL_PARSING_STRINGMAPKEY_HPP_ +#define RFL_PARSING_STRINGMAPKEY_HPP_ + +#include +#include +#include + +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../enums.hpp" +#include "../internal/enum_names_only_v.hpp" +#include "../internal/has_reflector.hpp" +#include "../internal/stringify_map_keys_v.hpp" +#include "../internal/underlying_enums_v.hpp" + +namespace rfl::parsing { + +/// Converts the additional key types enabled by StringifyMapKeys. Keep the +/// reflector ahead of enum conversion, just as the ordinary value parser does. +template +struct StringMapKey { + static constexpr bool enabled = [] { + if constexpr (!internal::stringify_map_keys_v) { + return false; + } else if constexpr (internal::has_read_reflector || + internal::has_write_reflector) { + return std::is_same_v::ReflType, std::string>; + } else { + return std::is_enum_v && + !internal::underlying_enums_v; + } + }(); + + static Result read(const std::string& _name) noexcept { + if constexpr (internal::has_read_reflector) { + try { + return Reflector::to(_name); + } catch (const std::exception& e) { + return error(e.what()); + } + } else if constexpr (std::is_enum_v) { + return rfl::string_to_enum>( + _name); + } else { + static_assert( + always_false_v, + "Reading string-reflected map keys requires Reflector::to."); + } + } + + static std::string write(const Key& _key) { + if constexpr (internal::has_write_reflector) { + return Reflector::from(_key); + } else if constexpr (std::is_enum_v) { + return rfl::enum_to_string(_key); + } else { + static_assert( + always_false_v, + "Writing string-reflected map keys requires Reflector::from."); + } + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/TypedMapReader.hpp b/include/rfl/parsing/TypedMapReader.hpp index 869c57d2a..01c43b45d 100644 --- a/include/rfl/parsing/TypedMapReader.hpp +++ b/include/rfl/parsing/TypedMapReader.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "Parser_base.hpp" +#include "StringMapKey.hpp" namespace rfl::parsing { @@ -26,7 +27,14 @@ struct TypedMapReader { const InputVarType& _value) const noexcept { // Archive readers can pass the same stream for both arguments. Always // finish reading the key before starting the value, and stop on failure. - auto key = Parser::read(*reader, _key); + auto key = [&]() -> Result { + if constexpr (StringMapKey::enabled) { + return Parser::read(*reader, _key) + .and_then(StringMapKey::read); + } else { + return Parser::read(*reader, _key); + } + }(); if (!key) { return Error("Failed to parse map key: " + key.error().what()); } diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index 2be9ee2e7..9dc1f493b 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -13,6 +13,7 @@ #include "MapParser.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "StringMapKey.hpp" #include "VectorReader.hpp" #include "is_forward_list.hpp" #include "is_map_like.hpp" @@ -128,7 +129,11 @@ struct VectorParser { */ static constexpr bool treat_as_map() { if constexpr (is_map_like_not_multimap()) { - if constexpr (internal::has_reflection_type_v) { + using Key = std::remove_cvref_t; + if constexpr (StringMapKey::enabled) { + return true; + } else if constexpr (internal::has_reflection_type_v< + typename T::first_type>) { using U = std::remove_cvref_t; return std::is_same() || std::is_integral_v || std::is_floating_point_v; diff --git a/tests/boost_serialization/test_stringify_map_keys.cpp b/tests/boost_serialization/test_stringify_map_keys.cpp new file mode 100644 index 000000000..8b997ba2e --- /dev/null +++ b/tests/boost_serialization/test_stringify_map_keys.cpp @@ -0,0 +1,15 @@ +#include "../test_stringify_map_keys.hpp" + +#include + +namespace test_stringify_map_keys { +TEST(boost_serialization, stringify_map_keys_roundtrip) { + check( + [](const auto& value) { + return rfl::boost_serialization::write(value); + }, + [](const auto& value) { + return rfl::boost_serialization::read(value); + }); +} +} // namespace test_stringify_map_keys diff --git a/tests/cbor/test_stringify_map_keys.cpp b/tests/cbor/test_stringify_map_keys.cpp new file mode 100644 index 000000000..5ae7a2fb2 --- /dev/null +++ b/tests/cbor/test_stringify_map_keys.cpp @@ -0,0 +1,15 @@ +#include "../test_stringify_map_keys.hpp" + +#include + +namespace test_stringify_map_keys { +TEST(cbor, stringify_map_keys_roundtrip) { + check( + [](const auto& value) { + return rfl::cbor::write(value); + }, + [](const auto& value) { + return rfl::cbor::read(value); + }); +} +} // namespace test_stringify_map_keys diff --git a/tests/generic/test_stringify_map_keys.cpp b/tests/generic/test_stringify_map_keys.cpp new file mode 100644 index 000000000..98e2f6d8b --- /dev/null +++ b/tests/generic/test_stringify_map_keys.cpp @@ -0,0 +1,16 @@ +#include "../test_stringify_map_keys.hpp" + +#include +#include + +namespace test_stringify_map_keys { +TEST(generic, stringify_map_keys_roundtrip) { + check( + [](const auto& value) { + return rfl::generic::write(value); + }, + [](const auto& value) { + return rfl::generic::read(value); + }); +} +} // namespace test_stringify_map_keys diff --git a/tests/json/test_stringify_map_keys.cpp b/tests/json/test_stringify_map_keys.cpp new file mode 100644 index 000000000..d051d6580 --- /dev/null +++ b/tests/json/test_stringify_map_keys.cpp @@ -0,0 +1,90 @@ +#include "../test_stringify_map_keys.hpp" + +#include + +namespace test_stringify_map_keys { +using P = rfl::StringifyMapKeys; + +TEST(json, stringify_map_keys_roundtrip) { + check([](const auto& value) { return rfl::json::write

(value); }, + [](const auto& json) { return rfl::json::read(json); }); +} + +TEST(json, stringify_map_keys_representation) { + const std::map map{{Colour::Red, 1}, {Colour::Blue, 2}}; + EXPECT_EQ(rfl::json::write

(map), R"({"Red":1,"Blue":2})"); + EXPECT_EQ(rfl::json::write(map), R"([["Red",1],["Blue",2]])"); + EXPECT_EQ(rfl::json::write

(std::map{}), "{}"); + const auto legacy = rfl::json::read>( + rfl::json::write(map)); + ASSERT_TRUE(legacy); + EXPECT_EQ(*legacy, map); + EXPECT_FALSE( + (rfl::json::read>(R"({"Red":1})"))); + EXPECT_FALSE((rfl::json::read, P>( + R"([["Red",1]])"))); +} + +TEST(json, stringify_map_keys_reflector_precedence) { + const std::map map{{CustomColour::Red, 3}}; + EXPECT_EQ(rfl::json::write

(map), R"({"rouge":3})"); + EXPECT_EQ((rfl::json::write(map)), R"({"rouge":3})"); + EXPECT_EQ(rfl::json::write(map), R"([["rouge",3]])"); + const auto result = rfl::json::read, P, + rfl::UnderlyingEnums>(R"({"rouge":3})"); + ASSERT_TRUE(result); + EXPECT_EQ(*result, map); + EXPECT_EQ(rfl::json::write

(std::map{{Key{1}, 9}}), + R"({"key-1":9})"); +} + +TEST(json, stringify_map_keys_errors) { + const auto unknown = + rfl::json::read, P>(R"({"Purple":1})"); + ASSERT_FALSE(unknown); + EXPECT_NE(unknown.error().what().find("Purple"), std::string::npos); + const auto thrown = + rfl::json::read, P>(R"({"Red":1})"); + ASSERT_FALSE(thrown); + EXPECT_NE(thrown.error().what().find("Unknown colour: Red"), + std::string::npos); + const auto error = rfl::json::read, P>(R"({"bad":1})"); + ASSERT_FALSE(error); + EXPECT_NE(error.error().what().find("Invalid custom key: bad"), + std::string::npos); + EXPECT_FALSE((rfl::json::read, P>(R"({"Red":"bad"})"))); +} + +TEST(json, stringify_map_keys_enum_processors) { + using Map = std::map; + const auto permissive = rfl::json::read(R"({"1":7})"); + ASSERT_TRUE(permissive); + EXPECT_EQ(permissive->at(Colour::Green), 7); + EXPECT_FALSE((rfl::json::read(R"({"1":7})"))); + EXPECT_TRUE((rfl::json::read(R"({"Green":7})"))); + const Map value{{Colour::Red, 1}}; + EXPECT_EQ((rfl::json::write(value)), "[[0,1]]"); + const auto numeric = rfl::json::read("[[0,1]]"); + ASSERT_TRUE(numeric); + EXPECT_EQ(*numeric, value); +} + +TEST(json, stringify_map_keys_preserves_other_maps) { + EXPECT_EQ(rfl::json::write

(std::map{{Numeric::One, 2}}), + "[[1,2]]"); + EXPECT_EQ(rfl::json::write

( + std::multimap{{Colour::Red, 1}, {Colour::Red, 2}}), + R"([["Red",1],["Red",2]])"); + EXPECT_EQ(rfl::json::write

(std::map{{1, 2}}), R"({"1":2})"); + EXPECT_EQ(rfl::json::write

(std::map{{"x", 2}}), + R"({"x":2})"); +} + +TEST(json, stringify_map_keys_schema) { + const auto expected = rfl::json::to_schema>(); + EXPECT_EQ((rfl::json::to_schema, P>()), expected); + EXPECT_EQ((rfl::json::to_schema, P>()), expected); + EXPECT_EQ((rfl::json::to_schema, P>()), expected); + EXPECT_NE((rfl::json::to_schema>()), expected); +} +} // namespace test_stringify_map_keys diff --git a/tests/test_stringify_map_keys.hpp b/tests/test_stringify_map_keys.hpp new file mode 100644 index 000000000..82740fb19 --- /dev/null +++ b/tests/test_stringify_map_keys.hpp @@ -0,0 +1,125 @@ +#ifndef RFL_TEST_STRINGIFY_MAP_KEYS_HPP_ +#define RFL_TEST_STRINGIFY_MAP_KEYS_HPP_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_stringify_map_keys { +enum class Colour { Red, Green, Blue }; +enum class CustomColour { Red, Blue }; +enum class Numeric { One = 1 }; + +struct Key { + int id; + auto operator<=>(const Key&) const = default; +}; +struct Hash { + std::size_t operator()(const Key& key) const { + return std::hash{}(key.id); + } +}; +} // namespace test_stringify_map_keys + +namespace rfl { +template <> +struct Reflector { + using ReflType = std::string; + static auto to(const std::string& name) { + using E = test_stringify_map_keys::CustomColour; + if (name == "rouge") return E::Red; + if (name == "bleu") return E::Blue; + throw std::runtime_error("Unknown colour: " + name); + } + static std::string from(test_stringify_map_keys::CustomColour value) { + return value == test_stringify_map_keys::CustomColour::Red ? "rouge" + : "bleu"; + } +}; + +template <> +struct Reflector { + using ReflType = std::string; + static Result to(const std::string& name) { + if (name == "key-1") return test_stringify_map_keys::Key{1}; + if (name == "key-2") return test_stringify_map_keys::Key{2}; + return error("Invalid custom key: " + name); + } + static std::string from(const test_stringify_map_keys::Key& key) { + return "key-" + std::to_string(key.id); + } +}; + +template <> +struct Reflector { + using ReflType = int; + static auto to(int value) { + return static_cast(value); + } + static int from(test_stringify_map_keys::Numeric value) { + return static_cast(value); + } +}; +} // namespace rfl + +namespace test_stringify_map_keys { +template +void roundtrip(const auto& write, const auto& read, const T& value) { + const auto result = read.template operator()(write(value)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(*result, value); +} + +inline void check(const auto& write, const auto& read) { + const auto names = read.template operator()>( + write(std::map{{Colour::Red, 1}})); + ASSERT_TRUE(names) << names.error().what(); + EXPECT_EQ(names->at("Red"), 1); + const auto custom_names = + read.template operator()>( + write(std::map{{Key{1}, 9}})); + ASSERT_TRUE(custom_names) << custom_names.error().what(); + EXPECT_EQ(custom_names->at("key-1"), 9); + EXPECT_FALSE((read.template operator()>( + write(std::map{{"unknown", 1}})))); + EXPECT_FALSE((read.template operator()>( + write(std::map{{"invalid", 1}})))); + EXPECT_FALSE((read.template operator()>( + write(std::map{{"invalid", 1}})))); + roundtrip(write, read, + std::map{{Colour::Red, 1}, {Colour::Blue, 2}}); + roundtrip(write, read, std::map{}); + roundtrip( + write, read, + std::unordered_map{{Colour::Red, 1}, {Colour::Blue, 2}}); + roundtrip(write, read, std::map{{CustomColour::Red, 3}}); + roundtrip(write, read, std::map{{Key{1}, 3}, {Key{2}, 4}}); + roundtrip(write, read, + std::unordered_map{{Key{1}, 3}, {Key{2}, 4}}); + roundtrip( + write, read, + std::map>{{Colour::Green, {{Key{2}, 7}}}}); + // Numeric reflectors and multimaps retain the existing array representation. + roundtrip(write, read, std::map{{Numeric::One, 1}}); + roundtrip(write, read, + std::multimap{{Colour::Red, 1}, {Colour::Red, 2}}); + const std::map> move_only = [] { + std::map> map; + map.emplace(Key{1}, std::make_unique(42)); + return map; + }(); + const auto result = + read.template operator()>( + write(move_only)); + ASSERT_TRUE(result) << result.error().what(); + ASSERT_TRUE(result->at(Key{1})); + EXPECT_EQ(*result->at(Key{1}), 42); +} +} // namespace test_stringify_map_keys +#endif diff --git a/tests/yaml/test_stringify_map_keys.cpp b/tests/yaml/test_stringify_map_keys.cpp new file mode 100644 index 000000000..e2cfffa74 --- /dev/null +++ b/tests/yaml/test_stringify_map_keys.cpp @@ -0,0 +1,26 @@ +#include "../test_stringify_map_keys.hpp" + +#include + +namespace test_stringify_map_keys { +TEST(yaml, stringify_map_keys_roundtrip) { + check( + [](const auto& value) { + return rfl::yaml::write(value); + }, + [](const auto& value) { + return rfl::yaml::read(value); + }); +} +TEST(yaml, stringify_map_keys_issue_661) { + struct Test { + std::map dictionary; + }; + const auto result = rfl::yaml::read( + std::string("dictionary:\n Red: Rojo\n Green: Verde\n Blue: Azul\n")); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result->dictionary.at(Colour::Red), "Rojo"); + EXPECT_EQ(result->dictionary.at(Colour::Green), "Verde"); + EXPECT_EQ(result->dictionary.at(Colour::Blue), "Azul"); +} +} // namespace test_stringify_map_keys From d6b98d79143af5a8af215246bb9a0c0db9a59553 Mon Sep 17 00:00:00 2001 From: HolyK <45712321+hazby2002@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:32:45 +0800 Subject: [PATCH 2/2] Guard map key detection for reflectors without ReflType --- include/rfl/parsing/MapReader.hpp | 2 +- include/rfl/parsing/StringMapKey.hpp | 13 ++++-- tests/json/test_stringify_map_keys.cpp | 57 ++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index a98328ec2..78f753d3b 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -86,7 +86,7 @@ class MapReader { }; if constexpr (StringMapKey::enabled) { - return StringMapKey::read(_pair.first) + return StringMapKey::read(std::move(_pair.first)) .and_then(to_pair); } else if constexpr (std::is_integral_v || std::is_floating_point_v) { diff --git a/include/rfl/parsing/StringMapKey.hpp b/include/rfl/parsing/StringMapKey.hpp index 70421cccc..b2721a625 100644 --- a/include/rfl/parsing/StringMapKey.hpp +++ b/include/rfl/parsing/StringMapKey.hpp @@ -24,17 +24,24 @@ struct StringMapKey { return false; } else if constexpr (internal::has_read_reflector || internal::has_write_reflector) { - return std::is_same_v::ReflType, std::string>; + // A write reflector can define from() without declaring ReflType. + if constexpr (requires { typename Reflector::ReflType; }) { + using ReflType = std::remove_cvref_t::ReflType>; + return std::is_same_v; + } else { + return false; + } } else { return std::is_enum_v && !internal::underlying_enums_v; } }(); - static Result read(const std::string& _name) noexcept { + static Result read(std::string _name) noexcept { if constexpr (internal::has_read_reflector) { try { - return Reflector::to(_name); + using ReflType = typename Reflector::ReflType; + return Reflector::to(static_cast(_name)); } catch (const std::exception& e) { return error(e.what()); } diff --git a/tests/json/test_stringify_map_keys.cpp b/tests/json/test_stringify_map_keys.cpp index d051d6580..38ce9ea9d 100644 --- a/tests/json/test_stringify_map_keys.cpp +++ b/tests/json/test_stringify_map_keys.cpp @@ -2,6 +2,40 @@ #include +namespace test_stringify_map_keys { +struct Tag { + int id; + auto operator<=>(const Tag&) const = default; +}; + +struct StringRefKey { + std::string value; + auto operator<=>(const StringRefKey&) const = default; +}; +} // namespace test_stringify_map_keys + +namespace rfl { +template <> +struct Reflector { + static std::string from(const test_stringify_map_keys::Tag& tag) { + return std::to_string(tag.id); + } +}; + +template <> +struct Reflector { + using ReflType = std::string&; + + static auto to(ReflType value) { + return test_stringify_map_keys::StringRefKey{std::move(value)}; + } + static const std::string& from( + const test_stringify_map_keys::StringRefKey& key) { + return key.value; + } +}; +} // namespace rfl + namespace test_stringify_map_keys { using P = rfl::StringifyMapKeys; @@ -38,6 +72,29 @@ TEST(json, stringify_map_keys_reflector_precedence) { R"({"key-1":9})"); } +TEST(json, stringify_map_keys_reflector_without_refl_type) { + struct Document { + std::map colours; + std::map tags; + }; + + const auto result = rfl::json::read( + R"({"colours":{"Red":1},"tags":[[{"id":7},2]]})"); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result->colours.at(Colour::Red), 1); + EXPECT_EQ(result->tags.at(Tag{7}), 2); +} + +TEST(json, stringify_map_keys_string_reference_reflector) { + using Map = std::map; + const Map map{{StringRefKey{"key"}, 3}}; + const auto json = rfl::json::write

(map); + EXPECT_EQ(json, R"({"key":3})"); + const auto result = rfl::json::read(json); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(*result, map); +} + TEST(json, stringify_map_keys_errors) { const auto unknown = rfl::json::read, P>(R"({"Purple":1})");