Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion include/rfl/parsing/NamedTupleParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,44 @@ concept CanEmitDefault =

namespace rfl::parsing {

template <class T>
struct is_std_optional_for_default : std::false_type {};

template <class T>
struct is_std_optional_for_default<std::optional<T>> : std::true_type {};

template <class T>
inline constexpr bool is_plain_integer_for_default_v =
std::is_integral_v<T> && !std::is_same_v<T, bool> &&
!std::is_same_v<T, char> && !std::is_same_v<T, wchar_t> &&
!std::is_same_v<T, char8_t> && !std::is_same_v<T, char16_t> &&
!std::is_same_v<T, char32_t>;

/// Fast-path conversion of a scalar or optional-scalar default value to
/// `rfl::Generic` for schema emission, matching `rfl::generic::Writer::to_generic`
/// semantics without instantiating `rfl::to_generic<ProcessorsType>` /
/// `rfl::generic::Writer`. Complex types fall back to `rfl::to_generic`.
template <class ProcessorsType, class U>
inline Generic to_default_generic(const U& _val) {
using T = std::remove_cvref_t<U>;
if constexpr (std::is_same_v<T, bool>) {
return Generic(_val);
} else if constexpr (is_plain_integer_for_default_v<T>) {
return Generic(static_cast<std::int64_t>(_val));
} else if constexpr (std::is_floating_point_v<T>) {
return Generic(static_cast<double>(_val));
} else if constexpr (std::is_same_v<T, std::string>) {
return Generic(_val);
} else if constexpr (is_std_optional_for_default<T>::value) {
if (_val.has_value()) {
return to_default_generic<ProcessorsType>(*_val);
}
return Generic();
} else {
return rfl::to_generic<ProcessorsType>(_val);
}
}

/// Sets the default value of the DefaultVal node in `_schema`.
inline void set_schema_default_value(Generic _default, schema::Type* _schema) {
_schema->variant_.visit([&](auto& _s) {
Expand Down Expand Up @@ -171,7 +209,7 @@ void build_named_tuple_field_schema(
internal::CanEmitDefault<U>) {
if (_field_val != nullptr) {
set_schema_default_value(
rfl::to_generic<ProcessorsType>(
to_default_generic<ProcessorsType>(
internal::get_default_val(*_field_val).get()),
&s);
}
Expand Down
Loading