Added support for flag enums; handle unidentified enums

This commit is contained in:
Patrick Urbanke
2023-12-14 19:38:52 +01:00
parent 79c24add9a
commit a547abd8c1
16 changed files with 496 additions and 112 deletions
+97 -4
View File
@@ -1,6 +1,8 @@
# Enums
reflect-cpp supports scoped enumerations.
reflect-cpp supports scoped enumerations. They can either come in the form of normal enumerations or flag enums.
## Normal enumerations
Example:
@@ -38,7 +40,7 @@ enum struct Color2 { red, green, blue, yellow };
enum Color3 { red, green, blue, yellow };
```
2. You cannot have more than 100 values and if you explicitly assign values, they must be between 0 and 99.
2. You cannot have more than 128 values and if you explicitly assign values, they must be between 0 and 127.
```cpp
/// OK
@@ -50,6 +52,97 @@ enum struct Color2 { red, green, blue = 50, yellow };
/// unsupported - red is a negative value
enum Color3 { red = -10, green, blue, yellow };
/// unsupported - red is greater than 99
/// unsupported - red is greater than 127
enum Color3 { red = 200, green, blue, yellow };
```
```
## Flag enums
Sometimes the enumerations are not mutually exclusive - sticking with the metaphor of colors, it is perfectly
possible for things to have more than one color. C++ programmers sometimes like to model this using a flag enum.
Flag enums work as follows:
1. The bitwise OR operator must be defined on them. If an enum has the bitwise OR operator defined on it, it will be treated as a flag enum.
2. The most important values of the enum must be 1 or 2^N, N being a positive integer (in other words 1,2,4,8,16,32,...).
Example:
```cpp
// The important colors must be 1 or 2^N
enum class Color {
red = 256,
green = 512,
blue = 1024,
yellow = 2048,
orange = (256 | 2048) // red + yellow = orange
};
// The bitwise OR operator must be defined - this is how reflect-cpp knows that
// this is a flag enum.
inline Color operator|(Color c1, Color c2) {
return static_cast<Color>(static_cast<int>(c1) | static_cast<int>(c2));
}
```
In this particular example, the important colors red, green, blue and yellow are all in the form of 2^N.
Other colors are ok as well, if they are expressed as combinations of the 2^N-colors.
When something is a flag enum, then you can also do this:
```cpp
const auto circle =
Circle{.radius = 2.0, .color = Color::blue | Color::green};
```
Which will then be represented as follows:
```json
{"radius":2.0,"color":"blue|green"}
```
Using orange is fine as well:
```cpp
const auto circle =
Circle{.radius = 2.0, .color = Color::orange};
```
But it will be represented in terms of the base colors (which are in the form 2^N):
```json
{"radius":2.0,"color":"red|yellow"}
```
You can also combine orange with another color:
```cpp
const auto circle =
Circle{.radius = 2.0, .color = Color::blue | Color::orange};
```
Which will result in this:
```json
{"radius":2.0,"color":"red|blue|yellow"}
```
## What happens if an enum cannot be matched?
If an enum cannot be matched, it will be written as an integer. This works for both normal enums as well as flag enums.
For instance, if you use the `Color` flag enum as described in the previous section, you can do something like this:
```cpp
// Enums are not supposed to be used like this, but it is defined behavior for scoped enumerations.
const auto circle = Circle{.radius = 2.0, .color = static_cast<Color>(10000)};
```
This will be represented as follows:
```json
{"radius":2.0,"color":"16|red|green|blue|8192"}
```
This works, because 16 + 256 + 512 + 1024 + 8192 = 10000. Flag enums are *always* represented in terms of 2^N-numbers.
@@ -1,60 +0,0 @@
#ifndef RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_
#define RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_
#include <algorithm>
#include <array>
#include <string>
#include <string_view>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/internal/enums/get_enum_names.hpp"
#include "rfl/type_name_t.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType>
struct LiteralConverter {
static constexpr auto names_ = get_enum_names<EnumType>();
using NamesLiteral = typename decltype(names_)::Literal;
static Result<NamesLiteral> enum_to_literal(const EnumType _enum) {
for (size_t i = 0; i < names_.size; ++i) {
if (names_.enums_[i] == _enum) {
return NamesLiteral::from_value(
static_cast<typename NamesLiteral::ValueType>(i));
}
}
return Error(
"Something went wrong when parsing the enum type '" +
type_name_t<EnumType>().str() +
"'. An integer representation of the enum type is " +
std::to_string(static_cast<std::underlying_type_t<EnumType>>(_enum)) +
". Is it possible that some of the values are negative or "
"greater than 99? This is unsupported (as is explicitly "
"stated in the documentation).");
}
static Result<std::string> enum_to_string(const EnumType _enum) {
const auto to_str = [](const auto _l) { return _l.str(); };
return enum_to_literal(_enum).transform(to_str);
}
static EnumType literal_to_enum(const NamesLiteral _lit) {
static_assert(names_.size != 0, "This does not work for empty enums.");
return names_.enums_[_lit.value()];
}
static Result<EnumType> string_to_enum(const std::string& _str) {
return NamesLiteral::from_string(_str).transform(literal_to_enum);
}
};
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
+10 -2
View File
@@ -8,12 +8,13 @@
#include <type_traits>
#include "rfl/Literal.hpp"
#include "rfl/define_literal.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType, class LiteralType, size_t N>
template <class EnumType, class LiteralType, size_t N, auto... _enums>
struct Names {
/// Contains a collection of enums as compile-time strings.
using Literal = LiteralType;
@@ -22,10 +23,17 @@ struct Names {
constexpr static size_t size = N;
/// A list of all the possible enums
std::array<EnumType, N> enums_;
constexpr static std::array<EnumType, N> enums_ =
std::array<EnumType, N>{_enums...};
static_assert(N == 0 || LiteralType::size() == N,
"Size of literal and enum do not match.");
template <class NewLiteral, auto _new_enum>
using AddOneType = std::conditional_t<
N == 0, Names<EnumType, NewLiteral, 1, _new_enum>,
Names<EnumType, define_literal_t<LiteralType, NewLiteral>, N + 1,
_enums..., _new_enum>>;
};
} // namespace enums
@@ -0,0 +1,132 @@
#ifndef RFL_INTERNAL_ENUMS_STRINGCONVERTER_HPP_
#define RFL_INTERNAL_ENUMS_STRINGCONVERTER_HPP_
#include <algorithm>
#include <array>
#include <string>
#include <string_view>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/internal/enums/get_enum_names.hpp"
#include "rfl/internal/enums/is_flag_enum.hpp"
#include "rfl/internal/strings/join.hpp"
#include "rfl/internal/strings/split.hpp"
#include "rfl/type_name_t.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType>
class StringConverter {
private:
static constexpr bool is_flag_enum_ = is_flag_enum<EnumType>;
static constexpr auto names_ = get_enum_names<EnumType, is_flag_enum_>();
using NamesLiteral = typename decltype(names_)::Literal;
public:
/// Transform an enum to a matching string.
static std::string enum_to_string(const EnumType _enum) {
if constexpr (is_flag_enum_) {
return flag_enum_to_string(_enum);
} else {
return enum_to_single_string(_enum);
}
}
/// Transforms a string to the matching enum.
static Result<EnumType> string_to_enum(const std::string& _str) {
static_assert(names_.size != 0,
"No enum could be identified. Please choose enum values "
"between 0 to 127 or for flag enums choose 1,2,4,8,16,...");
if constexpr (is_flag_enum_) {
return string_to_flag_enum(_str);
} else {
return single_string_to_enum(_str);
}
}
private:
/// Iterates through the enum bit by bit and matches it against the flags.
static std::string flag_enum_to_string(const EnumType _e) {
using T = std::underlying_type_t<EnumType>;
auto val = static_cast<T>(_e);
int i = 0;
std::vector<std::string> flags;
while (val != 0) {
const auto bit = val & static_cast<T>(1);
if (bit == 1) {
auto str = enum_to_single_string(
static_cast<EnumType>(static_cast<T>(1) << i));
flags.emplace_back(std::move(str));
}
++i;
val >>= 1;
}
return strings::join("|", flags);
}
/// This assumes that _enum can be exactly matched to one of the names and
/// does not have to be combined using |.
static std::string enum_to_single_string(const EnumType _enum) {
const auto to_str = [](const auto _l) { return _l.str(); };
for (size_t i = 0; i < names_.size; ++i) {
if (names_.enums_[i] == _enum) {
return NamesLiteral::from_value(
static_cast<typename NamesLiteral::ValueType>(i))
.transform(to_str)
.value();
}
}
return std::to_string(static_cast<std::underlying_type_t<EnumType>>(_enum));
}
/// Finds the enum matching the literal.
static EnumType literal_to_enum(const NamesLiteral _lit) noexcept {
return names_.enums_[_lit.value()];
}
/// This assumes that _enum can be exactly matched to one of the names and
/// does not have to be combined using |.
static Result<EnumType> single_string_to_enum(const std::string& _str) {
const auto r = NamesLiteral::from_string(_str).transform(literal_to_enum);
if (r) {
return r;
} else {
try {
return static_cast<EnumType>(std::stoi(_str));
} catch (std::exception& exp) {
return Error(exp.what());
}
}
}
/// Only relevant if this is a flag enum - combines the different matches
/// using |.
static Result<EnumType> string_to_flag_enum(
const std::string& _str) noexcept {
using T = std::underlying_type_t<EnumType>;
const auto split = strings::split(_str, "|");
auto res = static_cast<T>(0);
for (const auto& s : split) {
const auto r = single_string_to_enum(s);
if (r) {
res |= static_cast<T>(*r);
} else {
return r;
}
}
return static_cast<EnumType>(res);
}
};
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
+61 -37
View File
@@ -8,6 +8,7 @@
#include "rfl/Literal.hpp"
#include "rfl/define_literal.hpp"
#include "rfl/internal/enums/Names.hpp"
#include "rfl/internal/enums/is_scoped_enum.hpp"
#include "rfl/internal/remove_namespaces.hpp"
// https://en.cppreference.com/w/cpp/language/static_cast:
@@ -67,51 +68,74 @@ consteval auto get_enum_name() {
return to_str_lit(std::make_index_sequence<name.size()>{});
}
template <class EnumType>
constexpr auto start_value =
Names<EnumType, rfl::Literal<"">, 0>{.enums_ = std::array<EnumType, 0>{}};
template <class T>
consteval T calc_greatest_power_of_two() {
if constexpr (std::is_signed_v<T>) {
return static_cast<T>(1) << (sizeof(T) * 8 - 2);
} else {
return static_cast<T>(1) << (sizeof(T) * 8 - 1);
}
}
template <class EnumType, auto _names = start_value<EnumType>, int _i = 0>
template <class T, bool _is_flag>
consteval T get_max() {
if constexpr (_is_flag) {
return calc_greatest_power_of_two<T>();
} else {
return std::numeric_limits<T>::max() > 127 ? static_cast<T>(127)
: std::numeric_limits<T>::max();
}
}
template <class T, bool _is_flag, int _i>
consteval T calc_j() {
if constexpr (_is_flag) {
return static_cast<T>(1) << _i;
} else {
return static_cast<T>(_i);
}
}
template <class EnumType, class NamesType, auto _max, bool _is_flag, int _i>
consteval auto get_enum_names_impl() {
using T = std::underlying_type_t<EnumType>;
constexpr T j = calc_j<T, _is_flag, _i>();
constexpr auto name = get_enum_name<static_cast<EnumType>(j)>();
if constexpr (std::get<0>(name.arr_) == '(') {
if constexpr (j == _max) {
return NamesType{};
} else {
return get_enum_names_impl<EnumType, NamesType, _max, _is_flag, _i + 1>();
}
} else {
using NewNames = typename NamesType::template AddOneType<
Literal<remove_namespaces<name>()>, static_cast<EnumType>(j)>;
if constexpr (j == _max) {
return NewNames{};
} else {
return get_enum_names_impl<EnumType, NewNames, _max, _is_flag, _i + 1>();
}
}
}
template <class EnumType, bool _is_flag>
consteval auto get_enum_names() {
static_assert(
std::is_enum_v<EnumType> &&
!std::is_convertible_v<EnumType, std::underlying_type_t<EnumType>>,
"You must use scoped enums (using class or struct) for the "
"parsing to work!");
static_assert(is_scoped_enum<EnumType>,
"You must use scoped enums (using class or struct) for the "
"parsing to work!");
static_assert(std::is_integral_v<std::underlying_type_t<EnumType>>,
"The underlying type of any Enum must be integral!");
constexpr auto max =
std::numeric_limits<std::underlying_type_t<EnumType>>::max();
constexpr auto max = get_max<std::underlying_type_t<EnumType>, _is_flag>();
if constexpr (_i == 100 || _i > max) {
return _names;
} else {
constexpr auto name = get_enum_name<static_cast<EnumType>(_i)>();
if constexpr (std::get<0>(name.arr_) == '(') {
return get_enum_names<EnumType, _names, _i + 1>();
} else {
const auto update_enums = [&]<auto... Ns>(std::index_sequence<Ns...>) {
return std::array<EnumType, sizeof...(Ns) + 1>{
_names.enums_[Ns]..., static_cast<EnumType>(_i)};
};
using EmptyNames = Names<EnumType, rfl::Literal<"">, 0>;
using NewNames = std::conditional_t<
decltype(_names)::size == 0,
Names<EnumType, Literal<remove_namespaces<name>()>, 1>,
Names<EnumType,
define_literal_t<typename decltype(_names)::Literal,
Literal<remove_namespaces<name>()>>,
decltype(_names)::size + 1>>;
constexpr auto new_names =
NewNames{.enums_ = update_enums(
std::make_index_sequence<decltype(_names)::size>{})};
return get_enum_names<EnumType, new_names, _i + 1>();
}
}
return get_enum_names_impl<EnumType, EmptyNames, max, _is_flag, 0>();
}
} // namespace enums
@@ -0,0 +1,22 @@
#ifndef RFL_INTERNAL_ENUMS_IS_FLAG_ENUM_HPP_
#define RFL_INTERNAL_ENUMS_IS_FLAG_ENUM_HPP_
#include <concepts>
#include "rfl/internal/enums/is_scoped_enum.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType>
concept is_flag_enum = is_scoped_enum<EnumType> &&
requires(EnumType e1, EnumType e2) {
{ e1 | e2 } -> std::same_as<EnumType>;
};
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
@@ -0,0 +1,19 @@
#ifndef RFL_INTERNAL_ENUMS_IS_SCOPED_ENUM_HPP_
#define RFL_INTERNAL_ENUMS_IS_SCOPED_ENUM_HPP_
#include <concepts>
#include <type_traits>
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType>
concept is_scoped_enum = std::is_enum_v<EnumType> &&
!std::is_convertible_v<EnumType, std::underlying_type_t<EnumType>>;
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
+28
View File
@@ -0,0 +1,28 @@
#ifndef RFL_INTERNAL_STRINGS_JOIN_HPP_
#define RFL_INTERNAL_STRINGS_JOIN_HPP_
#include <string>
#include <vector>
namespace rfl {
namespace internal {
namespace strings {
/// Joins a string using the delimiter
inline std::string join(const std::string& _delimiter,
const std::vector<std::string>& _strings) {
if (_strings.size() == 0) {
return "";
}
auto res = _strings[0];
for (size_t i = 1; i < _strings.size(); ++i) {
res += _delimiter + _strings[i];
}
return res;
}
} // namespace strings
} // namespace internal
} // namespace rfl
#endif
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_INTERNAL_STRINGS_SPLIT_HPP_
#define RFL_INTERNAL_STRINGS_SPLIT_HPP_
#include <string>
#include <vector>
namespace rfl {
namespace internal {
namespace strings {
/// Splits a string alongside the delimiter
inline std::vector<std::string> split(const std::string& _str,
const std::string& _delimiter) {
auto str = _str;
size_t pos = 0;
std::vector<std::string> result;
while ((pos = str.find(_delimiter)) != std::string::npos) {
result.emplace_back(str.substr(0, pos));
str.erase(0, pos + _delimiter.length());
}
result.emplace_back(std::move(str));
return result;
}
} // namespace strings
} // namespace internal
} // namespace rfl
#endif
+5 -9
View File
@@ -35,7 +35,7 @@
#include "rfl/internal/Memoization.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/internal/all_fields.hpp"
#include "rfl/internal/enums/LiteralConverter.hpp"
#include "rfl/internal/enums/StringConverter.hpp"
#include "rfl/internal/flattened_ptr_tuple_t.hpp"
#include "rfl/internal/flattened_tuple_t.hpp"
#include "rfl/internal/get_field_names.hpp"
@@ -106,9 +106,9 @@ struct Parser {
};
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(to_struct);
} else if constexpr (std::is_enum_v<T>) {
using LiteralConverter = internal::enums::LiteralConverter<T>;
using StringConverter = internal::enums::StringConverter<T>;
return _r.template to_basic_type<std::string>(_var).and_then(
LiteralConverter::string_to_enum);
StringConverter::string_to_enum);
} else if constexpr (internal::is_basic_type_v<T>) {
return _r.template to_basic_type<std::decay_t<T>>(_var);
} else {
@@ -136,12 +136,8 @@ struct Parser {
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
} else if constexpr (std::is_enum_v<T>) {
using LiteralConverter = internal::enums::LiteralConverter<T>;
const auto handle_error = [](const auto& _err) -> std::string {
return _err.what();
};
const auto str =
LiteralConverter::enum_to_string(_var).or_else(handle_error).value();
using StringConverter = internal::enums::StringConverter<T>;
const auto str = StringConverter::enum_to_string(_var);
return _w.from_basic_type(str);
} else if constexpr (internal::is_basic_type_v<T>) {
return _w.from_basic_type(_var);
+2
View File
@@ -30,6 +30,8 @@ add_executable(
"test_enum.cpp"
"test_error_messages.cpp"
"test_field_variant.cpp"
"test_flag_enum.cpp"
"test_flag_enum_with_int.cpp"
"test_flatten.cpp"
"test_flatten_anonymous.cpp"
"test_forward_list.cpp"
+40
View File
@@ -0,0 +1,40 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "test_enum.hpp"
#include "write_and_read.hpp"
namespace test_flag_enum {
enum class Color {
red = 256,
green = 512,
blue = 1024,
yellow = 2048,
orange = (256 | 2048) // red + yellow = orange
};
inline Color operator|(Color c1, Color c2) {
return static_cast<Color>(static_cast<int>(c1) | static_cast<int>(c2));
}
struct Circle {
float radius;
Color color;
};
void test() {
std::cout << std::source_location::current().function_name() << std::endl;
const auto circle =
Circle{.radius = 2.0, .color = Color::blue | Color::orange};
write_and_read(circle, R"({"radius":2.0,"color":"red|blue|yellow"})");
}
} // namespace test_flag_enum
+4
View File
@@ -0,0 +1,4 @@
namespace test_flag_enum {
void test();
}
+39
View File
@@ -0,0 +1,39 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "test_enum.hpp"
#include "write_and_read.hpp"
namespace test_flag_enum_with_int {
enum class Color {
red = 256,
green = 512,
blue = 1024,
yellow = 2048,
orange = (256 | 2048) // red + yellow = orange
};
inline Color operator|(Color c1, Color c2) {
return static_cast<Color>(static_cast<int>(c1) | static_cast<int>(c2));
}
struct Circle {
float radius;
Color color;
};
void test() {
std::cout << std::source_location::current().function_name() << std::endl;
const auto circle = Circle{.radius = 2.0, .color = static_cast<Color>(10000)};
write_and_read(circle, R"({"radius":2.0,"color":"16|red|green|blue|8192"})");
}
} // namespace test_flag_enum_with_int
+4
View File
@@ -0,0 +1,4 @@
namespace test_flag_enum_with_int {
void test();
}
+4
View File
@@ -19,6 +19,8 @@
#include "test_enum.hpp"
#include "test_error_messages.hpp"
#include "test_field_variant.hpp"
#include "test_flag_enum.hpp"
#include "test_flag_enum_with_int.hpp"
#include "test_flatten.hpp"
#include "test_flatten_anonymous.hpp"
#include "test_forward_list.hpp"
@@ -67,6 +69,8 @@ int main() {
test_unique_ptr2::test();
test_literal::test();
test_enum::test();
test_flag_enum::test();
test_flag_enum_with_int::test();
test_variant::test();
test_tagged_union::test();
test_tagged_union2::test();