Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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<Colour, std::string>;

const Dictionary dictionary{{Colour::Red, "Rojo"}, {Colour::Blue, "Azul"}};
const auto json = rfl::json::write<rfl::StringifyMapKeys>(dictionary);
// {"Red":"Rojo","Blue":"Azul"}
const auto decoded =
rfl::json::read<Dictionary, rfl::StringifyMapKeys>(json);
```

For any key type `T` with a custom `rfl::Reflector<T>` whose `ReflType` is
`std::string`, writing uses `Reflector<T>::from` and reading uses
`Reflector<T>::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<T>` 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<std::string, T>`. The processor changes map keys only; enum values
elsewhere keep their ordinary representation.
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
17 changes: 17 additions & 0 deletions include/rfl/StringifyMapKeys.hpp
Original file line number Diff line number Diff line change
@@ -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 <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

} // namespace rfl

#endif
32 changes: 32 additions & 0 deletions include/rfl/internal/stringify_map_keys_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#ifndef RFL_INTERNAL_STRINGIFYMAPKEYS_HPP_
#define RFL_INTERNAL_STRINGIFYMAPKEYS_HPP_

#include <type_traits>

#include "../Processors.hpp"
#include "../StringifyMapKeys.hpp"

namespace rfl::internal {

template <class T>
class stringify_map_keys;

template <class T>
class stringify_map_keys : public std::false_type {};

template <>
class stringify_map_keys<StringifyMapKeys> : public std::true_type {};

template <class Head, class... Tail>
struct stringify_map_keys<Processors<Head, Tail...>> {
static constexpr bool value = (stringify_map_keys<Head>::value || ... ||
stringify_map_keys<Tail>::value);
};

template <class T>
constexpr bool stringify_map_keys_v =
stringify_map_keys<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace rfl::internal

#endif
20 changes: 17 additions & 3 deletions include/rfl/parsing/MapParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -125,7 +126,12 @@ struct MapParser {
auto entry = _w.map_entry(map);
const auto parent = typename ParentType::template MapEntry<
typename W::OutputMapEntryType>{&entry};
Parser<R, W, KeyType, ProcessorsType>::write(_w, key, parent);
if constexpr (StringMapKey<KeyType, ProcessorsType>::enabled) {
const auto name = StringMapKey<KeyType, ProcessorsType>::write(key);
Parser<R, W, std::string, ProcessorsType>::write(_w, name, parent);
} else {
Parser<R, W, KeyType, ProcessorsType>::write(_w, key, parent);
}
Parser<R, W, ValueType, ProcessorsType>::write(_w, value, parent);
}
};
Expand All @@ -148,7 +154,11 @@ struct MapParser {
typename ParentType::template Map<typename W::OutputMapType>;

for (const auto& [k, v] : _m) {
if constexpr (internal::has_reflection_type_v<KeyType>) {
if constexpr (StringMapKey<KeyType, ProcessorsType>::enabled) {
const auto name = StringMapKey<KeyType, ProcessorsType>::write(k);
const auto new_parent = ParentMapType{name, &m};
Parser<R, W, ValueType, ProcessorsType>::write(_w, v, new_parent);
} else if constexpr (internal::has_reflection_type_v<KeyType>) {
using ReflT = typename KeyType::ReflectionType;

if constexpr (std::is_integral_v<ReflT> ||
Expand Down Expand Up @@ -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<KeyType>) {
if constexpr (StringMapKey<KeyType, ProcessorsType>::enabled) {
const auto name = StringMapKey<KeyType, ProcessorsType>::write(k);
const auto new_parent = typename ParentType::Object{name, &obj};
Parser<R, W, ValueType, ProcessorsType>::write(_w, v, new_parent);
} else if constexpr (internal::has_reflection_type_v<KeyType>) {
using ReflT = typename KeyType::ReflectionType;

if constexpr (std::is_integral_v<ReflT> ||
Expand Down
8 changes: 6 additions & 2 deletions include/rfl/parsing/MapReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -84,8 +85,11 @@ class MapReader {
}
};

if constexpr (std::is_integral_v<KeyType> ||
std::is_floating_point_v<KeyType>) {
if constexpr (StringMapKey<KeyType, ProcessorsType>::enabled) {
return StringMapKey<KeyType, ProcessorsType>::read(std::move(_pair.first))
.and_then(to_pair);
} else if constexpr (std::is_integral_v<KeyType> ||
std::is_floating_point_v<KeyType>) {
return key_to_numeric<KeyType>(_pair).and_then(to_pair);

} else if constexpr (internal::has_reflection_type_v<KeyType>) {
Expand Down
74 changes: 74 additions & 0 deletions include/rfl/parsing/StringMapKey.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#ifndef RFL_PARSING_STRINGMAPKEY_HPP_
#define RFL_PARSING_STRINGMAPKEY_HPP_

#include <exception>
#include <string>
#include <type_traits>

#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 <class Key, class ProcessorsType>
struct StringMapKey {
static constexpr bool enabled = [] {
if constexpr (!internal::stringify_map_keys_v<ProcessorsType>) {
return false;
} else if constexpr (internal::has_read_reflector<Key> ||
internal::has_write_reflector<Key>) {
// A write reflector can define from() without declaring ReflType.
if constexpr (requires { typename Reflector<Key>::ReflType; }) {
using ReflType = std::remove_cvref_t<typename Reflector<Key>::ReflType>;
return std::is_same_v<ReflType, std::string>;
} else {
return false;
}
} else {
return std::is_enum_v<Key> &&
!internal::underlying_enums_v<ProcessorsType>;
}
}();

static Result<Key> read(std::string _name) noexcept {
if constexpr (internal::has_read_reflector<Key>) {
try {
using ReflType = typename Reflector<Key>::ReflType;
return Reflector<Key>::to(static_cast<const ReflType&>(_name));
} catch (const std::exception& e) {
return error(e.what());
}
} else if constexpr (std::is_enum_v<Key>) {
return rfl::string_to_enum<Key,
internal::enum_names_only_v<ProcessorsType>>(
_name);
} else {
static_assert(
always_false_v<Key>,
"Reading string-reflected map keys requires Reflector::to.");
}
}

static std::string write(const Key& _key) {
if constexpr (internal::has_write_reflector<Key>) {
return Reflector<Key>::from(_key);
} else if constexpr (std::is_enum_v<Key>) {
return rfl::enum_to_string(_key);
} else {
static_assert(
always_false_v<Key>,
"Writing string-reflected map keys requires Reflector::from.");
}
}
};

} // namespace rfl::parsing

#endif
10 changes: 9 additions & 1 deletion include/rfl/parsing/TypedMapReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

#include "../Result.hpp"
#include "Parser_base.hpp"
#include "StringMapKey.hpp"

namespace rfl::parsing {

Expand All @@ -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<R, W, Key, ProcessorsType>::read(*reader, _key);
auto key = [&]() -> Result<Key> {
if constexpr (StringMapKey<Key, ProcessorsType>::enabled) {
return Parser<R, W, std::string, ProcessorsType>::read(*reader, _key)
.and_then(StringMapKey<Key, ProcessorsType>::read);
} else {
return Parser<R, W, Key, ProcessorsType>::read(*reader, _key);
}
}();
if (!key) {
return Error("Failed to parse map key: " + key.error().what());
}
Expand Down
7 changes: 6 additions & 1 deletion include/rfl/parsing/VectorParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -128,7 +129,11 @@ struct VectorParser {
*/
static constexpr bool treat_as_map() {
if constexpr (is_map_like_not_multimap<VecType>()) {
if constexpr (internal::has_reflection_type_v<typename T::first_type>) {
using Key = std::remove_cvref_t<typename T::first_type>;
if constexpr (StringMapKey<Key, ProcessorsType>::enabled) {
return true;
} else if constexpr (internal::has_reflection_type_v<
typename T::first_type>) {
using U = std::remove_cvref_t<typename T::first_type::ReflectionType>;
return std::is_same<U, std::string>() || std::is_integral_v<U> ||
std::is_floating_point_v<U>;
Expand Down
15 changes: 15 additions & 0 deletions tests/boost_serialization/test_stringify_map_keys.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "../test_stringify_map_keys.hpp"

#include <rfl/boost_serialization.hpp>

namespace test_stringify_map_keys {
TEST(boost_serialization, stringify_map_keys_roundtrip) {
check(
[](const auto& value) {
return rfl::boost_serialization::write<rfl::StringifyMapKeys>(value);
},
[]<class T>(const auto& value) {
return rfl::boost_serialization::read<T, rfl::StringifyMapKeys>(value);
});
}
} // namespace test_stringify_map_keys
15 changes: 15 additions & 0 deletions tests/cbor/test_stringify_map_keys.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "../test_stringify_map_keys.hpp"

#include <rfl/cbor.hpp>

namespace test_stringify_map_keys {
TEST(cbor, stringify_map_keys_roundtrip) {
check(
[](const auto& value) {
return rfl::cbor::write<rfl::StringifyMapKeys>(value);
},
[]<class T>(const auto& value) {
return rfl::cbor::read<T, rfl::StringifyMapKeys>(value);
});
}
} // namespace test_stringify_map_keys
16 changes: 16 additions & 0 deletions tests/generic/test_stringify_map_keys.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#include "../test_stringify_map_keys.hpp"

#include <rfl/generic/read.hpp>
#include <rfl/generic/write.hpp>

namespace test_stringify_map_keys {
TEST(generic, stringify_map_keys_roundtrip) {
check(
[](const auto& value) {
return rfl::generic::write<rfl::StringifyMapKeys>(value);
},
[]<class T>(const auto& value) {
return rfl::generic::read<T, rfl::StringifyMapKeys>(value);
});
}
} // namespace test_stringify_map_keys
Loading
Loading