diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index fee7e13d1..0cf104d88 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -84,6 +84,44 @@ concept CanEmitDefault = namespace rfl::parsing { +template +struct is_std_optional_for_default : std::false_type {}; + +template +struct is_std_optional_for_default> : std::true_type {}; + +template +inline constexpr bool is_plain_integer_for_default_v = + std::is_integral_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v && !std::is_same_v && + !std::is_same_v; + +/// 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` / +/// `rfl::generic::Writer`. Complex types fall back to `rfl::to_generic`. +template +inline Generic to_default_generic(const U& _val) { + using T = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return Generic(_val); + } else if constexpr (is_plain_integer_for_default_v) { + return Generic(static_cast(_val)); + } else if constexpr (std::is_floating_point_v) { + return Generic(static_cast(_val)); + } else if constexpr (std::is_same_v) { + return Generic(_val); + } else if constexpr (is_std_optional_for_default::value) { + if (_val.has_value()) { + return to_default_generic(*_val); + } + return Generic(); + } else { + return rfl::to_generic(_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) { @@ -171,7 +209,7 @@ void build_named_tuple_field_schema( internal::CanEmitDefault) { if (_field_val != nullptr) { set_schema_default_value( - rfl::to_generic( + to_default_generic( internal::get_default_val(*_field_val).get()), &s); }