diff --git a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp index 5f3a13926..dafb301f7 100644 --- a/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp +++ b/include/rfl/internal/copy_flattened_tuple_to_named_tuple.hpp @@ -10,21 +10,15 @@ namespace rfl::internal { -template -auto copy_one_element(const auto& _flattened_tuple) { - const auto name_literal = FieldNames::template name_of<_i>(); - return rfl::make_field< - lit_name_v>>( - std::get<_i>(_flattened_tuple)); -} - template auto copy_flattened_tuple_to_named_tuple(const auto& _flattened_tuple) { constexpr auto size = rfl::tuple_size_v>; return [&](std::integer_sequence) { return make_named_tuple( - copy_one_element(_flattened_tuple)...); + rfl::make_field())>>>( + std::get<_i>(_flattened_tuple))...); }(std::make_integer_sequence()); } diff --git a/include/rfl/internal/cpp20/num_fields.hpp b/include/rfl/internal/cpp20/num_fields.hpp index 3864336e1..9c7fbe13d 100644 --- a/include/rfl/internal/cpp20/num_fields.hpp +++ b/include/rfl/internal/cpp20/num_fields.hpp @@ -98,15 +98,61 @@ struct CountFieldsHelper { } template - static consteval std::size_t count_max_args_in_agg_init() { - static_assert(n <= static_cast(sizeof(T))); - if constexpr (constructible() && !constructible()) { + static consteval std::size_t find_first_constructible() { + if constexpr (constructible()) { return n; + } else if constexpr (n < static_cast(sizeof(T))) { + return find_first_constructible(); } else { - return count_max_args_in_agg_init(); + static_assert(n < static_cast(sizeof(T)), + "Type is not aggregate-constructible; rfl::num_fields " + "requires an aggregate type."); + return 0; } } + template + static consteval std::size_t binary_search_max() { + if constexpr (lo + 1 >= hi) { + return lo; + } else { + constexpr std::size_t mid = lo + (hi - lo) / 2; + if constexpr (constructible()) { + return binary_search_max(); + } else { + return binary_search_max(); + } + } + } + + template + static consteval std::size_t expand_and_search() { + static_assert(lo <= static_cast(sizeof(T))); + constexpr std::size_t max_possible = static_cast(sizeof(T)); + constexpr std::size_t probe = + (step > max_possible - lo) ? (max_possible + 1) : (lo + step); + if constexpr (probe <= max_possible && constructible()) { + return expand_and_search(); + } else if constexpr (probe > max_possible && constructible()) { + static_assert( + probe <= max_possible, + "Type is constructible with more arguments than sizeof(T); " + "rfl::num_fields requires an aggregate type."); + return max_possible; + } else { + return binary_search_max(); + } + } + + static consteval std::size_t count_max_args_in_agg_init() { + // Once constructible() holds, constructible() is monotone + // non-increasing for k >= first (every trailing member from `first` onward + // is default-initializable), so exponential + binary search finds the + // exact maximum in O(log N) SFINAE evaluations instead of O(N). + constexpr std::size_t first = find_first_constructible<0>(); + return expand_and_search(); + } + template static consteval std::size_t get_nested_array_size() { if constexpr (size < 1) { diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..edeaa3f4e 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -2,12 +2,19 @@ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #include +#include #include +#include #include +#include #include +#include +#include #include #include +#include +#include "../Generic.hpp" #include "../NamedTuple.hpp" #include "../Result.hpp" #include "../internal/always_inline.hpp" @@ -78,6 +85,255 @@ concept CanEmitDefault = namespace rfl::parsing { +namespace detail { + +template +struct is_std_optional_for_default : std::false_type {}; + +template +struct is_std_optional_for_default> : std::true_type {}; + +template +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 default field value to `rfl::Generic` for schema +/// emission. Basic scalars construct `rfl::Generic` directly without +/// instantiating `rfl::to_generic` / `rfl::generic::Writer`. +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) { + if constexpr (std::is_unsigned_v && sizeof(T) >= sizeof(int64_t)) { + if (_val <= static_cast(std::numeric_limits::max())) { + return Generic(static_cast(_val)); + } + return rfl::to_generic(_val); + } else { + 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 (std::is_same_v>) { + Generic::Array arr; + arr.reserve(_val.size()); + for (const auto& s : _val) { + arr.emplace_back(s); + } + return Generic(std::move(arr)); + } else if constexpr (is_std_optional_for_default::value) { + if (_val.has_value()) { + return detail::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) { + if constexpr (std::is_same_v, + schema::Type::DefaultVal>) { + _s.default_value_ = std::move(_default); + } + }); +} + +/// Free per-field serialization helper parameterized only by ValueType (never +/// the enclosing NamedTuple's FieldTypes... pack). +template +void write_named_tuple_field(const W& _w, const std::string_view _name, + const ValueType& _value, + OutputObjectOrArrayType* _ptr) { + using ParentType = Parent; + const auto make_parent = [](const std::string_view _n, + OutputObjectOrArrayType* _p) { + if constexpr (_no_field_names) { + return typename ParentType::Array{_p}; + } else { + return typename ParentType::Object{_n, _p}; + } + }; + if constexpr (internal::is_extra_fields_v) { + for (const auto& [k, v] : *_value) { + const auto new_parent = make_parent(k, _ptr); + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + } else if constexpr (!_all_required && !_no_field_names && + !is_required()) { + const auto new_parent = make_parent(_name, _ptr); + if (!is_empty(_value)) { + if constexpr (internal::is_attribute_v) { + Parser::write( + _w, _value, new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } + } else { + const auto new_parent = make_parent(_name, _ptr); + if constexpr (internal::is_attribute_v) { + Parser::write(_w, _value, + new_parent.as_attribute()); + } else { + Parser::write(_w, _value, new_parent); + } + } +} + +/// Extracts a pointer to a view slot for schema default inspection. +/// Pointer slots (including `T*` and C-array pointers `T (*)[N]`) are returned +/// directly without dereferencing; non-pointer processor-added slots (such as +/// `rfl::AddStructName`'s `rfl::Literal<...>`) return `nullptr`. +template +RFL_ALWAYS_INLINE auto extract_schema_field_ptr(const SlotT& _slot) noexcept { + if constexpr (std::is_pointer_v) { + return _slot; + } else { + return static_cast(nullptr); + } +} + +/// Free per-field schema helper parameterized only by field type U and its +/// view-slot pointer type (never the enclosing NamedTuple's FieldTypes... +/// pack). Deduces `FieldValPtrT` independently of `U` so both raw C-array +/// pointers (`T (*)[N]` vs `rfl::internal::Array`) and non-pointer +/// processor-added slots (`const void*` / `nullptr`) work cleanly. +template +void build_named_tuple_field_schema( + std::map* _definitions, SchemaType* _schema, + const std::string_view _name, const FieldValPtrT _field_val) noexcept { + using PtrT = std::remove_cvref_t; + if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { + auto s = Parser::to_schema(_definitions); + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + internal::CanEmitDefault) { + if (_field_val != nullptr) { + detail::set_schema_default_value( + detail::to_default_generic( + internal::get_default_val(*_field_val).get()), + &s); + } + } + if constexpr (_no_field_names) { + _schema->types_.emplace_back(std::move(s)); + } else { + _schema->types_[std::string(_name)] = std::move(s); + } + } +} + +/// Whether a missing rfl::DefaultVal field can be value-initialized. Only +/// an rfl::NamedTuple does this at runtime, and it cannot have const fields, +/// so const fields of structs need no instantiation. +template +constexpr bool can_value_initialize_default_val() { + using T = typename internal::default_val_t::Type; + return !std::is_const_v && std::is_default_constructible_v && + std::is_default_constructible_v; +} + +/// Free per-field missing-field handler parameterized only by FieldSlotType +/// (never the enclosing NamedTuple's FieldTypes... pack). +/// Precondition: `_is_set_ptr` is non-null whenever `_defaults_constructed` is +/// false (the uninitialized-memory read path). +template +RFL_ALWAYS_INLINE void handle_missing_named_tuple_field( + const std::string_view _name, const bool _is_found, + const FieldSlotType& _field_slot, bool* _is_set_ptr, + FieldErrors* _errors, + const bool _value_initialize_default_vals) noexcept { + using SlotT = std::remove_cvref_t; + using ValueType = std::remove_reference_t>; + constexpr bool is_default_val_field = internal::is_default_val_v; + constexpr bool is_required_field = + !is_default_val_field && !internal::is_extra_fields_v && + (_all_required || is_required()); + + // When the struct was default-constructed, missing optional or DefaultVal + // fields already hold their default values, so nothing is needed. + if constexpr (_defaults_constructed && !is_required_field) { + return; + } else { + if (should_stop_on_field_error(*_errors)) return; + if (!_is_found) { + if constexpr (std::is_pointer_v && !_defaults_constructed && + is_default_val_field) { + if constexpr (detail::can_value_initialize_default_val()) { + if (_value_initialize_default_vals) { + // The value's constructor can throw, for instance a Validator + // whose zero value is invalid. + try { + ::new (_field_slot) ValueType(); + } catch (std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } + *_is_set_ptr = true; + return; + } + } + } + + if constexpr (is_required_field || + (is_default_val_field && !_defaults_constructed)) { + std::stringstream stream; + stream << "Field named '" << std::string(_name) << "' not found."; + _errors->emplace_back( + make_nested_error(std::string(_name), stream.str())); + return; + } + + if constexpr (std::is_pointer_v && !_defaults_constructed && + !is_required_field && !is_default_val_field) { + using NonConstT = std::remove_const_t; + const auto ptr = const_cast(_field_slot); + if constexpr (std::is_nothrow_default_constructible_v) { + ::new (ptr) NonConstT(); + } else { + // The default value can throw, for instance a Validator whose + // default value is invalid. + try { + ::new (ptr) NonConstT(); + } catch (std::exception& e) { + _errors->emplace_back(make_nested_error( + std::string(_name), + "Field named '" + std::string(_name) + + "' not found, and its default value could not be " + "constructed: " + + e.what())); + return; + } + } + *_is_set_ptr = true; + } + } + } +} + +} // namespace detail + template requires AreReaderAndWriter> @@ -246,83 +502,41 @@ struct NamedTupleParser { } private: - template - static void add_field_to_object(const W& _w, - const NamedTuple& _tup, - OutputObjectOrArrayType* _ptr) { - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_cvref_t; - const auto value = rfl::get<_i>(_tup); - if constexpr (internal::is_extra_fields_v) { - for (const auto& [k, v] : *value) { - const auto new_parent = make_parent(k, _ptr); - Parser, ProcessorsType>::write( - _w, v, new_parent); - } - } else if constexpr (!_all_required && !_no_field_names && - !is_required()) { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if (!is_empty(value)) { - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } else { - constexpr auto name = FieldType::name_.string_view(); - const auto new_parent = make_parent(name, _ptr); - if constexpr (internal::is_attribute_v) { - Parser::write( - _w, value, new_parent.as_attribute()); - } else { - Parser::write(_w, value, new_parent); - } - } - } - - template - static void add_field_to_schema( - std::map* _definitions, - SchemaType* _schema, - View* _view) noexcept { - using F = internal::nth_element_t<_i, FieldTypes...>; - using U = std::remove_cvref_t; - if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { - // Add default value here - auto s = Parser::to_schema(_definitions); - if constexpr (!std::is_same_v && internal::CanEmitDefault) { - s.variant_.visit([&](auto& value) { - if constexpr (std::is_same_v, - schema::Type::DefaultVal>) { - value.default_value_ = - rfl::to_generic((*rfl::get<_i>(*_view)).get()); - } - }); - } - if constexpr (_no_field_names) { - _schema->types_.emplace_back(std::move(s)); - } else { - _schema->types_[std::string(F::name())] = std::move(s); - } - } - }; - template static void build_object(const W& _w, const NamedTuple& _tup, OutputObjectOrArrayType* _ptr, std::integer_sequence) { - (add_field_to_object<_is>(_w, _tup, _ptr), ...); + (detail::write_named_tuple_field( + _w, internal::nth_element_t<_is, FieldTypes...>::name_.string_view(), + rfl::get<_is>(_tup), _ptr), + ...); } - template + template static void build_schema(std::map* _definitions, - SchemaType* _schema, - View* _view, + SchemaType* _schema, View* _view, std::integer_sequence) noexcept { - (add_field_to_schema(_definitions, _schema, _view), ...); + if constexpr (!std::is_same_v) { + (detail::build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), + _view ? detail::extract_schema_field_ptr(rfl::get<_is>(*_view)) + : nullptr), + ...); + } else { + (detail::build_named_tuple_field_schema< + R, W, _no_field_names, ProcessorsType, + std::remove_cvref_t< + typename internal::nth_element_t<_is, FieldTypes...>::Type>>( + _definitions, _schema, + internal::nth_element_t<_is, FieldTypes...>::name(), nullptr), + ...); + } if constexpr (NamedTupleType::pos_extra_fields() != -1) { using F = internal::nth_element_t - static RFL_ALWAYS_INLINE void handle_one_missing_field( - const std::array& _found, const NamedTupleType& _view, - std::array* _set, FieldErrors* _errors, - const bool _value_initialize_default_vals) noexcept { - if (should_stop_on_field_error(*_errors)) return; - using FieldType = internal::nth_element_t<_i, FieldTypes...>; - using ValueType = std::remove_reference_t< - std::remove_pointer_t>; - - if (!std::get<_i>(_found)) { - constexpr bool is_default_val_field = - internal::is_default_val_v; - constexpr bool is_required_field = - !is_default_val_field && !internal::is_extra_fields_v && - (_all_required || is_required()); - - // Without _set, the struct was default-constructed before it was read, - // so the field already holds its default value. With _set, the fields - // are constructed in raw memory. An rfl::NamedTuple has no in-class - // initializers, so a missing bare rfl::DefaultVal field is - // value-initialized there. Otherwise the field's default value is not - // available, so the field is required. - const bool defaults_constructed = _set == nullptr; - - if constexpr (is_default_val_field) { - if constexpr (can_value_initialize_default_val()) { - if (_value_initialize_default_vals && !defaults_constructed) { - // The value's constructor can throw, for instance a Validator - // whose zero value is invalid. - try { - ::new (rfl::get<_i>(_view)) ValueType(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - std::get<_i>(*_set) = true; - return; - } - } - } - - if (is_required_field || - (is_default_val_field && !defaults_constructed)) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - std::stringstream stream; - stream << "Field named '" << std::string(current_name) - << "' not found."; - _errors->emplace_back( - make_nested_error(std::string(current_name), stream.str())); - return; - } - - if constexpr (!is_required_field && !is_default_val_field) { - if (defaults_constructed) { - return; - } - using NonConstT = std::remove_const_t; - const auto ptr = const_cast(rfl::get<_i>(_view)); - if constexpr (std::is_nothrow_default_constructible_v) { - ::new (ptr) NonConstT(); - } else { - // The default value can throw, for instance a Validator whose - // default value is invalid. - try { - ::new (ptr) NonConstT(); - } catch (std::exception& e) { - constexpr auto current_name = - internal::nth_element_t<_i, FieldTypes...>::name(); - _errors->emplace_back(make_nested_error( - std::string(current_name), - "Field named '" + std::string(current_name) + - "' not found, and its default value could not be " - "constructed: " + - e.what())); - return; - } - } - std::get<_i>(*_set) = true; - } - } - } - - /// Whether a missing rfl::DefaultVal field can be value-initialized. Only - /// an rfl::NamedTuple does this at runtime, and it cannot have const fields, - /// so const fields of structs need no instantiation. - template - static constexpr bool can_value_initialize_default_val() { - using T = typename internal::default_val_t::Type; - return !std::is_const_v && std::is_default_constructible_v && - std::is_default_constructible_v; - } - - /// Generates error messages for when fields are missing. - template + template static RFL_ALWAYS_INLINE void handle_missing_fields( const std::array& _found, const NamedTupleType& _view, std::array* _set, FieldErrors* _errors, const bool _value_initialize_default_vals, std::integer_sequence) noexcept { - (handle_one_missing_field<_is>(_found, _view, _set, _errors, - _value_initialize_default_vals), + (detail::handle_missing_named_tuple_field< + _ignore_empty_containers, _all_required, _defaults_constructed, + ProcessorsType>( + internal::nth_element_t<_is, FieldTypes...>::name(), + std::get<_is>(_found), rfl::get<_is>(_view), + _set ? &std::get<_is>(*_set) : nullptr, _errors, + _value_initialize_default_vals), ...); } - static auto make_parent(const std::string_view& _name, - OutputObjectOrArrayType* _ptr) { - if constexpr (_no_field_names) { - return typename ParentType::Array{_ptr}; - } else { - return typename ParentType::Object{_name, _ptr}; - } - } - static RFL_ALWAYS_INLINE std::pair, std::optional> read_object_or_array(const R& _r, @@ -484,9 +592,9 @@ struct NamedTupleParser { } } if (!should_stop_on_field_error(errors)) { - handle_missing_fields(found, *_view, &set, &errors, - _value_initialize_default_vals, - std::make_integer_sequence()); + handle_missing_fields( + found, *_view, &set, &errors, _value_initialize_default_vals, + std::make_integer_sequence()); } if constexpr (internal::fail_fast_v) { return std::make_pair(set, std::move(errors).error()); @@ -517,9 +625,10 @@ struct NamedTupleParser { if constexpr (internal::has_default_val_v && !internal::default_if_missing_v) { if (!should_stop_on_field_error(errors)) { - handle_missing_fields(reader.found(), *_view, nullptr, &errors, - /*_value_initialize_default_vals=*/false, - std::make_integer_sequence()); + handle_missing_fields( + reader.found(), *_view, nullptr, &errors, + /*_value_initialize_default_vals=*/false, + std::make_integer_sequence()); } } if constexpr (internal::fail_fast_v) { diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 84ee4b826..a904c4a26 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -14,11 +14,88 @@ #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "find_field_index.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "wrap_error.hpp" namespace rfl::parsing { +namespace detail { + +/// Placement-moves a parsed field value into uninitialized struct storage. +/// Free function parameterized only by (Target, Source)—never ViewType—so +/// instantiations do not carry the enclosing NamedTuple in mangled symbol +/// names or DWARF debug info. +template +void placement_move_field(Target* _t, Source* _s) { + if constexpr (std::is_const_v) { + detail::placement_move_field(const_cast*>(_t), + _s); + } else if constexpr (!rfl::internal::is_array_v && + !std::is_array_v) { + ::new (_t) Target(std::move(*_s)); + } else if constexpr (rfl::internal::is_array_v) { + static_assert(std::is_array_v, "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + detail::placement_move_field(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + detail::placement_move_field(&((*_t)[i]), &((*_s)[i])); + } + } +} + +/// Reads one field into an uninitialized view slot. Free function parameterized +/// only by (R, W, OriginalType, ProcessorsType)—never the enclosing ViewType—so +/// instantiations do not repeat the full NamedTuple in mangled symbol names or +/// DWARF debug info. +template +RFL_ALWAYS_INLINE void assign_uninitialized_view_field( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, bool& _is_set, + FieldErrors* _errors, const size_t _reserve_errors) { + using T = std::remove_cvref_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + // Reserve lazily to avoid error-vector reallocations while keeping + // successful reads allocation-free. + _errors->reserve(_reserve_errors); + _errors->emplace_back(wrap_field_error(_name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + detail::placement_move_field(_slot, &(*res)); + } else { + _slot = std::move(*res); + } + _is_set = true; +} + +/// Reads one extra field into an uninitialized ExtraFields slot. +template +void assign_extra_uninitialized_field( + const R& _r, const std::string_view _current_name, + const typename R::InputVarType& _var, ExtraFieldsType* _extra_fields, + bool& _is_found, bool& _is_set, FieldErrors* _errors) { + using T = std::remove_cvref_t< + std::remove_pointer_t>; + if (!_is_set) { + ::new (_extra_fields) ExtraFieldsType(); + _is_set = true; + _is_found = true; + } + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + _extra_fields->emplace(std::string(_current_name), std::move(*res)); +} + +} // namespace detail + template class ViewReader { public: @@ -51,8 +128,8 @@ class ViewReader { */ void read(const std::string_view& _name, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _name, _var, view_, errors_, found_, set_, - std::make_integer_sequence()); + assign_to_matching_name(*r_, _name, _var, view_, errors_, found_, set_, + std::make_integer_sequence()); } /** @@ -63,7 +140,7 @@ class ViewReader { */ void read(const int _index, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, _index, _var, view_, errors_, found_, set_, + assign_to_matching_index(*r_, _index, _var, view_, errors_, found_, set_, std::make_integer_sequence()); } @@ -71,8 +148,36 @@ class ViewReader { template void read(std::integral_constant, const InputVarType& _var) const { if (should_stop_on_field_error(*errors_)) return; - assign_to_matching_field(*r_, i, _var, view_, errors_, found_, set_, - std::integer_sequence()); + bool already_assigned = false; + using FieldType = tuple_element_t; + if (!std::get(*found_)) { + std::get(*found_) = true; + already_assigned = true; + detail::assign_uninitialized_view_field( + *r_, _var, FieldType::name(), rfl::get(*view_), std::get(*set_), + errors_, size_); + } + + if constexpr (ViewType::pos_extra_fields() != -1) { + static_assert(!schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + static_assert( + ViewType::pos_extra_fields() == -1, + "rfl::ExtraFields are not supported for positional reads."); + } else if constexpr (internal::no_extra_fields_v) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + if (!already_assigned) { + std::stringstream stream; + stream << "Value named '" << i << "' not used."; + errors_->emplace_back( + make_nested_error(static_cast(i), stream.str())); + } + } } /** @@ -83,91 +188,47 @@ class ViewReader { static constexpr size_t size() { return size_; } private: - template - static bool is_matching(const int _current_index) { - return _current_index == i; - } - - template - static bool is_matching(const std::string_view& _current_name) { - return _current_name == FieldType::name(); - } - - static ErrorDetail::PathSegment to_path_segment(const int _current_index) { - return static_cast(_current_index); - } - - static ErrorDetail::PathSegment to_path_segment( - const std::string_view& _current_name) { - return std::string(_current_name); - } - - template - static RFL_ALWAYS_INLINE void assign_if_field_matches( - const R& _r, const auto _current_name_or_index, const auto& _var, - auto* _view, auto* _errors, auto* _found, auto* _set, - bool* _already_assigned) { - using FieldType = tuple_element_t; - using OriginalType = typename FieldType::Type; - using T = - std::remove_cvref_t>; - if (!(*_already_assigned) && !std::get(*_found) && - is_matching(_current_name_or_index)) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) [[unlikely]] { - constexpr auto name = FieldType::name(); - // Reserve lazily to avoid error-vector reallocations while keeping - // successful reads allocation-free. - _errors->reserve(size_); - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; - } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); - } - std::get(*_set) = true; - } - } - - template - static void assign_to_extra_fields(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, auto* _set) { - auto* extra_fields = _view->template get<_pos>(); - using ExtraFieldsType = - std::remove_cvref_t>; - using T = std::remove_cvref_t< - std::remove_pointer_t>; - if (!std::get<_pos>(*_set)) { - ::new (extra_fields) ExtraFieldsType(); - std::get<_pos>(*_set) = true; - std::get<_pos>(*_found) = true; - } - auto res = Parser::read(_r, _var); - if (!res) [[unlikely]] { - _errors->emplace_back( - wrap_field_error(_current_name, std::move(res).error())); - return; - } - extra_fields->emplace(std::string(_current_name), std::move(*res)); + template + static void assign_by_index(const R& _r, const int _idx, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, + std::array* _set, + std::integer_sequence) { + using Fields = typename ViewType::Fields; + static_cast( + ((_idx == is + ? (detail::assign_uninitialized_view_field< + R, W, typename tuple_element_t::Type, + ProcessorsType>(_r, _var, + tuple_element_t::name(), + rfl::get(*_view), std::get(*_set), + _errors, size_), + true) + : false) || + ...)); } template - static void assign_to_matching_field(const R& _r, - const auto _current_name_or_index, - const auto& _var, auto* _view, - auto* _errors, auto* _found, auto* _set, - std::integer_sequence) { + static void assign_to_matching_name(const R& _r, + const std::string_view& _current_name, + const InputVarType& _var, ViewType* _view, + FieldErrors* _errors, + std::array* _found, + std::array* _set, + std::integer_sequence _seq) { bool already_assigned = false; - - (assign_if_field_matches(_r, _current_name_or_index, _var, _view, - _errors, _found, _set, &already_assigned), - ...); + if constexpr (size_ > 0) { + if (const int idx = + detail::FieldNameLookup::find( + _current_name); + idx >= 0) { + if (!(*_found)[static_cast(idx)]) { + (*_found)[static_cast(idx)] = true; + already_assigned = true; + assign_by_index(_r, idx, _var, _view, _errors, _set, _seq); + } + } + } if constexpr (ViewType::pos_extra_fields() != -1) { static_assert(!schemaful::IsSchemafulReader, @@ -175,8 +236,13 @@ class ViewReader { "because schemaful formats cannot have extra fields."); constexpr int pos = ViewType::pos_extra_fields(); if (!already_assigned) { - assign_to_extra_fields(_r, _current_name_or_index, _var, _view, - _errors, _found, _set); + auto* extra_fields = _view->template get(); + using ExtraFieldsType = + std::remove_cvref_t>; + detail::assign_extra_uninitialized_field( + _r, _current_name, _var, extra_fields, std::get(*_found), + std::get(*_set), _errors); } } else if constexpr (internal::no_extra_fields_v) { static_assert( @@ -185,29 +251,48 @@ class ViewReader { "sense, because schemaful formats cannot have extra fields."); if (!already_assigned) { std::stringstream stream; - stream << "Value named '" << _current_name_or_index << "' not used."; - _errors->emplace_back(make_nested_error( - to_path_segment(_current_name_or_index), stream.str())); + stream << "Value named '" << _current_name << "' not used."; + _errors->emplace_back( + make_nested_error(std::string(_current_name), stream.str())); } } } - template - static void move_to(Target* _t, Source* _s) { - if constexpr (std::is_const_v) { - return move_to(const_cast*>(_t), _s); - } else if constexpr (!rfl::internal::is_array_v && - !std::is_array_v) { - ::new (_t) Target(std::move(*_s)); - } else if constexpr (rfl::internal::is_array_v) { - static_assert(std::is_array_v, - "Expected target to be a c-array."); - for (size_t i = 0; i < _s->arr_.size(); ++i) { - move_to(&((*_t)[i]), &(_s->arr_[i])); + template + static void assign_to_matching_index(const R& _r, const int _index, + const InputVarType& _var, + ViewType* _view, + FieldErrors* _errors, + std::array* _found, + std::array* _set, + std::integer_sequence _seq) { + bool already_assigned = false; + if constexpr (size_ > 0) { + if (_index >= 0 && static_cast(_index) < size_ && + !(*_found)[static_cast(_index)]) { + (*_found)[static_cast(_index)] = true; + already_assigned = true; + assign_by_index(_r, _index, _var, _view, _errors, _set, _seq); } - } else { - for (size_t i = 0; i < _s->size(); ++i) { - move_to(&((*_t)[i]), &((*_s)[i])); + } + + if constexpr (ViewType::pos_extra_fields() != -1) { + static_assert(!schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); + static_assert( + ViewType::pos_extra_fields() == -1, + "rfl::ExtraFields are not supported for positional reads."); + } else if constexpr (internal::no_extra_fields_v) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); + if (!already_assigned) { + std::stringstream stream; + stream << "Value named '" << _index << "' not used."; + _errors->emplace_back( + make_nested_error(static_cast(_index), stream.str())); } } } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..9cc43617f 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -4,20 +4,99 @@ #include #include #include +#include #include #include #include #include "../Ref.hpp" #include "../Tuple.hpp" +#include "../internal/always_inline.hpp" #include "../internal/is_array.hpp" #include "../internal/no_extra_fields_v.hpp" #include "FieldErrors.hpp" #include "Parser_base.hpp" +#include "find_field_index.hpp" #include "wrap_error.hpp" namespace rfl::parsing { +namespace detail { + +/// Move-assigns a parsed field value into an already-constructed struct field. +/// Free function parameterized only by (Target, Source)—never ViewType—so +/// instantiations do not carry the enclosing NamedTuple in mangled symbol +/// names or DWARF debug info. +template +void move_assign_field(Target* _t, Source* _s) { + if constexpr (!rfl::internal::is_array_v && + !std::is_array_v) { + if constexpr (std::is_const_v) { + // The struct was default-constructed, so *_t is a live const object + // and must not be assigned to. Re-create it in place instead. If the + // constructor throws, we are inside a noexcept function, so it cannot + // be destroyed twice. + using NonConstTarget = std::remove_const_t; + auto* const ptr = const_cast(_t); + std::destroy_at(ptr); + ::new (ptr) NonConstTarget(std::move(*_s)); + } else { + *_t = Target(std::move(*_s)); + } + } else if constexpr (rfl::internal::is_array_v) { + static_assert(std::is_array_v, "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + detail::move_assign_field(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + detail::move_assign_field(&((*_t)[i]), &((*_s)[i])); + } + } +} + +/// Reads one field into an already-constructed view slot. Free function +/// parameterized only by (R, W, OriginalType, ProcessorsType)—never the +/// enclosing ViewType—so instantiations do not repeat the full NamedTuple in +/// mangled symbol names or DWARF debug info. +template +RFL_ALWAYS_INLINE void assign_default_view_field( + const R& _r, const typename R::InputVarType& _var, + const std::string_view _name, OriginalType& _slot, + FieldErrors* _errors) { + using T = std::remove_cvref_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _errors->emplace_back(wrap_field_error(_name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + detail::move_assign_field(_slot, &(*res)); + } else { + _slot = std::move(*res); + } +} + +/// Reads one extra field into an already-constructed ExtraFields slot. +template +void assign_extra_default_field(const R& _r, + const std::string_view _current_name, + const typename R::InputVarType& _var, + ExtraFieldsType* _extra_fields, + FieldErrors* _errors) { + using T = std::remove_cvref_t< + std::remove_pointer_t>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + _extra_fields->emplace(std::string(_current_name), std::move(*res)); +} + +} // namespace detail + template class ViewReaderWithDefault { public: @@ -68,69 +147,47 @@ class ViewReaderWithDefault { static constexpr size_t size() { return size_; } private: - template - static void assign_if_field_matches(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, - bool* _already_assigned) { - using FieldType = tuple_element_t; - using OriginalType = typename FieldType::Type; - using T = - std::remove_cvref_t>; - constexpr auto name = FieldType::name(); - if (!(*_already_assigned) && !std::get(*_found) && - _current_name == name) { - std::get(*_found) = true; - *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; - } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); - } else { - rfl::get(*_view) = std::move(*res); - } - } - } - - template - static void assign_to_extra_fields(const R& _r, - const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors) { - auto* extra_fields = _view->template get<_pos>(); - using ExtraFieldsType = - std::remove_cvref_t>; - using T = std::remove_cvref_t< - std::remove_pointer_t>; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back( - wrap_field_error(_current_name, std::move(res).error())); - return; - } - extra_fields->emplace(std::string(_current_name), std::move(*res)); - } - template static void assign_to_matching_field(const R& _r, const std::string_view& _current_name, - const auto& _var, auto* _view, - auto* _errors, auto* _found, + const InputVarType& _var, + ViewType* _view, + FieldErrors* _errors, + std::array* _found, std::integer_sequence) { + using Fields = typename ViewType::Fields; bool already_assigned = false; - - (assign_if_field_matches(_r, _current_name, _var, _view, _errors, - _found, &already_assigned), - ...); + if constexpr (size_ > 0) { + if (const int idx = + detail::FieldNameLookup::find( + _current_name); + idx >= 0) { + if (!(*_found)[static_cast(idx)]) { + (*_found)[static_cast(idx)] = true; + already_assigned = true; + static_cast( + ((idx == is + ? (detail::assign_default_view_field< + R, W, typename tuple_element_t::Type, + ProcessorsType>(_r, _var, + tuple_element_t::name(), + rfl::get(*_view), _errors), + true) + : false) || + ...)); + } + } + } if constexpr (ViewType::pos_extra_fields() != -1) { constexpr int pos = ViewType::pos_extra_fields(); if (!already_assigned) { - assign_to_extra_fields(_r, _current_name, _var, _view, _errors); + auto* extra_fields = _view->template get(); + using ExtraFieldsType = + std::remove_cvref_t>; + detail::assign_extra_default_field( + _r, _current_name, _var, extra_fields, _errors); } } else if constexpr (internal::no_extra_fields_v) { if (!already_assigned) { @@ -144,35 +201,6 @@ class ViewReaderWithDefault { } } - template - static void move_to(Target* _t, Source* _s) { - if constexpr (!rfl::internal::is_array_v && - !std::is_array_v) { - if constexpr (std::is_const_v) { - // The struct was default-constructed, so *_t is a live const object - // and must not be assigned to. Re-create it in place instead. If the - // constructor throws, we are inside a noexcept function, so it cannot - // be destroyed twice. - using NonConstTarget = std::remove_const_t; - auto* const ptr = const_cast(_t); - std::destroy_at(ptr); - ::new (ptr) NonConstTarget(std::move(*_s)); - } else { - *_t = Target(std::move(*_s)); - } - } else if constexpr (rfl::internal::is_array_v) { - static_assert(std::is_array_v, - "Expected target to be a c-array."); - for (size_t i = 0; i < _s->arr_.size(); ++i) { - move_to(&((*_t)[i]), &(_s->arr_[i])); - } - } else { - for (size_t i = 0; i < _s->size(); ++i) { - move_to(&((*_t)[i]), &((*_s)[i])); - } - } - } - private: /// The underlying reader. const R* r_; diff --git a/include/rfl/parsing/call_destructors_where_necessary.hpp b/include/rfl/parsing/call_destructors_where_necessary.hpp index 403609760..c91d0e465 100644 --- a/include/rfl/parsing/call_destructors_where_necessary.hpp +++ b/include/rfl/parsing/call_destructors_where_necessary.hpp @@ -2,7 +2,9 @@ #define RFL_PARSING_CALL_DESTRUCTORS_WHERE_NECESSARY_HPP_ #include +#include #include +#include #include "../get.hpp" @@ -17,45 +19,50 @@ namespace rfl::parsing { */ template void call_destructor_on_array(const size_t _size, T* _ptr) { - for (size_t i = 0; i < _size; ++i) { - if constexpr (std::is_array_v) { - call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); - } else if constexpr (std::is_destructible_v>) { - (_ptr + i)->~T(); + if constexpr (!std::is_trivially_destructible_v>) { + for (size_t i = 0; i < _size; ++i) { + if constexpr (std::is_array_v) { + call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); + } else if constexpr (std::is_destructible_v>) { + (_ptr + i)->~T(); + } } } } +namespace detail { + /** - * @brief Calls the destructor on a single element of a view, if necessary. - * - * @tparam ViewType The type of the view. - * @tparam _size The size of the set array. - * @tparam _i The index of the element. - * @param _set A boolean array indicating which elements have been set. - * @param _view The view to call the destructor on. + * @brief Calls the destructor on a single field pointer if it was set. + * Free function parameterized only by the field's pointer type (never + * ViewType) so instantiations do not carry the enclosing NamedTuple in their + * mangled symbol name or DWARF debug info. */ -template -void call_destructor_on_one_if_necessary(const std::array& _set, - ViewType* _view) { - using FieldType = tuple_element_t<_i, typename ViewType::Fields>; - using OriginalType = std::remove_cv_t; +template +inline void destroy_field_if_set(const bool _is_set, + const OriginalType& _slot) noexcept { + using CleanOriginal = std::remove_cvref_t; using ValueType = - std::remove_cvref_t>; - if constexpr (!std::is_array_v && - std::is_pointer_v && - std::is_destructible_v) { - if (std::get<_i>(_set)) { - rfl::get<_i>(*_view)->~ValueType(); + std::remove_cvref_t>; + if constexpr (std::is_pointer_v && + std::is_array_v) { + if constexpr (!std::is_trivially_destructible_v< + std::remove_all_extents_t>) { + if (_is_set) { + call_destructor_on_array(sizeof(*_slot) / sizeof(**_slot), *_slot); + } } - } else if constexpr (std::is_array_v) { - if (std::get<_i>(_set)) { - auto ptr = rfl::get<_i>(*_view); - call_destructor_on_array(sizeof(*ptr) / sizeof(**ptr), *ptr); + } else if constexpr (std::is_pointer_v && + std::is_destructible_v && + !std::is_trivially_destructible_v) { + if (_is_set) { + _slot->~ValueType(); } } } +} // namespace detail + /** * @brief Calls the destructors on the elements of a view, if necessary. * @@ -68,7 +75,7 @@ template void call_destructors_where_necessary(const std::array& _set, ViewType* _view) { [&](std::integer_sequence) { - (call_destructor_on_one_if_necessary(_set, _view), + (detail::destroy_field_if_set(std::get(_set), rfl::get(*_view)), ...); }(std::make_integer_sequence()); } diff --git a/include/rfl/parsing/find_field_index.hpp b/include/rfl/parsing/find_field_index.hpp new file mode 100644 index 000000000..96d4013ea --- /dev/null +++ b/include/rfl/parsing/find_field_index.hpp @@ -0,0 +1,111 @@ +#ifndef RFL_PARSING_FIND_FIELD_INDEX_HPP_ +#define RFL_PARSING_FIND_FIELD_INDEX_HPP_ + +#include +#include +#include + +#include "../Literal.hpp" +#include "../internal/StringLiteral.hpp" + +namespace rfl::parsing::detail { + +struct FieldNameEntry { + std::string_view name; + int field_idx; +}; + +/// O(N log N) constexpr heapsort for FieldNameEntry tables (avoids relying on +/// C++20 constexpr std::sort support in older libc++ releases). +template +constexpr void sort_field_name_table( + std::array& _table) noexcept { + auto sift_down = [&](std::size_t _root, const std::size_t _end) { + while (true) { + std::size_t child = _root * 2 + 1; + if (child >= _end) { + break; + } + if (child + 1 < _end && _table[child].name < _table[child + 1].name) { + ++child; + } + if (_table[_root].name < _table[child].name) { + const auto tmp = _table[_root]; + _table[_root] = _table[child]; + _table[child] = tmp; + _root = child; + } else { + break; + } + } + }; + for (std::size_t start = _n / 2; start > 0; --start) { + sift_down(start - 1, _n); + } + for (std::size_t end = _n; end > 1; --end) { + const auto tmp = _table[0]; + _table[0] = _table[end - 1]; + _table[end - 1] = tmp; + sift_down(0, end - 1); + } +} + +/// Compile-time field name lookup keyed solely on a NamedTuple's `Names` +/// (`rfl::Literal<_names...>`), so the lookup table is independent of field +/// value types (e.g., `rfl::Description` wrappers) and shared across +/// `ViewReader`, `ViewReaderWithDefault`, readers, writers, and processors. +template +struct FieldNameLookup; + +template +struct FieldNameLookup> { + static constexpr std::size_t size_ = sizeof...(_names); + + static constexpr auto make_table() { + std::array table{}; + int idx = 0; + ((table[static_cast(idx)] = + FieldNameEntry{_names.string_view(), idx}, + ++idx), + ...); + if constexpr (size_ > 8) { + detail::sort_field_name_table(table); + } + return table; + } + + static int find(const std::string_view _name) noexcept { + if constexpr (size_ == 0) { + return -1; + } else { + static constexpr auto table = make_table(); + if constexpr (size_ <= 8) { + for (const auto& entry : table) { + if (entry.name == _name) { + return entry.field_idx; + } + } + return -1; + } else { + std::size_t lo = 0; + std::size_t hi = table.size(); + while (lo < hi) { + const std::size_t mid = lo + (hi - lo) / 2; + if (table[mid].name < _name) { + lo = mid + 1; + } else { + hi = mid; + } + } + if (lo < table.size() && table[lo].name == _name) { + return table[lo].field_idx; + } + return -1; + } + } + } +}; + +} // namespace rfl::parsing::detail + +#endif diff --git a/tests/json/test_parser_isolation_edge_cases.cpp b/tests/json/test_parser_isolation_edge_cases.cpp new file mode 100644 index 000000000..e2d1a8361 --- /dev/null +++ b/tests/json/test_parser_isolation_edge_cases.cpp @@ -0,0 +1,200 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_parser_isolation_edge_cases { + +struct EmptyStruct {}; +struct OneField { + int a; +}; +struct OneByte { + char a; +}; +struct FourBytes { + char a, b, c, d; +}; +struct NonDefaultable { + int x; + explicit NonDefaultable(int _x) : x(_x) {} +}; +struct MixedAggregate { + int a; + NonDefaultable b; + std::string c; + bool d; +}; +struct WithCArray { + int a[3]; + int b; +}; +struct WithConstRefMember { + const int& ref; + int val; +}; +struct WideStruct32 { + int f00, f01, f02, f03, f04, f05, f06, f07; + int f08, f09, f10, f11, f12, f13, f14, f15; + int f16, f17, f18, f19, f20, f21, f22, f23; + int f24, f25, f26, f27, f28, f29, f30, f31; +}; + +struct SmallWithExtra { + int a = 1; + rfl::ExtraFields extra; +}; + +struct SmallStrict { + int a = 1; + int b = 2; +}; + +struct WideWithExtra { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; + int f6 = 6; + int f7 = 7; + int f8 = 8; + int f9 = 9; + rfl::ExtraFields extra; +}; + +struct WideStrict { + int f0 = 0; + int f1 = 1; + int f2 = 2; + int f3 = 3; + int f4 = 4; + int f5 = 5; + int f6 = 6; + int f7 = 7; + int f8 = 8; + int f9 = 9; +}; + +struct DefaultValEdgeScalars { + rfl::DefaultVal big_u64 = + static_cast(std::numeric_limits::max()) + 42ULL; + rfl::DefaultVal tag_char = 'Z'; + rfl::DefaultVal flag = true; + rfl::DefaultVal ratio = 1.5f; + rfl::DefaultVal label = "hello"; + rfl::DefaultVal> tags = + std::vector{"a", "b"}; + rfl::DefaultVal> opt_set = 9; + rfl::DefaultVal> opt_empty = std::nullopt; + rfl::Rename<"renamedCount", rfl::DefaultVal> renamed_count = 7; +}; + +struct AddStructNameWithDefault { + rfl::DefaultVal count = 7; + std::string name = "ok"; +}; + +TEST(json, test_num_fields_binary_search_edge_cases) { + static_assert(rfl::num_fields == 0); + static_assert(rfl::num_fields == 1); + static_assert(rfl::num_fields == 1); + static_assert(rfl::num_fields == 4); + static_assert(rfl::num_fields == 4); +#if defined(REFLECT_CPP_C_ARRAYS_OR_INHERITANCE) || \ + defined(REFLECTCPP_C_ARRAYS_OR_INHERITANCE) + static_assert(rfl::num_fields == 2); +#else + static_assert(rfl::num_fields == 4); +#endif + static_assert(rfl::num_fields == 2); + static_assert(rfl::num_fields == 32); + SUCCEED(); +} + +TEST(json, test_view_reader_duplicate_keys_small_and_wide) { + // Small struct (<= 8 fields, linear scan path) + const auto dup_strict_small = + rfl::json::read( + R"({"a":10,"b":20,"a":30})"); + EXPECT_FALSE(dup_strict_small.has_value()); + + const auto dup_def_small = + rfl::json::read( + R"({"a":10,"a":30})"); + EXPECT_FALSE(dup_def_small.has_value()); + + const auto dup_extra_small = + rfl::json::read(R"({"a":10,"a":30})").value(); + EXPECT_EQ(dup_extra_small.a, 10); + EXPECT_EQ(dup_extra_small.extra.at("a"), 30); + + // Wide struct (> 8 fields, sorted binary-search path) + const auto dup_strict_wide = rfl::json::read( + R"({"f0":0,"f1":1,"f2":2,"f3":3,"f4":4,"f5":5,"f6":6,"f7":7,"f8":8,"f9":9,"f5":55})"); + EXPECT_FALSE(dup_strict_wide.has_value()); + + const auto dup_def_wide = + rfl::json::read( + R"({"f5":5,"f5":55})"); + EXPECT_FALSE(dup_def_wide.has_value()); + + const auto dup_extra_wide = + rfl::json::read( + R"({"f5":5,"f5":55,"z":99})") + .value(); + EXPECT_EQ(dup_extra_wide.f5, 5); + EXPECT_EQ(dup_extra_wide.extra.at("f5"), 55); + EXPECT_EQ(dup_extra_wide.extra.at("z"), 99); +} + +TEST(json, test_to_default_generic_edge_values_and_add_struct_name) { + const auto schema = rfl::json::to_schema(); + const auto root = + rfl::json::read(schema).value().to_object().value(); + const auto defs = root.get("$defs").value().to_object().value(); + ASSERT_EQ(defs.size(), 1u); + const auto def_obj = defs.begin()->second.to_object().value(); + const auto props = def_obj.get("properties").value().to_object().value(); + const auto default_json = [&](const std::string& _field) { + const auto f = props.get(_field).value().to_object().value(); + return rfl::json::write(f.get("default").value()); + }; + + EXPECT_EQ(default_json("tag_char"), "90"); + EXPECT_EQ(default_json("flag"), "true"); + EXPECT_EQ(default_json("ratio"), "1.5"); + EXPECT_EQ(default_json("label"), "\"hello\""); + EXPECT_EQ(default_json("tags"), "[\"a\",\"b\"]"); + EXPECT_EQ(default_json("opt_set"), "9"); + EXPECT_EQ(default_json("opt_empty"), "null"); + EXPECT_EQ(default_json("renamedCount"), "7"); + // uint64_t > INT64_MAX must match rfl::to_generic fallback: + const auto expected_u64 = rfl::json::write(rfl::to_generic( + static_cast(std::numeric_limits::max()) + 42ULL)); + EXPECT_EQ(default_json("big_u64"), expected_u64); + + const auto asn_schema = + rfl::json::to_schema>(); + EXPECT_NE( + asn_schema.find( + "\"type\":{\"type\":\"string\",\"enum\":[\"AddStructNameWithDefault\"]}"), + std::string::npos); + EXPECT_NE(asn_schema.find("\"default\":7"), std::string::npos); + + const auto parsed = + rfl::json::read>( + R"({"type":"AddStructNameWithDefault","name":"hi"})") + .value(); + EXPECT_EQ(parsed.count.get(), 7); + EXPECT_EQ(parsed.name, "hi"); +} + +} // namespace test_parser_isolation_edge_cases