Added a custom implementation of a variant (rfl::Variant) (#151)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-07-17 22:10:28 +02:00
committed by GitHub
parent 0045030512
commit a562a6fb88
53 changed files with 1431 additions and 426 deletions
+1 -1
View File
@@ -478,7 +478,7 @@ In addition, it supports the following custom containers:
- `rfl::Result`: Allows for exception-free programming.
- `rfl::TaggedUnion`: Similar to `std::variant`, but with explicit tags that make parsing more efficient.
- `rfl::Validator`: Allows for automatic input validation.
- `rfl::Variant`: An alternative to `std::variant`.
- `rfl::Variant`: An alternative to `std::variant` that compiles considerably faster.
### Custom classes
+21 -9
View File
@@ -1,10 +1,19 @@
# `std::variant`, `rfl::Variant` and `rfl::TaggedUnion`
## `std::variant` or `rfl::Variant` (untagged)
## `rfl::Variant` (untagged)
Sometimes you know that the JSON object can be one of several alternatives. For example,
you might have several shapes like `Circle`, `Rectangle` or `Square`. For these kind of
cases, the C++ standard library contains `std::variant`, even though we we recommend you to use `rfl::Variant` instead:
cases, the C++ standard library contains `std::variant` and it is supported by reflect-cpp.
However, we recommend you use `rfl::Variant` instead.
`rfl::Variant` behaves just like `std::variant`, but it compiles considerably faster,
particularly for variants with many alternatives.
You can use the functions `rfl::get`, `rfl::get_if`, `rfl::holds_alternative`, `rfl::visit`,
`rfl::variant_alternative_t` and `rfl::variant_size_v` to access the variant and they work
the same way as their equivalents in the standard library.
```cpp
struct Circle {
@@ -34,7 +43,7 @@ several problems with this:
1) It is in inefficient: The parser has to read the fields for all of the different alternatives until it can't find a required field in the JSON object. It will then move on to the next alternative.
2) It leads to confusing error messages: If none of the alternatives can be matched, you will get an error message telling you why each of the alternatives couldn't be matched. Such error messages are very long-winding and hard to read.
3) It is dangerous. Imagine we had written `std::variant<Circle, Square, Rectangle>` instead of `std::variant<Circle, Rectangle, Square>`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs.
3) It is dangerous. Imagine we had written `rfl::Variant<Circle, Square, Rectangle>` instead of `rfl::Variant<Circle, Rectangle, Square>`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs.
## `rfl::TaggedUnion` (internally tagged)
@@ -196,7 +205,7 @@ Because the tag is external, this is called *externally tagged*. It is the stand
## The visitor pattern
In C++, the idiomatic way to handle `std::variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit).
In C++, the idiomatic way to handle `std::variant`, `rfl::Variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit).
For instance, the externally tagged `rfl::Variant` from the example above could be handled like this:
@@ -223,10 +232,13 @@ const auto handle_shapes = [](const auto& field) {
}
};
std::visit(handle_shapes, my_shape.variant());
rfl::visit(handle_shapes, my_shape); // OK
my_shape.visit(handle_shapes); // also OK
```
Likewise, `rfl::TaggedUnion` contains `std::variant` under-the-hood. The original variant can be
You can also apply `rfl::visit` to `rfl::TaggedUnion`. The underlying `rfl::Variant` can be
retrieved using `.variant()`:
```cpp
@@ -247,7 +259,7 @@ const auto handle_shapes = [](const auto& s) {
}
};
std::visit(handle_shapes, my_shape.variant());
rfl::visit(handle_shapes, my_shape); // OK
my_shape.visit(handle_shapes); // also OK
```
+8 -7
View File
@@ -13,6 +13,7 @@
#include "Result.hpp"
#include "internal/StringLiteral.hpp"
#include "internal/no_duplicate_field_names.hpp"
#include "internal/nth_tuple_element_t.hpp"
namespace rfl {
@@ -182,7 +183,7 @@ class Literal {
#if __cpp_lib_three_way_comparison >= 201907L
return name() <=> _str;
#else
auto const &const_name = name();
auto const& const_name = name();
if (const_name < _str) {
return std::strong_ordering::less;
}
@@ -199,7 +200,7 @@ class Literal {
#if __cpp_lib_three_way_comparison >= 201907L
return name() <=> _str;
#else
auto const &const_name = name();
auto const& const_name = name();
if (const_name < _str) {
return std::strong_ordering::less;
}
@@ -268,7 +269,7 @@ class Literal {
template <int _i>
static void allowed_strings_vec_add_one(std::vector<std::string>* _values) {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
using FieldType = internal::nth_tuple_element_t<_i, FieldsType>;
_values->emplace_back(FieldType::name_.str());
}
@@ -288,7 +289,7 @@ class Literal {
template <int _i>
void find_name_set_if_matches(std::string* _name) const {
if (_i == value_) {
using FieldType = typename std::tuple_element_t<_i, FieldsType>;
using FieldType = internal::nth_tuple_element_t<_i, FieldsType>;
*_name = FieldType::name_.str();
}
}
@@ -297,7 +298,7 @@ class Literal {
/// the string at compile time within the Literal's own fields.
template <int _i>
constexpr static auto find_name_within_own_fields() {
return std::tuple_element_t<_i, FieldsType>::name_;
return internal::nth_tuple_element_t<_i, FieldsType>::name_;
}
/// Finds the correct value associated with
@@ -325,7 +326,7 @@ class Literal {
template <int _i>
static void find_value_set_if_matches(const std::string& _str, bool* _found,
int* _idx) {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
using FieldType = internal::nth_tuple_element_t<_i, FieldsType>;
if (!*_found && FieldType::name_.string_view() == _str) {
*_idx = _i;
*_found = true;
@@ -338,7 +339,7 @@ class Literal {
if constexpr (_i == num_fields_) {
return -1;
} else {
using FieldType = typename std::tuple_element<_i, FieldsType>::type;
using FieldType = internal::nth_tuple_element_t<_i, FieldsType>;
if constexpr (FieldType::name_ == _name) {
return _i;
} else {
+8 -6
View File
@@ -14,6 +14,7 @@
#include "internal/find_index.hpp"
#include "internal/is_extra_fields.hpp"
#include "internal/no_duplicate_field_names.hpp"
#include "internal/nth_tuple_element_t.hpp"
namespace rfl {
@@ -444,7 +445,7 @@ class NamedTuple {
if constexpr (_i == size()) {
return _idx;
} else {
using FieldType = typename std::tuple_element_t<_i, Fields>;
using FieldType = internal::nth_element_t<_i, FieldTypes...>;
constexpr bool is_extra_fields =
internal::is_extra_fields_v<typename FieldType::Type>;
static_assert(_idx == -1 || !is_extra_fields,
@@ -472,7 +473,7 @@ class NamedTuple {
} else {
// When we add additional fields, it is more intuitive to add
// them to the end, that is why we do it like this.
using FieldType = typename std::tuple_element_t<i, Fields>;
using FieldType = internal::nth_element_t<i, FieldTypes...>;
using T = std::remove_cvref_t<typename FieldType::Type>;
return make_fields<num_additional_fields>(
FieldType(std::forward<T>(std::get<i>(values_))),
@@ -494,7 +495,7 @@ class NamedTuple {
} else {
// When we add additional fields, it is more intuitive to add
// them to the end, that is why we do it like this.
using FieldType = typename std::tuple_element<i, Fields>::type;
using FieldType = internal::nth_element_t<i, FieldTypes...>;
return make_fields<num_additional_fields>(FieldType(std::get<i>(values_)),
std::move(_args)...);
}
@@ -510,7 +511,7 @@ class NamedTuple {
if constexpr (retrieved_all_fields) {
return NamedTuple<FieldTypes...>(std::forward<Args>(_args)...);
} else {
using FieldType = typename std::tuple_element<size, Fields>::type;
using FieldType = internal::nth_element_t<size, FieldTypes...>;
if constexpr (size == _index) {
return make_replaced<_index, V, T>(
@@ -581,12 +582,13 @@ class NamedTuple {
if constexpr (retrieved_all_fields) {
return std::make_tuple(std::forward<Args>(_args)...);
} else {
constexpr auto field_name = std::tuple_element<size, Fields>::type::name_;
constexpr auto field_name =
internal::nth_element_t<size, FieldTypes...>::name_;
constexpr auto index =
internal::find_index<field_name, std::tuple<OtherFieldTypes...>>();
using FieldType = typename std::tuple_element<size, Fields>::type;
using FieldType = internal::nth_element_t<size, FieldTypes...>;
using T = std::remove_cvref_t<typename FieldType::Type>;
+2 -1
View File
@@ -1,6 +1,7 @@
#ifndef RFL_RESULT_HPP_
#define RFL_RESULT_HPP_
#include <algorithm>
#include <array>
#include <iostream>
#include <optional>
@@ -327,7 +328,7 @@ class Result {
return *(reinterpret_cast<const Error*>(t_or_err_.data()));
}
void move_from_other(Result<T>& _other) {
void move_from_other(Result<T>& _other) noexcept {
if (success_) {
new (&get_t()) T(std::move(_other.get_t()));
} else {
+26 -59
View File
@@ -1,8 +1,7 @@
#ifndef RFL_TAGGEDUNION_HPP_
#define RFL_TAGGEDUNION_HPP_
#include <variant>
#include "Variant.hpp"
#include "define_literal.hpp"
#include "internal/Getter.hpp"
#include "internal/StringLiteral.hpp"
@@ -16,7 +15,7 @@ struct TaggedUnion {
static constexpr internal::StringLiteral discrimininator_ = _discriminator;
/// The type of the underlying variant.
using VariantType = std::variant<Ts...>;
using VariantType = rfl::Variant<Ts...>;
/// A literal containing all the tags that are possible
using PossibleTags = define_literal_t<internal::tag_t<_discriminator, Ts>...>;
@@ -88,6 +87,30 @@ struct TaggedUnion {
/// Returns the underlying variant.
const VariantType& variant() const { return variant_; }
/// Applies function _f to all underlying alternatives.
template <class F>
auto visit(F& _f) {
return variant_.visit(_f);
}
/// Applies function _f to all underlying alternatives.
template <class F>
auto visit(F& _f) const {
return variant_.visit(_f);
}
/// Applies function _f to all underlying alternatives.
template <class F>
auto visit(const F& _f) {
return variant_.visit(_f);
}
/// Applies function _f to all underlying alternatives.
template <class F>
auto visit(const F& _f) const {
return variant_.visit(_f);
}
static_assert(!PossibleTags::has_duplicates(),
"Duplicate tags are not allowed inside tagged unions.");
@@ -96,62 +119,6 @@ struct TaggedUnion {
VariantType variant_;
};
namespace internal {
template <StringLiteral _discriminator, class... NamedTupleTypes>
struct Getter<TaggedUnion<_discriminator, NamedTupleTypes...>> {
public:
/// Retrieves the indicated value from the tuple.
template <int _index>
static inline auto& get(
TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get<_index>(
_tu.variant_);
}
/// Gets a field by name.
template <StringLiteral _field_name>
static inline auto& get(
TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get<_field_name>(
_tu.variant_);
}
/// Gets a field by the field type.
template <class Field>
static inline auto& get(
TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get<Field>(
_tu.variant_);
}
/// Retrieves the indicated value from the tuple.
template <int _index>
static inline const auto& get_const(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get_const<_index>(
_tu.variant_);
}
/// Gets a field by name.
template <StringLiteral _field_name>
static inline const auto& get_const(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get_const<
_field_name>(_tu.variant_);
}
/// Gets a field by the field type.
template <class Field>
static inline const auto& get_const(
const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) {
return Getter<std::variant<NamedTupleTypes...>>::template get_const<Field>(
_tu.variant_);
}
};
} // namespace internal
} // namespace rfl
#endif // RFL_TAGGEDUNION_HPP_
+476 -45
View File
@@ -1,84 +1,515 @@
#ifndef RFL_VARIANT_HPP_
#define RFL_VARIANT_HPP_
#include <variant>
#include <array>
#include <bit>
#include <cstdint>
#include <limits>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <utility>
#include "internal/element_index.hpp"
#include "internal/nth_element_t.hpp"
#include "internal/variant/find_max_size.hpp"
#include "internal/variant/is_alternative_type.hpp"
namespace rfl {
template <class... AlternativeTypes>
struct Variant {
/// The type of the underlying variant.
using VariantType = std::variant<AlternativeTypes...>;
class Variant {
static constexpr auto max_size_wrapper_ =
internal::variant::find_max_size<AlternativeTypes...>();
Variant(const VariantType& _variant) : variant_(_variant) {}
static constexpr unsigned long num_bytes_ = max_size_wrapper_.size_;
Variant(VariantType&& _variant) noexcept : variant_(std::move(_variant)) {}
using LargestType = typename decltype(max_size_wrapper_)::Type;
Variant(const Variant<AlternativeTypes...>& _variant) = default;
using DataType = std::array<unsigned char, num_bytes_>;
Variant(Variant<AlternativeTypes...>&& _variant) noexcept = default;
using IndexType =
std::conditional_t<sizeof...(AlternativeTypes) <=
std::numeric_limits<std::uint8_t>::max(),
std::uint8_t, std::uint16_t>;
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant(const T& _t) : variant_(_t) {}
static constexpr IndexType size_ = sizeof...(AlternativeTypes);
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant(T&& _t) noexcept : variant_(std::forward<T>(_t)) {}
template <IndexType _i>
struct Index {};
~Variant() = default;
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(const VariantType& _variant) {
variant_ = _variant;
return *this;
public:
Variant() {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
move_from_type(FirstAlternative());
}
Variant(const Variant<AlternativeTypes...>& _other) {
copy_from_other(_other);
}
Variant(Variant<AlternativeTypes...>&& _other) noexcept {
move_from_other(std::move(_other));
}
template <class T,
typename std::enable_if<internal::variant::is_alternative_type<
T, AlternativeTypes...>(),
bool>::type = true>
Variant(const T& _t) {
copy_from_type(_t);
}
template <class T,
typename std::enable_if<internal::variant::is_alternative_type<
T, AlternativeTypes...>(),
bool>::type = true>
Variant(T&& _t) noexcept {
move_from_type(std::forward<T>(_t));
}
~Variant() { destroy_if_necessary(); }
/// Emplaces a new element into the variant.
template <class T, class... Args>
constexpr T& emplace(Args&&... _args) {
auto t = T{std::forward<Args>(_args)...};
destroy_if_necessary();
move_from_type(std::move(t));
return *(reinterpret_cast<T*>(data_.data()));
}
/// Emplaces a new element into the variant.
template <int _i, class... Args>
constexpr auto& emplace(Args&&... _args) {
using T = internal::nth_element_t<_i, AlternativeTypes...>;
return emplace<T>(std::move(_args)...);
}
/// Returns the index of the element currently held.
constexpr int index() const noexcept { return index_; }
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(VariantType&& _variant) {
variant_ = std::move(_variant);
template <class T,
typename std::enable_if<internal::variant::is_alternative_type<
T, AlternativeTypes...>(),
bool>::type = true>
Variant<AlternativeTypes...>& operator=(const T& _t) {
auto temp = Variant<AlternativeTypes...>(_t);
destroy_if_necessary();
move_from_other(std::move(temp));
return *this;
}
/// Assigns the underlying object.
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
typename std::enable_if<internal::variant::is_alternative_type<
T, AlternativeTypes...>(),
bool>::type = true>
Variant<AlternativeTypes...>& operator=(T&& _variant) {
variant_ = std::forward<T>(_variant);
return *this;
}
/// Assigns the underlying object.
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant<AlternativeTypes...>& operator=(const T& _variant) {
variant_ = _variant;
Variant<AlternativeTypes...>& operator=(T&& _t) noexcept {
destroy_if_necessary();
move_from_type(std::forward<T>(_t));
return *this;
}
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(
const Variant<AlternativeTypes...>& _other) = default;
const Variant<AlternativeTypes...>& _other) {
if (this == &_other) {
return *this;
}
auto temp = Variant<AlternativeTypes...>(_other);
destroy_if_necessary();
move_from_other(std::move(temp));
return *this;
}
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(
Variant<AlternativeTypes...>&& _other) = default;
Variant<AlternativeTypes...>&& _other) noexcept {
if (this == &_other) {
return *this;
}
destroy_if_necessary();
move_from_other(std::move(_other));
return *this;
}
/// Returns the underlying variant.
VariantType& variant() { return variant_; }
/// Swaps the content with the other variant.
void swap(Variant<AlternativeTypes...>& _other) noexcept {
if (this == &_other) {
return;
}
auto temp = Variant<AlternativeTypes...>(std::move(*this));
move_from_other(std::move(_other));
_other = std::move(temp);
}
/// Returns the underlying variant.
const VariantType& variant() const { return variant_; }
template <class F>
auto visit(F& _f) {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
using ResultType = std::remove_cvref_t<
std::invoke_result_t<std::remove_cvref_t<F>, FirstAlternative&>>;
if constexpr (std::is_same_v<ResultType, void>) {
bool visited = false;
do_visit_no_result(_f, &visited,
std::make_integer_sequence<IndexType, size_>());
} else {
auto res = std::optional<ResultType>();
do_visit_with_result(_f, &res,
std::make_integer_sequence<IndexType, size_>());
return std::move(*res);
}
}
/// The underlying variant - a Variant is a thin wrapper
/// around a variant that is mainly used for parsing.
VariantType variant_;
template <class F>
auto visit(F& _f) const {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
using ResultType = std::remove_cvref_t<
std::invoke_result_t<std::remove_cvref_t<F>, FirstAlternative&>>;
if constexpr (std::is_same_v<ResultType, void>) {
bool visited = false;
do_visit_no_result(_f, &visited,
std::make_integer_sequence<IndexType, size_>());
} else {
auto res = std::optional<ResultType>();
do_visit_with_result(_f, &res,
std::make_integer_sequence<IndexType, size_>());
return std::move(*res);
}
}
template <class F>
auto visit(const F& _f) {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
using ResultType = std::remove_cvref_t<
std::invoke_result_t<std::remove_cvref_t<F>, FirstAlternative&>>;
if constexpr (std::is_same_v<ResultType, void>) {
bool visited = false;
do_visit_no_result(_f, &visited,
std::make_integer_sequence<IndexType, size_>());
} else {
auto res = std::optional<ResultType>();
do_visit_with_result(_f, &res,
std::make_integer_sequence<IndexType, size_>());
return std::move(*res);
}
}
template <class F>
auto visit(const F& _f) const {
using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>;
using ResultType = std::remove_cvref_t<
std::invoke_result_t<std::remove_cvref_t<F>, FirstAlternative&>>;
if constexpr (std::is_same_v<ResultType, void>) {
bool visited = false;
do_visit_no_result(_f, &visited,
std::make_integer_sequence<IndexType, size_>());
} else {
auto res = std::optional<ResultType>();
do_visit_with_result(_f, &res,
std::make_integer_sequence<IndexType, size_>());
return std::move(*res);
}
}
private:
void copy_from_other(const Variant<AlternativeTypes...>& _other) {
const auto copy_one = [this](const auto& _t) { this->copy_from_type(_t); };
_other.visit(copy_one);
}
template <class T>
void copy_from_type(const T& _t) noexcept {
using CurrentType = std::remove_cvref_t<decltype(_t)>;
index_ =
internal::element_index<CurrentType,
std::remove_cvref_t<AlternativeTypes>...>();
new (reinterpret_cast<CurrentType*>(data_.data())) CurrentType(_t);
}
void destroy_if_necessary() {
const auto destroy_one = [](auto& _t) {
using T = std::remove_cvref_t<decltype(_t)>;
if constexpr (std::is_destructible_v<T>) {
_t.~T();
}
};
visit(destroy_one);
}
template <class F, IndexType... _is>
void do_visit_no_result(F& _f, bool* _visited,
std::integer_sequence<IndexType, _is...>) {
auto visit_one = [this]<IndexType _i>(const F& _f, bool* _visited,
Index<_i>) {
if (!*_visited && index_ == _i) {
_f(get_alternative<_i>());
*_visited = true;
}
};
(visit_one(_f, _visited, Index<_is>{}), ...);
}
template <class F, IndexType... _is>
void do_visit_no_result(F& _f, bool* _visited,
std::integer_sequence<IndexType, _is...>) const {
auto visit_one = [this]<IndexType _i>(const F& _f, bool* _visited,
Index<_i>) {
if (!*_visited && index_ == _i) {
_f(get_alternative<_i>());
*_visited = true;
}
};
(visit_one(_f, _visited, Index<_is>{}), ...);
}
template <class F, class ResultType, IndexType... _is>
void do_visit_with_result(F& _f, std::optional<ResultType>* _res,
std::integer_sequence<IndexType, _is...>) {
auto visit_one = [this]<IndexType _i>(const F& _f,
std::optional<ResultType>* _res,
Index<_i>) {
if (!*_res && index_ == _i) {
*_res = _f(get_alternative<_i>());
}
};
(visit_one(_f, _res, Index<_is>{}), ...);
}
template <class F, class ResultType, IndexType... _is>
void do_visit_with_result(F& _f, std::optional<ResultType>* _res,
std::integer_sequence<IndexType, _is...>) const {
auto visit_one = [this]<IndexType _i>(const F& _f,
std::optional<ResultType>* _res,
Index<_i>) {
if (!*_res && index_ == _i) {
*_res = _f(get_alternative<_i>());
}
};
(visit_one(_f, _res, Index<_is>{}), ...);
}
template <class F, IndexType... _is>
void do_visit_no_result(const F& _f, bool* _visited,
std::integer_sequence<IndexType, _is...>) {
const auto visit_one = [this]<IndexType _i>(const F& _f, bool* _visited,
Index<_i>) {
if (!*_visited && index_ == _i) {
_f(get_alternative<_i>());
*_visited = true;
}
};
(visit_one(_f, _visited, Index<_is>{}), ...);
}
template <class F, IndexType... _is>
void do_visit_no_result(const F& _f, bool* _visited,
std::integer_sequence<IndexType, _is...>) const {
const auto visit_one = [this]<IndexType _i>(const F& _f, bool* _visited,
Index<_i>) {
if (!*_visited && index_ == _i) {
_f(get_alternative<_i>());
*_visited = true;
}
};
(visit_one(_f, _visited, Index<_is>{}), ...);
}
template <class F, class ResultType, IndexType... _is>
void do_visit_with_result(const F& _f, std::optional<ResultType>* _res,
std::integer_sequence<IndexType, _is...>) {
const auto visit_one = [this]<IndexType _i>(const F& _f,
std::optional<ResultType>* _res,
Index<_i>) {
if (!*_res && index_ == _i) {
*_res = _f(get_alternative<_i>());
}
};
(visit_one(_f, _res, Index<_is>{}), ...);
}
template <class F, class ResultType, IndexType... _is>
void do_visit_with_result(const F& _f, std::optional<ResultType>* _res,
std::integer_sequence<IndexType, _is...>) const {
const auto visit_one = [this]<IndexType _i>(const F& _f,
std::optional<ResultType>* _res,
Index<_i>) {
if (!*_res && index_ == _i) {
*_res = _f(get_alternative<_i>());
}
};
(visit_one(_f, _res, Index<_is>{}), ...);
}
template <IndexType _i>
auto& get_alternative() noexcept {
using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>;
return *(reinterpret_cast<CurrentType*>(data_.data()));
}
template <IndexType _i>
const auto& get_alternative() const noexcept {
using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>;
return *(reinterpret_cast<const CurrentType*>(data_.data()));
}
void move_from_other(Variant<AlternativeTypes...>&& _other) noexcept {
const auto move_one = [this](auto&& _t) {
this->move_from_type(std::forward<std::remove_cvref_t<decltype(_t)>>(_t));
};
std::forward<Variant<AlternativeTypes...>>(_other).visit(move_one);
}
template <class T>
void move_from_type(T&& _t) noexcept {
using CurrentType = std::remove_cvref_t<decltype(_t)>;
index_ =
internal::element_index<CurrentType,
std::remove_cvref_t<AlternativeTypes>...>();
new (reinterpret_cast<CurrentType*>(data_.data()))
CurrentType(std::forward<T>(_t));
}
private:
/// Index indicating which of the alternatives is currently contained in the
/// variant.
IndexType index_;
/// The underlying data, can be any of the underlying types.
alignas(LargestType) DataType data_;
};
template <class T, class... Types>
constexpr T* get_if(Variant<Types...>& _v) noexcept {
const auto get = [](auto& _v) -> T* {
using Type = std::remove_cvref_t<decltype(_v)>;
if constexpr (std::is_same<Type, std::remove_cvref_t<T>>()) {
return &_v;
} else {
return nullptr;
}
};
return _v.visit(get);
}
template <class T, class... Types>
constexpr const T* get_if(const Variant<Types...>& _v) noexcept {
const auto get = [](const auto& _v) -> const T* {
using Type = std::remove_cvref_t<decltype(_v)>;
if constexpr (std::is_same<Type, std::remove_cvref_t<T>>()) {
return &_v;
} else {
return nullptr;
}
};
return _v.visit(get);
}
template <int _i, class... Types>
constexpr auto* get_if(Variant<Types...>& _v) noexcept {
using T = internal::nth_element_t<_i, Types...>;
return get_if<T>(_v);
}
template <int _i, class... Types>
constexpr auto* get_if(const Variant<Types...>& _v) noexcept {
using T = internal::nth_element_t<_i, Types...>;
return get_if<T>(_v);
}
template <class T, class... Types>
constexpr T& get(Variant<Types...>& _v) {
auto ptr = get_if<T>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return *ptr;
}
template <class T, class... Types>
constexpr T&& get(Variant<Types...>&& _v) {
auto ptr = get_if<T>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return std::move(*ptr);
}
template <class T, class... Types>
constexpr const T& get(const Variant<Types...>& _v) {
auto ptr = get_if<T>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return *ptr;
}
template <int _i, class... Types>
constexpr auto& get(Variant<Types...>& _v) {
auto ptr = get_if<_i>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return *ptr;
}
template <int _i, class... Types>
constexpr auto&& get(Variant<Types...>&& _v) {
auto ptr = get_if<_i>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return std::move(*ptr);
}
template <int _i, class... Types>
constexpr const auto& get(const Variant<Types...>& _v) {
auto ptr = get_if<_i>(_v);
if (!ptr) {
throw std::runtime_error("Variant does not contain signified type.");
}
return *ptr;
}
template <class T, class... Types>
constexpr bool holds_alternative(const Variant<Types...>& _v) noexcept {
constexpr auto ix = internal::element_index<std::remove_cvref_t<T>,
std::remove_cvref_t<Types>...>();
static_assert(ix != -1, "Type not supported.");
return ix == _v.index();
}
template <int N, class T>
struct variant_alternative;
template <int N, class... Types>
struct variant_alternative<N, Variant<Types...>> {
using type = internal::nth_element_t<N, Types...>;
};
template <int N, class VariantType>
using variant_alternative_t =
typename variant_alternative<N, std::remove_cvref_t<VariantType>>::type;
template <class T>
struct variant_size;
template <class... Types>
struct variant_size<Variant<Types...>>
: std::integral_constant<size_t, sizeof...(Types)> {};
template <class VariantType>
constexpr size_t variant_size_v =
variant_size<std::remove_cvref_t<VariantType>>();
} // namespace rfl
namespace std {
template <class... Types>
void swap(rfl::Variant<Types...>& _lhs, rfl::Variant<Types...>& _rhs) noexcept {
_lhs.swap(_rhs);
};
} // namespace std
#endif
+12 -12
View File
@@ -26,8 +26,8 @@ struct EqualTo {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::EqualTo{.value_ = value}};
}
};
@@ -50,8 +50,8 @@ struct Minimum {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::Minimum{.value_ = value}};
}
};
@@ -74,8 +74,8 @@ struct ExclusiveMinimum {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::ExclusiveMinimum{.value_ = value}};
}
};
@@ -98,8 +98,8 @@ struct Maximum {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::Maximum{.value_ = value}};
}
};
@@ -122,8 +122,8 @@ struct ExclusiveMaximum {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::ExclusiveMaximum{.value_ = value}};
}
};
@@ -146,8 +146,8 @@ struct NotEqualTo {
using ValidationType = parsing::schema::ValidationType;
const auto value =
std::is_floating_point_v<T>
? std::variant<double, int>(static_cast<double>(_threshold))
: std::variant<double, int>(static_cast<int>(_threshold));
? rfl::Variant<double, int>(static_cast<double>(_threshold))
: rfl::Variant<double, int>(static_cast<int>(_threshold));
return ValidationType{ValidationType::NotEqualTo{.value_ = value}};
}
};
+5 -74
View File
@@ -6,6 +6,7 @@
#include "StringLiteral.hpp"
#include "find_index.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl::internal {
@@ -40,8 +41,8 @@ struct Getter {
constexpr auto index =
find_index<Field::name_, typename NamedTupleType::Fields>();
static_assert(
std::is_same<typename std::tuple_element<
index, typename NamedTupleType::Fields>::type::Type,
std::is_same<typename nth_tuple_element_t<
index, typename NamedTupleType::Fields>::Type,
typename Field::Type>(),
"If two fields have the same name, "
"their type must be the same as "
@@ -69,8 +70,8 @@ struct Getter {
constexpr auto index =
find_index<Field::name_, typename NamedTupleType::Fields>();
static_assert(
std::is_same<typename std::tuple_element<
index, typename NamedTupleType::Fields>::type::Type,
std::is_same<typename nth_tuple_element_t<
index, typename NamedTupleType::Fields>::Type,
typename Field::Type>(),
"If two fields have the same name, "
"their type must be the same as "
@@ -81,76 +82,6 @@ struct Getter {
// ----------------------------------------------------------------------------
/// For handling std::variant.
template <class... NamedTupleTypes>
struct Getter<std::variant<NamedTupleTypes...>> {
public:
/// Retrieves the indicated value from the tuple.
template <int _index>
static inline auto& get(std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](auto& _t) -> auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_t)>;
return Getter<NamedTupleType>::template get<_index>(_t);
};
return std::visit(apply, _tup);
}
/// Gets a field by name.
template <StringLiteral _field_name>
static inline auto& get(std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](auto& _t) -> auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_t)>;
return Getter<NamedTupleType>::template get<_field_name>(_t);
};
return std::visit(apply, _tup);
}
/// Gets a field by the field type.
template <class Field>
static inline auto& get(std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](auto& _t) -> auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_t)>;
return Getter<NamedTupleType>::template get<Field>(_t);
};
return std::visit(apply, _tup);
}
/// Retrieves the indicated value from the tuple.
template <int _index>
static inline const auto& get_const(
const std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](const auto& _tup) -> const auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_tup)>;
return Getter<NamedTupleType>::template get_const<_index>(_tup);
};
return std::visit(apply, _tup);
}
/// Gets a field by name.
template <StringLiteral _field_name>
static inline const auto& get_const(
const std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](const auto& _t) -> const auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_t)>;
return Getter<NamedTupleType>::template get_const<_field_name>(_t);
};
return std::visit(apply, _tup);
}
/// Gets a field by the field type.
template <class Field>
static inline const auto& get_const(
const std::variant<NamedTupleTypes...>& _tup) {
const auto apply = [](const auto& _t) -> const auto& {
using NamedTupleType = std::remove_cvref_t<decltype(_t)>;
return Getter<NamedTupleType>::template get_const<Field>(_t);
};
return std::visit(apply, _tup);
}
};
// ----------------------------------------------------------------------------
} // namespace rfl::internal
#endif
+7 -6
View File
@@ -6,18 +6,19 @@
#include <utility>
#include "is_field.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
template <class TupleType, int _i = 0>
constexpr bool all_fields() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return true;
} else {
using T = std::tuple_element_t<_i, TupleType>;
return is_field_v<T> && all_fields<TupleType, _i + 1>();
}
if constexpr (_i == std::tuple_size_v<TupleType>) {
return true;
} else {
using T = nth_tuple_element_t<_i, TupleType>;
return is_field_v<T> && all_fields<TupleType, _i + 1>();
}
}
} // namespace internal
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_INTERNAL_ELEMENT_INDEX_HPP_
#define RFL_INTERNAL_ELEMENT_INDEX_HPP_
#include <type_traits>
namespace rfl::internal {
template <int _i, class T>
consteval int find_element_index() {
return -1;
}
template <int _i, class T, class Head, class... Tail>
consteval int find_element_index() {
if constexpr (std::is_same_v<T, Head>) {
return _i;
} else {
return find_element_index<_i + 1, T, Tail...>();
}
}
template <class T, class... AlternativeTypes>
consteval int element_index() {
return find_element_index<0, T, AlternativeTypes...>();
}
} // namespace rfl::internal
#endif
+17 -14
View File
@@ -7,9 +7,10 @@
#include "../NamedTuple.hpp"
#include "../TaggedUnion.hpp"
#include "../named_tuple_t.hpp"
#include "StringLiteral.hpp"
#include "find_index.hpp"
#include "../named_tuple_t.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -24,13 +25,14 @@ struct FieldType;
/// Default option - for named tuples.
template <StringLiteral _field_name, class T>
struct FieldType {
using NamedTupleType = named_tuple_t<T>;
using NamedTupleType = named_tuple_t<T>;
static constexpr int field_ix_ =
internal::find_index<_field_name, typename NamedTupleType::Fields>();
static constexpr int field_ix_ =
internal::find_index<_field_name, typename NamedTupleType::Fields>();
using Type = typename std::tuple_element<
field_ix_, typename NamedTupleType::Fields>::type::Type;
using Type =
typename nth_tuple_element_t<field_ix_,
typename NamedTupleType::Fields>::Type;
};
/// For variants - in this case the FieldType returned by all options must be
@@ -39,22 +41,23 @@ template <StringLiteral _field_name, class FirstAlternativeType,
class... OtherAlternativeTypes>
struct FieldType<_field_name,
std::variant<FirstAlternativeType, OtherAlternativeTypes...>> {
constexpr static bool all_types_match = std::conjunction_v<std::is_same<
typename FieldType<_field_name, FirstAlternativeType>::Type,
typename FieldType<_field_name, OtherAlternativeTypes>::Type>...>;
constexpr static bool all_types_match = std::conjunction_v<std::is_same<
typename FieldType<_field_name, FirstAlternativeType>::Type,
typename FieldType<_field_name, OtherAlternativeTypes>::Type>...>;
static_assert(all_types_match, "All field types must be the same.");
static_assert(all_types_match, "All field types must be the same.");
using Type = typename FieldType<_field_name, FirstAlternativeType>::Type;
using Type = typename FieldType<_field_name, FirstAlternativeType>::Type;
};
/// For tagged union - just defers to the variant.
template <StringLiteral _field_name, StringLiteral _discriminator_name,
class... VarTypes>
struct FieldType<_field_name, TaggedUnion<_discriminator_name, VarTypes...>> {
using Type = typename FieldType<
_field_name, typename TaggedUnion<_discriminator_name,
VarTypes...>::VariantType>::Type;
using Type =
typename FieldType<_field_name,
typename TaggedUnion<_discriminator_name,
VarTypes...>::VariantType>::Type;
};
} // namespace internal
+2 -3
View File
@@ -1,10 +1,10 @@
#ifndef RFL_FIND_INDEX_HPP_
#define RFL_FIND_INDEX_HPP_
#include <tuple>
#include <type_traits>
#include "StringLiteral.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -12,8 +12,7 @@ namespace internal {
/// Finds the index of the field signified by _field_name
template <StringLiteral _field_name, class Fields, int I = 0>
constexpr static int find_index() {
using FieldType =
std::remove_cvref_t<typename std::tuple_element<I, Fields>::type>;
using FieldType = std::remove_cvref_t<nth_tuple_element_t<I, Fields>>;
constexpr bool name_i_matches = (FieldType::name_ == _field_name);
+17 -8
View File
@@ -95,19 +95,28 @@ auto get_field_name() {
}
}
// We don't want the operator+ to apply to normal literals,
// so we introduce this wrapper.
template <StringLiteral... _names>
struct LiteralWrapper {
Literal<_names...> literal_;
};
template <StringLiteral... _names>
auto wrap_literal(const Literal<_names...>& _literal) {
return LiteralWrapper<_names...>{_literal};
}
template <StringLiteral... _names1, StringLiteral... _names2>
auto concat_two_literals(const rfl::Literal<_names1...>&,
const rfl::Literal<_names2...>&) {
return rfl::Literal<_names1..., _names2...>::template from_value<0>();
auto operator+(const LiteralWrapper<_names1...>&,
const LiteralWrapper<_names2...>&) {
return LiteralWrapper<_names1..., _names2...>{
rfl::Literal<_names1..., _names2...>::template from_value<0>()};
}
template <class Head, class... Tail>
auto concat_literals(const Head& _head, const Tail&... _tail) {
if constexpr (sizeof...(_tail) == 0) {
return _head;
} else {
return concat_two_literals(_head, concat_literals(_tail...));
}
return (wrap_literal(_head) + ... + wrap_literal(_tail)).literal_;
}
inline auto concat_literals() { return rfl::Literal<>(); }
+2 -1
View File
@@ -7,6 +7,7 @@
#include "../MetaField.hpp"
#include "../type_name_t.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -17,7 +18,7 @@ auto get_meta_fields(AlreadyExtracted&&... _already_extracted) {
if constexpr (NamedTupleType::size() == i) {
return std::array<MetaField, i>{std::move(_already_extracted)...};
} else {
using FieldType = std::tuple_element_t<i, typename NamedTupleType::Fields>;
using FieldType = nth_tuple_element_t<i, typename NamedTupleType::Fields>;
auto name = typename FieldType::Name().str();
auto type = type_name_t<typename FieldType::Type>().str();
return get_meta_fields<NamedTupleType>(
+3 -2
View File
@@ -8,6 +8,7 @@
#include "all_fields.hpp"
#include "is_field.hpp"
#include "is_flatten_field.hpp"
#include "nth_tuple_element_t.hpp"
#include "ptr_tuple_t.hpp"
namespace rfl {
@@ -18,7 +19,7 @@ constexpr bool all_fields_or_flatten() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return true;
} else {
using T = std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
using T = std::remove_cvref_t<nth_tuple_element_t<_i, TupleType>>;
if constexpr (is_flatten_field_v<T>) {
return all_fields_or_flatten<
ptr_tuple_t<typename std::remove_pointer_t<T>::Type>>() &&
@@ -34,7 +35,7 @@ constexpr bool some_fields_or_flatten() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return false;
} else {
using T = std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
using T = std::remove_cvref_t<nth_tuple_element_t<_i, TupleType>>;
if constexpr (is_flatten_field_v<T>) {
return some_fields_or_flatten<
ptr_tuple_t<typename std::remove_pointer_t<T>::Type>>() ||
+2 -1
View File
@@ -6,6 +6,7 @@
#include <utility>
#include "is_flatten_field.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -15,7 +16,7 @@ constexpr bool has_flatten_fields() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return false;
} else {
using T = std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
using T = std::remove_cvref_t<nth_tuple_element_t<_i, TupleType>>;
return is_flatten_field_v<T> || has_flatten_fields<TupleType, _i + 1>();
}
}
@@ -5,6 +5,7 @@
#include "is_flatten_field.hpp"
#include "move_to_field_tuple.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -15,7 +16,7 @@ auto move_and_flatten_field_tuple(FieldTuple&& _t, Args&&... _args) {
if constexpr (i == std::tuple_size_v<std::remove_cvref_t<FieldTuple>>) {
return std::tuple_cat(std::move(_args)...);
} else {
using T = std::tuple_element_t<i, std::remove_cvref_t<FieldTuple>>;
using T = nth_tuple_element_t<i, std::remove_cvref_t<FieldTuple>>;
if constexpr (is_flatten_field<T>::value) {
return move_and_flatten_field_tuple(
std::move(_t), std::move(_args)...,
@@ -4,11 +4,12 @@
#include <functional>
#include <type_traits>
#include "../named_tuple_t.hpp"
#include "is_field.hpp"
#include "is_named_tuple.hpp"
#include "nt_to_ptr_named_tuple.hpp"
#include "nth_tuple_element_t.hpp"
#include "ptr_field_tuple_t.hpp"
#include "../named_tuple_t.hpp"
namespace rfl {
namespace internal {
@@ -24,7 +25,7 @@ auto make_ptr_fields(PtrNamedTupleType& _n, Args... _args) {
return std::make_tuple(_args...);
} else {
using Field =
std::remove_cvref_t<std::tuple_element_t<i, PtrFieldTupleType>>;
std::remove_cvref_t<nth_tuple_element_t<i, PtrFieldTupleType>>;
using T = std::remove_cvref_t<std::remove_pointer_t<typename Field::Type>>;
if constexpr (is_named_tuple_v<T>) {
@@ -54,7 +55,7 @@ auto move_from_ptr_fields(Pointers& _ptrs, Args&&... _args) {
if constexpr (i == std::tuple_size_v<std::remove_cvref_t<Pointers>>) {
return T{std::move(_args)...};
} else {
using FieldType = std::tuple_element_t<i, std::remove_cvref_t<Pointers>>;
using FieldType = nth_tuple_element_t<i, std::remove_cvref_t<Pointers>>;
if constexpr (is_field_v<FieldType>) {
return move_from_ptr_fields<T>(
@@ -66,7 +67,7 @@ auto move_from_ptr_fields(Pointers& _ptrs, Args&&... _args) {
using PtrFieldTupleType = std::remove_cvref_t<ptr_field_tuple_t<T>>;
using U = std::remove_cvref_t<std::remove_pointer_t<
typename std::tuple_element_t<i, PtrFieldTupleType>::Type>>;
typename nth_tuple_element_t<i, PtrFieldTupleType>::Type>>;
return move_from_ptr_fields<T>(
_ptrs, std::move(_args)...,
+4 -4
View File
@@ -19,7 +19,7 @@ constexpr int calc_flattened_size() {
if constexpr (_i == std::tuple_size_v<Tuple>) {
return 0;
} else {
using T = std::remove_pointer_t<std::tuple_element_t<_i, Tuple>>;
using T = std::remove_pointer_t<nth_tuple_element_t<_i, Tuple>>;
if constexpr (is_flatten_field_v<T>) {
return calc_flattened_size<ptr_tuple_t<typename T::Type>>() +
calc_flattened_size<Tuple, _i + 1>();
@@ -39,7 +39,7 @@ auto unflatten_ptr_tuple(PtrTupleType& _t, Args... _args) {
return std::make_tuple(_args...);
} else {
using T = std::remove_cvref_t<
std::remove_pointer_t<std::tuple_element_t<i, TargetTupleType>>>;
std::remove_pointer_t<nth_tuple_element_t<i, TargetTupleType>>>;
if constexpr (is_flatten_field_v<T>) {
using SubTargetTupleType =
@@ -65,7 +65,7 @@ auto move_from_pointers(Pointers& _ptrs, Args&&... _args) {
if constexpr (i == std::tuple_size_v<std::remove_cvref_t<Pointers>>) {
return std::remove_cvref_t<T>{std::move(_args)...};
} else {
using FieldType = std::tuple_element_t<i, std::remove_cvref_t<Pointers>>;
using FieldType = nth_tuple_element_t<i, std::remove_cvref_t<Pointers>>;
if constexpr (std::is_pointer_v<FieldType>) {
return move_from_pointers<T>(_ptrs, std::move(_args)...,
@@ -75,7 +75,7 @@ auto move_from_pointers(Pointers& _ptrs, Args&&... _args) {
using PtrTupleType = ptr_tuple_t<std::remove_cvref_t<T>>;
using U = std::remove_cvref_t<typename std::remove_pointer_t<
typename std::tuple_element_t<i, PtrTupleType>>::Type>;
nth_tuple_element_t<i, PtrTupleType>>::Type>;
return move_from_pointers<T>(_ptrs, std::move(_args)...,
move_from_pointers<U>(std::get<i>(_ptrs)));
@@ -3,6 +3,8 @@
#include <tuple>
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -11,10 +13,8 @@ namespace no_duplicate_field_names_helpers {
template <class Fields, int _i, int _j>
constexpr inline void compare_two_fields() {
if constexpr (_j < _i) {
using FieldType1 =
std::remove_cvref_t<typename std::tuple_element<_i, Fields>::type>;
using FieldType2 =
std::remove_cvref_t<typename std::tuple_element<_j, Fields>::type>;
using FieldType1 = std::remove_cvref_t<nth_tuple_element_t<_i, Fields>>;
using FieldType2 = std::remove_cvref_t<nth_tuple_element_t<_j, Fields>>;
constexpr auto field_name_i = FieldType1::name_;
constexpr auto field_name_j = FieldType2::name_;
@@ -5,6 +5,7 @@
#include "../Field.hpp"
#include "../make_named_tuple.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -21,7 +22,7 @@ auto nt_to_ptr_named_tuple(NamedTupleType& _nt, AlreadyExtracted... _a) {
if constexpr (i == num_fields) {
return make_named_tuple(_a...);
} else {
using FieldType = typename std::tuple_element<i, Fields>::type;
using FieldType = nth_tuple_element_t<i, Fields>;
using T = std::remove_cvref_t<typename FieldType::Type>;
return nt_to_ptr_named_tuple(
_nt, _a..., Field<FieldType::name_, T*>(&std::get<i>(_nt.values())));
@@ -40,7 +41,7 @@ auto nt_to_ptr_named_tuple(const NamedTupleType& _nt, AlreadyExtracted... _a) {
if constexpr (i == num_fields) {
return make_named_tuple(_a...);
} else {
using FieldType = typename std::tuple_element<i, Fields>::type;
using FieldType = nth_tuple_element_t<i, Fields>;
using T = std::remove_cvref_t<typename FieldType::Type>;
return nt_to_ptr_named_tuple(
_nt, _a...,
+73
View File
@@ -0,0 +1,73 @@
#ifndef RFL_INTERNAL_NTH_ELEMENT_T_HPP_
#define RFL_INTERNAL_NTH_ELEMENT_T_HPP_
#include <tuple>
namespace rfl::internal {
#if defined(__clang__)
template <int N, class... Ts>
using nth_element_t = __type_pack_element<N, Ts...>;
#else
template <int N, class... Ts>
struct NthElement;
template <int N, class Head, class... Tail>
struct NthElement<N, Head, Tail...> {
using Type = typename NthElement<N - 1, Tail...>::Type;
};
template <class T0, class... Ts>
struct NthElement<0, T0, Ts...> {
using Type = T0;
};
template <class T0, class T1, class... Ts>
struct NthElement<1, T0, T1, Ts...> {
using Type = T1;
};
template <class T0, class T1, class T2, class... Ts>
struct NthElement<2, T0, T1, T2, Ts...> {
using Type = T2;
};
template <class T0, class T1, class T2, class T3, class... Ts>
struct NthElement<3, T0, T1, T2, T3, Ts...> {
using Type = T3;
};
template <class T0, class T1, class T2, class T3, class T4, class... Ts>
struct NthElement<4, T0, T1, T2, T3, T4, Ts...> {
using Type = T4;
};
template <class T0, class T1, class T2, class T3, class T4, class T5,
class... Ts>
struct NthElement<5, T0, T1, T2, T3, T4, T5, Ts...> {
using Type = T5;
};
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6,
class... Ts>
struct NthElement<6, T0, T1, T2, T3, T4, T5, T6, Ts...> {
using Type = T6;
};
template <class T0, class T1, class T2, class T3, class T4, class T5, class T6,
class T7, class... Ts>
struct NthElement<7, T0, T1, T2, T3, T4, T5, T6, T7, Ts...> {
using Type = T7;
};
template <int N, class... Ts>
using nth_element_t = typename NthElement<N, Ts...>::Type;
#endif
} // namespace rfl::internal
#endif
@@ -0,0 +1,23 @@
#ifndef RFL_INTERNAL_NTH_TUPLE_ELEMENT_T_HPP_
#define RFL_INTERNAL_NTH_TUPLE_ELEMENT_T_HPP_
#include <tuple>
#include "nth_element_t.hpp"
namespace rfl::internal {
template <int N, class T>
struct nth_tuple_element;
template <int N, class... Ts>
struct nth_tuple_element<N, std::tuple<Ts...>> {
using Type = nth_element_t<N, Ts...>;
};
template <int N, class T>
using nth_tuple_element_t = typename nth_tuple_element<N, T>::Type;
} // namespace rfl::internal
#endif
+3 -2
View File
@@ -8,6 +8,7 @@
#include "../NamedTuple.hpp"
#include "../define_named_tuple.hpp"
#include "StringLiteral.hpp"
#include "nth_tuple_element_t.hpp"
namespace rfl {
namespace internal {
@@ -34,8 +35,8 @@ struct remove_single_field {
constexpr static int num_fields =
std::tuple_size_v<typename OldNamedTupleType::Fields>;
using FieldType = std::remove_cvref_t<typename std::tuple_element<
num_fields - _i, typename OldNamedTupleType::Fields>::type>;
using FieldType = std::remove_cvref_t<
nth_tuple_element_t<num_fields - _i, typename OldNamedTupleType::Fields>>;
using NewNamedTupleType =
std::conditional_t<_name == FieldType::name_, _NewNamedTupleType,
@@ -5,6 +5,7 @@
#include "has_flatten_fields.hpp"
#include "is_flatten_field.hpp"
#include "nth_tuple_element_t.hpp"
#include "to_ptr_tuple.hpp"
namespace rfl {
@@ -18,7 +19,7 @@ auto flatten_ptr_tuple(PtrTuple&& _t, Args... _args) {
} else if constexpr (i == std::tuple_size_v<std::remove_cvref_t<PtrTuple>>) {
return std::tuple_cat(std::forward<Args>(_args)...);
} else {
using T = std::tuple_element_t<i, std::remove_cvref_t<PtrTuple>>;
using T = nth_tuple_element_t<i, std::remove_cvref_t<PtrTuple>>;
if constexpr (is_flatten_field_v<T>) {
return flatten_ptr_tuple(
std::forward<PtrTuple>(_t), std::forward<Args>(_args)...,
+2 -1
View File
@@ -13,6 +13,7 @@
#include "is_empty.hpp"
#include "is_field.hpp"
#include "is_named_tuple.hpp"
#include "nth_tuple_element_t.hpp"
#include "to_flattened_ptr_tuple.hpp"
#include "to_ptr_field_tuple.hpp"
@@ -25,7 +26,7 @@ auto flatten_ptr_field_tuple(PtrFieldTuple& _t, Args&&... _args) {
if constexpr (i == std::tuple_size_v<std::remove_cvref_t<PtrFieldTuple>>) {
return std::tuple_cat(std::forward<Args>(_args)...);
} else {
using T = std::tuple_element_t<i, std::remove_cvref_t<PtrFieldTuple>>;
using T = nth_tuple_element_t<i, std::remove_cvref_t<PtrFieldTuple>>;
if constexpr (internal::is_flatten_field<T>::value) {
auto subtuple = internal::to_ptr_field_tuple(*std::get<i>(_t).get());
return flatten_ptr_field_tuple(_t, std::forward<Args>(_args)...,
@@ -0,0 +1,29 @@
#ifndef RFL_INTERNAL_VARIANT_FIND_MAX_SIZE_HPP_
#define RFL_INTERNAL_VARIANT_FIND_MAX_SIZE_HPP_
namespace rfl::internal::variant {
template <class T>
struct SizeWrapper {
using Type = T;
static constexpr unsigned long size_ = sizeof(T);
};
template <class T1, class T2>
consteval auto operator|(const SizeWrapper<T1>& _s1,
const SizeWrapper<T2>& _s2) {
if constexpr (sizeof(T2) > sizeof(T1)) {
return _s2;
} else {
return _s1;
}
}
template <class Head, class... Tail>
consteval auto find_max_size() {
return (SizeWrapper<Head>{} | ... | SizeWrapper<Tail>{});
}
} // namespace rfl::internal::variant
#endif
@@ -0,0 +1,19 @@
#ifndef RFL_INTERNAL_VARIANT_IS_ALTERNATIVE_TYPE_HPP_
#define RFL_INTERNAL_VARIANT_IS_ALTERNATIVE_TYPE_HPP_
#include <type_traits>
#include "../element_index.hpp"
namespace rfl::internal::variant {
template <class T, class... AlternativeTypes>
static constexpr bool is_alternative_type() {
return internal::element_index<std::remove_cvref_t<T>,
std::remove_cvref_t<AlternativeTypes>...>() !=
-1;
}
} // namespace rfl::internal::variant
#endif
+7 -7
View File
@@ -5,10 +5,10 @@
#include <memory>
#include <optional>
#include <string>
#include <variant>
#include "../../Literal.hpp"
#include "../../Rename.hpp"
#include "../../Variant.hpp"
namespace rfl::json::schema {
@@ -36,7 +36,7 @@ struct Type {
rfl::Rename<"maxLength", std::optional<size_t>> maxSize;
};
using NumericType = std::variant<Integer, Number>;
using NumericType = rfl::Variant<Integer, Number>;
struct AllOf {
std::optional<std::string> description;
@@ -50,13 +50,13 @@ struct Type {
struct ExclusiveMaximum {
std::optional<std::string> description;
std::variant<double, int> exclusiveMaximum;
rfl::Variant<double, int> exclusiveMaximum;
std::string type;
};
struct ExclusiveMinimum {
std::optional<std::string> description;
std::variant<double, int> exclusiveMinimum;
rfl::Variant<double, int> exclusiveMinimum;
std::string type;
};
@@ -70,13 +70,13 @@ struct Type {
struct Maximum {
std::optional<std::string> description;
std::variant<double, int> maximum;
rfl::Variant<double, int> maximum;
std::string type;
};
struct Minimum {
std::optional<std::string> description;
std::variant<double, int> minimum;
rfl::Variant<double, int> minimum;
std::string type;
};
@@ -137,7 +137,7 @@ struct Type {
};
using ReflectionType =
std::variant<AllOf, AnyOf, Boolean, ExclusiveMaximum, ExclusiveMinimum,
rfl::Variant<AllOf, AnyOf, Boolean, ExclusiveMaximum, ExclusiveMinimum,
FixedSizeTypedArray, Integer, Maximum, Minimum, Number, Null,
Object, OneOf, Reference, Regex, String, StringEnum,
StringMap, Tuple, TypedArray>;
+4 -4
View File
@@ -10,10 +10,10 @@
#include <map>
#include <string>
#include <type_traits>
#include <variant>
#include "../Literal.hpp"
#include "../Processors.hpp"
#include "../Variant.hpp"
#include "../parsing/schema/Type.hpp"
#include "../parsing/schema/ValidationType.hpp"
#include "../parsing/schema/make.hpp"
@@ -31,8 +31,8 @@ template <class T>
struct TypeHelper {};
template <class... Ts>
struct TypeHelper<std::variant<Ts...>> {
using JSONSchemaType = std::variant<schema::JSONSchema<Ts>...>;
struct TypeHelper<rfl::Variant<Ts...>> {
using JSONSchemaType = rfl::Variant<schema::JSONSchema<Ts>...>;
};
/// Returns the JSON schema for a class.
@@ -52,7 +52,7 @@ std::string to_schema(const yyjson_write_flag _flag = 0) {
.definitions = definitions};
};
auto root = type_to_json_schema_type(internal_schema.root_);
const auto json_schema = std::visit(to_schema, std::move(root.value));
const auto json_schema = rfl::visit(to_schema, std::move(root.value));
return write(json_schema, _flag);
}
} // namespace rfl::json
+8 -7
View File
@@ -5,10 +5,11 @@
#include <stdexcept>
#include <string>
#include <type_traits>
#include <variant>
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../always_false.hpp"
#include "../visit.hpp"
#include "FieldVariantReader.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
@@ -19,9 +20,9 @@ namespace parsing {
/// To be used when all options of the variants are rfl::Field. Essentially,
/// this is an externally tagged union.
template <class R, class W, class ProcessorsType, class... FieldTypes>
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
requires AreReaderAndWriter<R, W, rfl::Variant<FieldTypes...>>
struct FieldVariantParser {
using FieldVariantType = std::variant<FieldTypes...>;
using FieldVariantType = rfl::Variant<FieldTypes...>;
using ResultType = Result<FieldVariantType>;
public:
@@ -58,7 +59,7 @@ struct FieldVariantParser {
}
template <class P>
static void write(const W& _w, const std::variant<FieldTypes...>& _v,
static void write(const W& _w, const rfl::Variant<FieldTypes...>& _v,
const P& _parent) noexcept {
static_assert(
internal::no_duplicate_field_names<std::tuple<FieldTypes...>>(),
@@ -72,13 +73,13 @@ struct FieldVariantParser {
_parent);
};
std::visit(handle, _v);
rfl::visit(handle, _v);
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions,
[[maybe_unused]] std::vector<schema::Type> _types = {}) {
using VariantType = std::variant<NamedTuple<FieldTypes>...>;
std::vector<schema::Type> _types = {}) {
using VariantType = rfl::Variant<NamedTuple<FieldTypes>...>;
return Parser<R, W, VariantType, ProcessorsType>::to_schema(_definitions);
}
};
+38 -38
View File
@@ -5,11 +5,13 @@
#include <optional>
#include <string_view>
#include <type_traits>
#include <variant>
#include <utility>
#include <vector>
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../internal/is_array.hpp"
#include "../internal/nth_element_t.hpp"
namespace rfl::parsing {
@@ -17,7 +19,7 @@ template <class R, class W, class ProcessorsType, class... FieldTypes>
class FieldVariantReader {
private:
using InputVarType = typename R::InputVarType;
using FieldVariantType = std::variant<FieldTypes...>;
using FieldVariantType = rfl::Variant<FieldTypes...>;
using ResultType = Result<FieldVariantType>;
public:
@@ -27,50 +29,48 @@ class FieldVariantReader {
~FieldVariantReader() = default;
template <size_t _i = 0>
void read(const std::string_view& _disc_value,
const InputVarType& _var) const noexcept {
if constexpr (_i < sizeof...(FieldTypes)) {
if constexpr (_i == 0) {
if (*field_variant_) {
*field_variant_ = Error(
"Could not parse: Expected the object to have "
"exactly one field, but found more than one.");
return;
}
}
using FieldType = std::remove_cvref_t<
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type>;
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
constexpr auto key = FieldType::name_.string_view();
if (key == _disc_value) {
const auto to_variant = [](ValueType&& _val) {
return std::variant<FieldTypes...>(FieldType(std::move(_val)));
};
const auto embellish_error = [&](const Error& _e) {
return Error("Could not parse std::variant with field '" +
std::string(_disc_value) + "': " + _e.what());
};
*field_variant_ =
Parser<R, W, ValueType, ProcessorsType>::read(*r_, _var)
.transform(to_variant)
.or_else(embellish_error);
return;
} else {
read<_i + 1>(_disc_value, _var);
}
} else {
try_matching_fields(
_disc_value, _var,
std::make_integer_sequence<int, sizeof...(FieldTypes)>());
if (!*field_variant_) {
*field_variant_ = Error(
"Could not parse std::variant, could not match field named "
"Could not parse rfl::Variant, could not match field named "
"'" +
std::string(_disc_value) + "'.");
}
}
private:
template <int... _is>
void try_matching_fields(const std::string_view& _disc_value,
const InputVarType& _var,
std::integer_sequence<int, _is...>) const noexcept {
(try_one<_is>(_disc_value, _var), ...);
}
template <int _i>
void try_one(const std::string_view& _disc_value,
const InputVarType& _var) const noexcept {
using FieldType =
std::remove_cvref_t<internal::nth_element_t<_i, FieldTypes...>>;
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
constexpr auto key = FieldType::name_.string_view();
if (key == _disc_value) {
const auto to_variant = [](ValueType&& _val) {
return rfl::Variant<FieldTypes...>(FieldType(std::move(_val)));
};
const auto embellish_error = [&](const Error& _e) {
return Error("Could not parse rfl::Variant with field '" +
std::string(_disc_value) + "': " + _e.what());
};
*field_variant_ = Parser<R, W, ValueType, ProcessorsType>::read(*r_, _var)
.transform(to_variant)
.or_else(embellish_error);
}
}
private:
/// The underlying reader.
const R* r_;
+7 -9
View File
@@ -16,6 +16,7 @@
#include "../internal/is_basic_type.hpp"
#include "../internal/is_extra_fields.hpp"
#include "../internal/is_skip.hpp"
#include "../internal/nth_element_t.hpp"
#include "../internal/strings/replace_all.hpp"
#include "../to_view.hpp"
#include "AreReaderAndWriter.hpp"
@@ -129,8 +130,7 @@ struct NamedTupleParser {
static void add_field_to_object(const W& _w,
const NamedTuple<FieldTypes...>& _tup,
OutputObjectOrArrayType* _ptr) noexcept {
using FieldType =
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
using FieldType = internal::nth_element_t<_i, FieldTypes...>;
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
const auto value = rfl::get<_i>(_tup);
if constexpr (internal::is_extra_fields_v<ValueType>) {
@@ -167,8 +167,7 @@ struct NamedTupleParser {
static void add_field_to_schema(
std::map<std::string, schema::Type>* _definitions,
SchemaType* _schema) noexcept {
using F =
std::tuple_element_t<_i, typename NamedTuple<FieldTypes...>::Fields>;
using F = internal::nth_element_t<_i, FieldTypes...>;
using U = std::remove_cvref_t<typename F::Type>;
if constexpr (!internal::is_skip_v<U> && !internal::is_extra_fields_v<U>) {
auto s = Parser<R, W, U, ProcessorsType>::to_schema(_definitions);
@@ -194,9 +193,8 @@ struct NamedTupleParser {
(add_field_to_schema<_is>(_definitions, _schema), ...);
if constexpr (NamedTupleType::pos_extra_fields() != -1) {
using F =
std::tuple_element_t<NamedTupleType::pos_extra_fields(),
typename NamedTuple<FieldTypes...>::Fields>;
using F = internal::nth_element_t<NamedTupleType::pos_extra_fields(),
FieldTypes...>;
using ExtraFieldsType = std::remove_cvref_t<typename F::Type>;
using U = std::remove_cvref_t<typename ExtraFieldsType::Type>;
_schema->additional_properties_ = std::make_shared<schema::Type>(
@@ -210,7 +208,7 @@ struct NamedTupleParser {
const NamedTupleType& _view,
std::array<bool, size_>* _set,
std::vector<Error>* _errors) noexcept {
using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>;
using FieldType = internal::nth_element_t<_i, FieldTypes...>;
using ValueType = std::remove_reference_t<
std::remove_pointer_t<typename FieldType::Type>>;
@@ -220,7 +218,7 @@ struct NamedTupleParser {
(_all_required || is_required<ValueType, _ignore_empty_containers>());
if constexpr (is_required_field) {
constexpr auto current_name =
std::tuple_element_t<_i, typename NamedTupleType::Fields>::name();
internal::nth_element_t<_i, FieldTypes...>::name();
_errors->emplace_back(Error(
"Field named '" + std::string(current_name) + "' not found."));
} else {
+93 -21
View File
@@ -8,46 +8,118 @@
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../always_false.hpp"
#include "../internal/nth_element_t.hpp"
#include "FieldVariantParser.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
namespace rfl {
namespace parsing {
namespace rfl::parsing {
template <class R, class W, class... FieldTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, rfl::Variant<FieldTypes...>>
struct Parser<R, W, rfl::Variant<FieldTypes...>, ProcessorsType> {
template <class R, class W, class... AlternativeTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, rfl::Variant<AlternativeTypes...>>
class Parser<R, W, rfl::Variant<AlternativeTypes...>, ProcessorsType> {
public:
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<rfl::Variant<FieldTypes...>> read(
static Result<rfl::Variant<AlternativeTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
const auto to_rfl_variant = [](auto&& _var) {
return rfl::Variant<FieldTypes...>(
std::forward<std::variant<FieldTypes...>>(_var));
};
return Parser<R, W, std::variant<FieldTypes...>, ProcessorsType>::read(_r,
_var)
.transform(to_rfl_variant);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var);
} else {
std::optional<rfl::Variant<AlternativeTypes...>> result;
std::vector<Error> errors;
read_variant(
_r, _var, &result, &errors,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
if (result) {
return std::move(*result);
} else {
return Error(
to_single_error_message(errors,
"Could not parse the variant. Each of the "
"possible alternatives failed "
"for the following reasons: ",
100000));
}
}
}
template <class P>
static void write(const W& _w, const rfl::Variant<FieldTypes...>& _variant,
static void write(const W& _w,
const rfl::Variant<AlternativeTypes...>& _variant,
const P& _parent) noexcept {
Parser<R, W, std::variant<FieldTypes...>, ProcessorsType>::write(
_w, _variant.variant(), _parent);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
FieldVariantParser<R, W, ProcessorsType, AlternativeTypes...>::write(
_w, _variant, _parent);
} else {
const auto handle = [&](const auto& _v) {
using Type = std::remove_cvref_t<decltype(_v)>;
Parser<R, W, Type, ProcessorsType>::write(_w, _v, _parent);
};
return rfl::visit(handle, _variant);
}
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
return Parser<R, W, std::variant<FieldTypes...>, ProcessorsType>::to_schema(
_definitions);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::to_schema(_definitions);
} else {
std::vector<schema::Type> types;
build_schema(
_definitions, &types,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}};
}
}
private:
template <size_t _i>
static void add_to_schema(std::map<std::string, schema::Type>* _definitions,
std::vector<schema::Type>* _types) noexcept {
using AltType =
std::remove_cvref_t<internal::nth_element_t<_i, AlternativeTypes...>>;
_types->push_back(
Parser<R, W, AltType, ProcessorsType>::to_schema(_definitions));
}
template <int... _is>
static void build_schema(std::map<std::string, schema::Type>* _definitions,
std::vector<schema::Type>* _types,
std::integer_sequence<int, _is...>) noexcept {
(add_to_schema<_is>(_definitions, _types), ...);
}
template <int _i>
static void read_one_alternative(
const R& _r, const InputVarType& _var,
std::optional<rfl::Variant<AlternativeTypes...>>* _result,
std::vector<Error>* _errors) noexcept {
if (!*_result) {
using AltType =
std::remove_cvref_t<internal::nth_element_t<_i, AlternativeTypes...>>;
auto res = Parser<R, W, AltType, ProcessorsType>::read(_r, _var);
if (res) {
*_result = std::move(*res);
} else {
_errors->emplace_back(*res.error());
}
}
}
template <int... _is>
static void read_variant(
const R& _r, const InputVarType& _var,
std::optional<rfl::Variant<AlternativeTypes...>>* _result,
std::vector<Error>* _errors,
std::integer_sequence<int, _is...>) noexcept {
(read_one_alternative<_is>(_r, _var, _result, _errors), ...);
}
};
} // namespace parsing
} // namespace rfl
} // namespace rfl::parsing
#endif
+1 -1
View File
@@ -67,7 +67,7 @@ struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
const auto handle = [&](const auto& _val) {
write_wrapped(_w, _val, _parent);
};
std::visit(handle, _tagged_union.variant_);
rfl::visit(handle, _tagged_union.variant_);
}
static schema::Type to_schema(
+62 -29
View File
@@ -8,7 +8,9 @@
#include "../Ref.hpp"
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../always_false.hpp"
#include "../internal/to_ptr_field.hpp"
#include "FieldVariantParser.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
@@ -17,22 +19,35 @@
namespace rfl {
namespace parsing {
template <class R, class W, class... FieldTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
class Parser<R, W, std::variant<FieldTypes...>, ProcessorsType> {
template <class R, class W, class... AlternativeTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::variant<AlternativeTypes...>>
class Parser<R, W, std::variant<AlternativeTypes...>, ProcessorsType> {
template <class T>
using ptr_field_t =
decltype(internal::to_ptr_field(std::declval<const T&>()));
public:
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<std::variant<FieldTypes...>> read(
static Result<std::variant<AlternativeTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
if constexpr (internal::all_fields<std::tuple<FieldTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType, FieldTypes...>::read(
_r, _var);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
const auto wrap = [](auto&& _v) {
return std::variant<AlternativeTypes...>(std::move(_v));
};
const auto to_std_variant = [&](auto&& _v) {
return rfl::visit(wrap, std::move(_v));
};
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var)
.transform(to_std_variant);
} else {
std::optional<std::variant<FieldTypes...>> result;
std::optional<std::variant<AlternativeTypes...>> result;
std::vector<Error> errors;
read_variant(_r, _var, &result, &errors);
read_variant(
_r, _var, &result, &errors,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
if (result) {
return std::move(*result);
} else {
@@ -47,11 +62,21 @@ class Parser<R, W, std::variant<FieldTypes...>, ProcessorsType> {
}
template <class P>
static void write(const W& _w, const std::variant<FieldTypes...>& _variant,
static void write(const W& _w,
const std::variant<AlternativeTypes...>& _variant,
const P& _parent) noexcept {
if constexpr (internal::all_fields<std::tuple<FieldTypes...>>()) {
FieldVariantParser<R, W, ProcessorsType, FieldTypes...>::write(
_w, _variant, _parent);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
const auto wrap = [](const auto& _v) {
return rfl::Variant<ptr_field_t<AlternativeTypes>...>(
internal::to_ptr_field(_v));
};
const auto to_rfl_variant = [&](const auto& _v) {
return std::visit(wrap, _v);
};
FieldVariantParser<
R, W, ProcessorsType,
ptr_field_t<AlternativeTypes>...>::write(_w, to_rfl_variant(_variant),
_parent);
} else {
const auto handle = [&](const auto& _v) {
using Type = std::remove_cvref_t<decltype(_v)>;
@@ -63,13 +88,14 @@ class Parser<R, W, std::variant<FieldTypes...>, ProcessorsType> {
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
if constexpr (internal::all_fields<std::tuple<FieldTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType, FieldTypes...>::to_schema(
_definitions);
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::to_schema(_definitions);
} else {
std::vector<schema::Type> types;
build_schema(_definitions, &types,
std::make_integer_sequence<int, sizeof...(FieldTypes)>());
build_schema(
_definitions, &types,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}};
}
}
@@ -79,7 +105,7 @@ class Parser<R, W, std::variant<FieldTypes...>, ProcessorsType> {
static void add_to_schema(std::map<std::string, schema::Type>* _definitions,
std::vector<schema::Type>* _types) noexcept {
using U = std::remove_cvref_t<
std::variant_alternative_t<_i, std::variant<FieldTypes...>>>;
std::variant_alternative_t<_i, std::variant<AlternativeTypes...>>>;
_types->push_back(Parser<R, W, U, ProcessorsType>::to_schema(_definitions));
}
@@ -90,24 +116,31 @@ class Parser<R, W, std::variant<FieldTypes...>, ProcessorsType> {
(add_to_schema<_is>(_definitions, _types), ...);
}
template <int _i = 0>
static void read_variant(const R& _r, const InputVarType& _var,
std::optional<std::variant<FieldTypes...>>* _result,
std::vector<Error>* _errors) noexcept {
constexpr size_t size = sizeof...(FieldTypes);
if constexpr (_i < size) {
using AltType = std::remove_cvref_t<
std::variant_alternative_t<_i, std::variant<FieldTypes...>>>;
template <int _i>
static void read_one_alternative(
const R& _r, const InputVarType& _var,
std::optional<std::variant<AlternativeTypes...>>* _result,
std::vector<Error>* _errors) noexcept {
if (!*_result) {
using AltType =
std::remove_cvref_t<internal::nth_element_t<_i, AlternativeTypes...>>;
auto res = Parser<R, W, AltType, ProcessorsType>::read(_r, _var);
if (res) {
*_result = std::move(*res);
return;
} else {
_errors->emplace_back(*res.error());
return read_variant<_i + 1>(_r, _var, _result, _errors);
}
}
}
template <int... _is>
static void read_variant(
const R& _r, const InputVarType& _var,
std::optional<std::variant<AlternativeTypes...>>* _result,
std::vector<Error>* _errors,
std::integer_sequence<int, _is...>) noexcept {
(read_one_alternative<_is>(_r, _var, _result, _errors), ...);
}
};
} // namespace parsing
+3 -2
View File
@@ -7,6 +7,7 @@
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/nth_element_t.hpp"
#include "Parent.hpp"
#include "TupleReader.hpp"
#include "schema/Type.hpp"
@@ -87,8 +88,8 @@ struct TupleParser {
static void to_array(const W& _w, const std::tuple<Ts...>& _tup,
const P& _parent) noexcept {
if constexpr (_i < sizeof...(Ts)) {
using NewFieldType = std::remove_cvref_t<
typename std::tuple_element_t<_i, std::tuple<Ts...>>>;
using NewFieldType =
std::remove_cvref_t<internal::nth_element_t<_i, Ts...>>;
Parser<R, W, NewFieldType, ProcessorsType>::write(_w, std::get<_i>(_tup),
_parent);
to_array<_i + 1>(_w, _tup, _parent);
+4 -3
View File
@@ -8,6 +8,7 @@
#include "../Result.hpp"
#include "../internal/is_array.hpp"
#include "../internal/nth_tuple_element_t.hpp"
namespace rfl::parsing {
@@ -46,7 +47,7 @@ class TupleReader {
return;
}
using CurrentType =
std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
std::remove_cvref_t<internal::nth_tuple_element_t<_i, TupleType>>;
if constexpr (!std::is_array_v<CurrentType> &&
std::is_pointer_v<CurrentType> &&
std::is_destructible_v<CurrentType>) {
@@ -65,7 +66,7 @@ class TupleReader {
if constexpr (_i < size_) {
if (i_ == _i) {
using CurrentType =
std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
std::remove_cvref_t<internal::nth_tuple_element_t<_i, TupleType>>;
if constexpr (_all_required ||
is_required<CurrentType, _ignore_empty_containers>()) {
@@ -86,7 +87,7 @@ class TupleReader {
if constexpr (_i < size_) {
if (i_ == _i) {
using CurrentType =
std::remove_cvref_t<std::tuple_element_t<_i, TupleType>>;
std::remove_cvref_t<internal::nth_tuple_element_t<_i, TupleType>>;
auto res = Parser<R, W, CurrentType, ProcessorsType>::read(*r_, _var);
+5 -2
View File
@@ -9,6 +9,7 @@
#include "../Result.hpp"
#include "../internal/is_array.hpp"
#include "../internal/nth_tuple_element_t.hpp"
namespace rfl::parsing {
@@ -48,7 +49,8 @@ class ViewReader {
const auto& _var, auto* _view,
auto* _errors, auto* _found, auto* _set,
bool* _already_assigned) {
using FieldType = std::tuple_element_t<i, typename ViewType::Fields>;
using FieldType =
internal::nth_tuple_element_t<i, typename ViewType::Fields>;
using OriginalType = typename FieldType::Type;
using T =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
@@ -132,7 +134,8 @@ class ViewReader {
template <int _i>
void call_destructor_on_one_if_necessary() const {
using FieldType = std::tuple_element_t<_i, typename ViewType::Fields>;
using FieldType =
internal::nth_tuple_element_t<_i, typename ViewType::Fields>;
using OriginalType = std::remove_cvref_t<typename FieldType::Type>;
using ValueType =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
@@ -9,6 +9,7 @@
#include "../Result.hpp"
#include "../internal/is_array.hpp"
#include "../internal/nth_tuple_element_t.hpp"
namespace rfl::parsing {
@@ -59,7 +60,8 @@ class ViewReaderWithStrippedFieldNames {
static void assign_if_field_is_field_i(const R& _r, const auto& _var,
auto* _view, auto* _errors,
auto* _found, auto* _set, int _i) {
using FieldType = std::tuple_element_t<i, typename ViewType::Fields>;
using FieldType =
internal::nth_tuple_element_t<i, typename ViewType::Fields>;
using OriginalType = typename FieldType::Type;
using T =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
@@ -105,7 +107,8 @@ class ViewReaderWithStrippedFieldNames {
// TODO: Unnecessary code duplication.
template <int _i>
void call_destructor_on_one_if_necessary() const {
using FieldType = std::tuple_element_t<_i, typename ViewType::Fields>;
using FieldType =
internal::nth_tuple_element_t<_i, typename ViewType::Fields>;
using OriginalType = std::remove_cvref_t<typename FieldType::Type>;
using ValueType =
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
+2 -2
View File
@@ -5,10 +5,10 @@
#include <map>
#include <memory>
#include <string>
#include <variant>
#include <vector>
#include "../../Ref.hpp"
#include "../../Variant.hpp"
#include "ValidationType.hpp"
namespace rfl::parsing::schema {
@@ -86,7 +86,7 @@ struct Type {
};
using VariantType =
std::variant<Boolean, Int32, Int64, UInt32, UInt64, Integer, Float,
rfl::Variant<Boolean, Int32, Int64, UInt32, UInt64, Integer, Float,
Double, String, AnyOf, Description, FixedSizeTypedArray,
Literal, Object, Optional, Reference, StringMap, Tuple,
TypedArray, Validated>;
@@ -4,10 +4,10 @@
#include <cstddef>
#include <map>
#include <string>
#include <variant>
#include <vector>
#include "../../Ref.hpp"
#include "../../Variant.hpp"
namespace rfl::parsing::schema {
@@ -21,27 +21,27 @@ struct ValidationType {
};
struct EqualTo {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct ExclusiveMaximum {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct ExclusiveMinimum {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct Maximum {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct Minimum {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct NotEqualTo {
std::variant<double, int> value_;
rfl::Variant<double, int> value_;
};
struct OneOf {
@@ -57,7 +57,7 @@ struct ValidationType {
};
using VariantType =
std::variant<AllOf, AnyOf, EqualTo, ExclusiveMaximum, ExclusiveMinimum,
rfl::Variant<AllOf, AnyOf, EqualTo, ExclusiveMaximum, ExclusiveMinimum,
Maximum, Minimum, OneOf, NotEqualTo, Regex, Size>;
/// A type can be determined to be any of the above.
+84 -10
View File
@@ -11,22 +11,96 @@
namespace rfl {
/// Implements the visitor pattern for Literals.
template <class Visitor, internal::StringLiteral... _fields, class... Args>
inline auto visit(const Visitor& _visitor, const Literal<_fields...> _literal,
const Args&... _args) {
constexpr int size = sizeof...(_fields);
using WrapperType = internal::VisitorWrapper<Visitor, _fields...>;
const auto wrapper = WrapperType{&_visitor};
return internal::VisitTree::visit<0, size, WrapperType>(
wrapper, _literal.value(), _args...);
constexpr int size = sizeof...(_fields);
using WrapperType = internal::VisitorWrapper<Visitor, _fields...>;
const auto wrapper = WrapperType{&_visitor};
return internal::VisitTree::visit<0, size, WrapperType>(
wrapper, _literal.value(), _args...);
}
/// Implements the visitor pattern for TaggedUnions.
template <class Visitor, internal::StringLiteral _discriminator, class... Args>
inline auto visit(const Visitor& _visitor,
template <class F, class... AlternativeTypes>
inline auto visit(F& _f, Variant<AlternativeTypes...>& _v) {
return _v.visit(_f);
}
template <class F, class... AlternativeTypes>
inline auto visit(F& _f, Variant<AlternativeTypes...>&& _v) {
return _v.visit(_f);
}
template <class F, class... AlternativeTypes>
inline auto visit(F& _f, const Variant<AlternativeTypes...>& _v) {
return _v.visit(_f);
}
template <class F, class... AlternativeTypes>
inline auto visit(const F& _f, Variant<AlternativeTypes...>& _v) {
return _v.visit(_f);
}
template <class F, class... AlternativeTypes>
inline auto visit(const F& _f, Variant<AlternativeTypes...>&& _v) {
return _v.visit(_f);
}
template <class F, class... AlternativeTypes>
inline auto visit(const F& _f, const Variant<AlternativeTypes...>& _v) {
return _v.visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(F& _f, TaggedUnion<_discriminator, Args...>& _tagged_union) {
return _tagged_union.variant().visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(F& _f, TaggedUnion<_discriminator, Args...>&& _tagged_union) {
return _tagged_union.variant().visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(F& _f,
const TaggedUnion<_discriminator, Args...>& _tagged_union) {
return std::visit(_visitor, _tagged_union.variant());
return _tagged_union.variant().visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(const F& _f,
TaggedUnion<_discriminator, Args...>& _tagged_union) {
return _tagged_union.variant().visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(const F& _f,
TaggedUnion<_discriminator, Args...>&& _tagged_union) {
return _tagged_union.variant().visit(_f);
}
template <class F, internal::StringLiteral _discriminator, class... Args>
inline auto visit(const F& _f,
const TaggedUnion<_discriminator, Args...>& _tagged_union) {
return _tagged_union.variant().visit(_f);
}
template <class F, class Head, class... Tail>
inline auto visit(F& _f, Head& _head, Tail&... _tail) {
const auto f_outer = [&](auto& _h) {
const auto f_inner = [&](auto&... _t) { return _f(_h, _t...); };
return visit(f_inner, _tail...);
};
return _head.visit(f_outer);
}
template <class F, class Head, class... Tail>
inline auto visit(const F& _f, Head& _head, Tail&... _tail) {
const auto f_outer = [&](auto& _h) {
const auto f_inner = [&](auto&... _t) { return _f(_h, _t...); };
return visit(f_inner, _tail...);
};
return _head.visit(f_outer);
}
} // namespace rfl
+17 -13
View File
@@ -128,7 +128,7 @@ bool is_optional(const parsing::schema::Type& _t) {
using T = std::remove_cvref_t<decltype(_v)>;
return std::is_same<T, parsing::schema::Type::Optional>();
};
return std::visit(handle, _t.variant_);
return rfl::visit(handle, _t.variant_);
}
std::string numeric_type_to_string(const parsing::schema::Type& _type) {
@@ -145,13 +145,13 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) {
return schema::Type::Number{}.type.str();
}
};
return std::visit(handle_variant, _type.variant_);
return rfl::visit(handle_variant, _type.variant_);
}
schema::Type handle_validation_type(
const parsing::schema::Type& _type,
const parsing::schema::ValidationType& _validation_type) {
const auto handle_variant = [&](const auto& _v) -> schema::Type {
auto handle_variant = [&](const auto& _v) -> schema::Type {
using T = std::remove_cvref_t<decltype(_v)>;
using ValidationType = parsing::schema::ValidationType;
if constexpr (std::is_same<T, ValidationType::AllOf>()) {
@@ -180,22 +180,25 @@ schema::Type handle_validation_type(
} else if constexpr (std::is_same<T, ValidationType::Size>()) {
auto t = type_to_json_schema_type(_type);
const auto to_size = [](const auto _v) {
return static_cast<size_t>(_v);
};
auto handle_size_variant = [&](auto& _t, const auto& _size_limit) {
using U = std::remove_cvref_t<decltype(_t)>;
using V = std::remove_cvref_t<decltype(_size_limit)>;
if constexpr (std::is_same<U, schema::Type::TypedArray>() ||
std::is_same<U, schema::Type::String>()) {
if constexpr (std::is_same<V, ValidationType::Minimum>()) {
_t.minSize = std::get<int>(_size_limit.value_);
_t.minSize = _size_limit.value_.visit(to_size);
return t;
} else if constexpr (std::is_same<V, ValidationType::Maximum>()) {
_t.maxSize = std::get<int>(_size_limit.value_);
_t.maxSize = _size_limit.value_.visit(to_size);
return t;
} else if constexpr (std::is_same<V, ValidationType::EqualTo>()) {
_t.minSize = std::get<int>(_size_limit.value_);
_t.maxSize = std::get<int>(_size_limit.value_);
_t.minSize = _size_limit.value_.visit(to_size);
_t.maxSize = _size_limit.value_.visit(to_size);
return t;
} else if constexpr (std::is_same<V, ValidationType::AnyOf>() ||
@@ -210,7 +213,8 @@ schema::Type handle_validation_type(
}
return t;
};
return std::visit(handle_size_variant, t.value, _v.size_limit_->variant_);
return rfl::visit(handle_size_variant, t.value, _v.size_limit_->variant_);
} else if constexpr (std::is_same<T, ValidationType::ExclusiveMaximum>()) {
return schema::Type{.value = schema::Type::ExclusiveMaximum{
@@ -259,11 +263,11 @@ schema::Type handle_validation_type(
}
};
return std::visit(handle_variant, _validation_type.variant_);
return rfl::visit(handle_variant, _validation_type.variant_);
}
schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
const auto handle_variant = [](const auto& _t) -> schema::Type {
auto handle_variant = [](const auto& _t) -> schema::Type {
using T = std::remove_cvref_t<decltype(_t)>;
using Type = parsing::schema::Type;
if constexpr (std::is_same<T, Type::Boolean>()) {
@@ -296,7 +300,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
_v.description = _t.description_;
return schema::Type{_v};
};
return std::visit(update_prediction, res.value);
return rfl::visit(update_prediction, res.value);
} else if constexpr (std::is_same<T, Type::FixedSizeTypedArray>()) {
return schema::Type{.value = schema::Type::FixedSizeTypedArray{
@@ -362,7 +366,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
}
};
return std::visit(handle_variant, _type.variant_);
return rfl::visit(handle_variant, _type.variant_);
}
} // namespace rfl::json
+35
View File
@@ -0,0 +1,35 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_field_variant_std {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = std::variant<rfl::Field<"circle", Circle>,
rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", rfl::Box<Square>>>;
TEST(json, test_field_variant_std) {
const Shapes r =
rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5});
write_and_read(r, R"({"rectangle":{"height":10.0,"width":5.0}})");
}
} // namespace test_field_variant_std
+32
View File
@@ -0,0 +1,32 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant) {
const Shapes r = Rectangle{.height = 10, .width = 5};
write_and_read(r, R"({"height":10.0,"width":5.0})");
}
} // namespace test_rfl_variant
+32
View File
@@ -0,0 +1,32 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_emplace {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_emplace) {
Shapes r;
r.emplace<1>(10.0, 5.0);
write_and_read(r, R"({"height":10.0,"width":5.0})");
}
} // namespace test_rfl_variant_emplace
+32
View File
@@ -0,0 +1,32 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_get_if {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_get_if) {
const Shapes r = Rectangle{.height = 10, .width = 5};
EXPECT_TRUE(rfl::get_if<1>(r) && true);
EXPECT_FALSE(rfl::get_if<0>(r) && true);
}
} // namespace test_rfl_variant_get_if
@@ -0,0 +1,32 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_holds_alternative {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_holds_alternative) {
const Shapes r = Rectangle{.height = 10, .width = 5};
EXPECT_TRUE(rfl::holds_alternative<Rectangle>(r));
EXPECT_FALSE(rfl::holds_alternative<Circle>(r));
}
} // namespace test_rfl_variant_holds_alternative
+34
View File
@@ -0,0 +1,34 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_swap {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_swap) {
Shapes r = Rectangle{.height = 10, .width = 5};
Shapes c = Circle{.radius = 3};
r.swap(c);
write_and_read(c, R"({"height":10.0,"width":5.0})");
write_and_read(r, R"({"radius":3.0})");
}
} // namespace test_rfl_variant_swap
+39
View File
@@ -0,0 +1,39 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_visit {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_visit) {
Shapes r = Rectangle{.height = 10, .width = 5};
Shapes c = Circle{.radius = 3};
Shapes s = std::make_unique<Square>(Square{.width = 3.0});
const auto f = [](const auto& _r, const auto& _c, const auto& _s) {
return rfl::json::write(_r) + ", " + rfl::json::write(_c) + ", " +
rfl::json::write(_s);
};
const auto str = rfl::visit(f, r, c, s);
EXPECT_TRUE(str ==
R"({"height":10.0,"width":5.0}, {"radius":3.0}, {"width":3.0})");
}
} // namespace test_rfl_variant_visit
@@ -0,0 +1,40 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_rfl_variant_visit_in_place {
struct Circle {
double radius;
};
struct Rectangle {
double height;
double width;
};
struct Square {
double width;
};
using Shapes = rfl::Variant<Circle, Rectangle, std::unique_ptr<Square>>;
TEST(json, test_rfl_variant_visit) {
Shapes r = Rectangle{.height = 10, .width = 5};
Shapes c = Circle{.radius = 3};
Shapes s = std::make_unique<Square>(Square{.width = 3.0});
const auto str = rfl::visit(
[](const auto& _r, const auto& _c, const auto& _s) {
return rfl::json::write(_r) + ", " + rfl::json::write(_c) + ", " +
rfl::json::write(_s);
},
r, c, s);
EXPECT_TRUE(str ==
R"({"height":10.0,"width":5.0}, {"radius":3.0}, {"width":3.0})");
}
} // namespace test_rfl_variant_visit_in_place