Added support for enums; #3

This commit is contained in:
Patrick Urbanke
2023-12-09 13:27:57 +01:00
parent c95c1f4b05
commit e416283e41
12 changed files with 401 additions and 0 deletions
+23
View File
@@ -160,6 +160,29 @@ Found 5 errors:
5) Field named 'children' not found.
```
## Enums
reflect-cpp supports scoped enumerations:
```cpp
enum class Color { red, green, blue, yellow };
struct Circle {
float radius;
Color color;
};
const auto circle = Circle{.radius = 2.0, .color = Color::green};
rfl::json::write(circle);
```
This results in the following JSON string:
```json
{"radius":2.0,"color":"green"}
```
## Algebraic data types
reflect-cpp supports Pydantic-style tagged unions, which allow you to form algebraic data types:
+55
View File
@@ -0,0 +1,55 @@
# Enums
reflect-cpp supports scoped enumerations.
Example:
```cpp
enum class Color { red, green, blue, yellow };
struct Circle {
float radius;
Color color;
};
const auto circle = Circle{.radius = 2.0, .color = Color::green};
rfl::json::write(circle);
```
This results in the following JSON string:
```json
{"radius":2.0,"color":"green"}
```
However, some limitations apply:
1. They must be be scoped enumerations.
```cpp
/// OK - scoped enumeration
enum class Color1 { red, green, blue, yellow };
/// OK - scoped enumeration
enum struct Color2 { red, green, blue, yellow };
/// unsupported - unscoped enumerations
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.
```cpp
/// OK
enum class Color1 { red, green, blue, yellow };
/// OK
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
enum Color3 { red = 200, green, blue, yellow };
```
+8
View File
@@ -73,6 +73,14 @@ class Literal {
return Literal<fields_...>(_value);
}
/// Constructs a new Literal.
static Result<Literal<fields_...>> from_value(ValueType _value) {
if (_value >= num_fields_) {
return Error("Value cannot exceed number of fields.");
}
return Literal<fields_...>(_value);
}
/// Determines whether the literal contains the string.
static bool contains(const std::string& _str) { return has_value(_str); }
@@ -0,0 +1,38 @@
#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/Literal.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType, class LiteralType, size_t N>
struct Names {
/// Contains a collection of enums as compile-time strings.
using Names = LiteralType;
/// The number of possible values
constexpr static size_t size = N;
/// A list of all the possible enums
std::array<EnumType, N> enums_;
/// The integer values underlying the enum.
std::array<std::underlying_type_t<EnumType>, N> integers_;
static_assert(LiteralType::size() == N,
"Size of literal and enum do not match.");
};
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
@@ -0,0 +1,59 @@
#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) {
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
+38
View File
@@ -0,0 +1,38 @@
#ifndef RFL_INTERNAL_ENUMS_NAMES_HPP_
#define RFL_INTERNAL_ENUMS_NAMES_HPP_
#include <algorithm>
#include <array>
#include <string>
#include <string_view>
#include <type_traits>
#include "rfl/Literal.hpp"
namespace rfl {
namespace internal {
namespace enums {
template <class EnumType, class LiteralType, size_t N>
struct Names {
/// Contains a collection of enums as compile-time strings.
using Literal = LiteralType;
/// The number of possible values
constexpr static size_t size = N;
/// A list of all the possible enums
std::array<EnumType, N> enums_;
/// The integer values underlying the enum.
std::array<std::underlying_type_t<EnumType>, N> integers_;
static_assert(N == 0 || LiteralType::size() == N,
"Size of literal and enum do not match.");
};
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
@@ -0,0 +1,130 @@
#ifndef RFL_INTERNAL_ENUMS_GET_ENUM_NAMES_HPP_
#define RFL_INTERNAL_ENUMS_GET_ENUM_NAMES_HPP_
#include <limits>
#include <source_location>
#include <type_traits>
#include "rfl/Literal.hpp"
#include "rfl/define_literal.hpp"
#include "rfl/internal/enums/Names.hpp"
#include "rfl/internal/remove_namespaces.hpp"
// https://en.cppreference.com/w/cpp/language/static_cast:
// 8) A value of integer or enumeration type can be converted to any complete
// enumeration type.
// If the underlying type is not fixed, the behavior is undefined if the value
// of expression is out of range (the range is all values possible for the
// smallest bit-field large enough to hold all enumerators of the target
// enumeration). If the underlying type is fixed, the result is the same as
// converting the original value first to the underlying type of the enumeration
// and then to the enumeration type.
// https://en.cppreference.com/w/cpp/language/enum
// enum struct|class name { enumerator = constexpr , enumerator = constexpr ,
// ... } (1)
// ...
// 1) declares a scoped enumeration type whose underlying type is int (the
// keywords class and struct are exactly equivalent)
//
// --> These rules taken together imply that if you EITHER fix the type OR you
// use a scoped integer, static_cast<MyEnum>(some_integer_value) will always be
// defined.
namespace rfl {
namespace internal {
namespace enums {
template <auto e>
consteval auto get_enum_name_str_view() {
const auto func_name =
std::string_view{std::source_location::current().function_name()};
#if defined(__clang__)
const auto split = func_name.substr(0, func_name.size() - 1);
return split.substr(split.find("e = ") + 4);
#elif defined(__GNUC__)
const auto split = func_name.substr(0, func_name.size() - 1);
return split.substr(split.find("e = ") + 4);
#elif defined(_MSC_VER)
const auto split = func_name.substr(0, func_name.size() - 7);
return split.substr(split.find("get_enum_name_str_view<") + 23);
#else
static_assert(false,
"You are using an unsupported compiler. Please use GCC, Clang "
"or MSVC or use rfl::Literal.");
#endif
}
template <auto e>
consteval auto get_enum_name() {
constexpr auto name = get_enum_name_str_view<e>();
const auto to_str_lit = [&]<auto... Ns>(std::index_sequence<Ns...>) {
return StringLiteral<sizeof...(Ns) + 1>{name[Ns]...};
};
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>{},
.integers_ = std::array<std::underlying_type_t<EnumType>, 0>{}};
template <class EnumType, auto _names = start_value<EnumType>, int _i = 0>
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(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();
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)};
};
const auto update_integers = [&]<auto... Ns>(std::index_sequence<Ns...>) {
return std::array<std::underlying_type_t<EnumType>, sizeof...(Ns) + 1>{
_names.integers_[Ns]...,
static_cast<std::underlying_type_t<EnumType>>(_i)};
};
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>{}),
.integers_ = update_integers(
std::make_index_sequence<decltype(_names)::size>{})};
return get_enum_names<EnumType, new_names, _i + 1>();
}
}
}
} // namespace enums
} // namespace internal
} // namespace rfl
#endif
+13
View File
@@ -35,6 +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/flattened_ptr_tuple_t.hpp"
#include "rfl/internal/flattened_tuple_t.hpp"
#include "rfl/internal/get_field_names.hpp"
@@ -104,6 +105,10 @@ 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>;
return _r.template to_basic_type<std::string>(_var).and_then(
LiteralConverter::string_to_enum);
} else if constexpr (internal::is_basic_type_v<T>) {
return _r.template to_basic_type<std::decay_t<T>>(_var);
} else {
@@ -130,6 +135,14 @@ struct Parser {
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
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();
return _w.from_basic_type(str);
} else if constexpr (internal::is_basic_type_v<T>) {
return _w.from_basic_type(_var);
} else {
+1
View File
@@ -27,6 +27,7 @@ add_executable(
"test_default_values.cpp"
"test_deque.cpp"
"test_email.cpp"
"test_enum.cpp"
"test_error_messages.cpp"
"test_field_variant.cpp"
"test_flatten.cpp"
+30
View File
@@ -0,0 +1,30 @@
#include "test_enum.hpp"
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_enum {
enum class Color { red, green, blue, yellow };
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::green};
write_and_read(circle, R"({"radius":2.0,"color":"green"})");
}
} // namespace test_enum
+4
View File
@@ -0,0 +1,4 @@
namespace test_enum {
void test();
}
+2
View File
@@ -16,6 +16,7 @@
#include "test_default_values.hpp"
#include "test_deque.hpp"
#include "test_email.hpp"
#include "test_enum.hpp"
#include "test_error_messages.hpp"
#include "test_field_variant.hpp"
#include "test_flatten.hpp"
@@ -65,6 +66,7 @@ int main() {
test_unique_ptr::test();
test_unique_ptr2::test();
test_literal::test();
test_enum::test();
test_variant::test();
test_tagged_union::test();
test_tagged_union2::test();