diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 7e586b749..0b7418027 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -2,8 +2,11 @@ #define RFL_PARSING_FIELD_VARIANT_PARSER_HPP_ #include +#include #include #include +#include +#include #include "../NamedTuple.hpp" #include "../Result.hpp" @@ -18,6 +21,32 @@ namespace rfl::parsing { +/// Namespace-scope visitor for writing one externally tagged field alternative, +/// parameterized only by `(R, W, ProcessorsType, P)` and the active `FieldType` +/// — never the enclosing `FieldTypes...` pack. +template +struct FieldVariantWriter { + const W& w_; + const P& parent_; + + template + void operator()(const FieldType& _field) const { + const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); + using NamedTupleType = std::remove_cvref_t; + Parser::write(w_, named_tuple, + parent_); + } +}; + +/// Namespace-scope schema builder for one externally tagged field alternative, +/// parameterized only by `(R, W, FieldType, ProcessorsType)`. +template +inline schema::Type field_variant_alternative_to_schema( + std::map* _definitions) noexcept { + using NamedTupleType = NamedTuple>; + return Parser::to_schema(_definitions); +} + /// To be used when all options of the variants are rfl::Field. Essentially, /// this is an externally tagged union. template @@ -43,24 +72,23 @@ struct FieldVariantParser { "Externally tagged variants cannot have duplicate field " "names."); - const auto to_result = [&](const auto _obj) -> ResultType { - auto field_variant = std::optional>(); - const auto reader = - FieldVariantReader( - &_r, &field_variant); - auto err = _r.read_object(reader, _obj); - if (err) { - return error(std::move(*err)); - } - if (!field_variant) { - return error( - "Could not parse: Expected the object to have " - "exactly one field, but found none."); - } - return std::move(*field_variant); - }; - - return _r.to_object(_var).and_then(to_result); + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return error(std::move(obj).error()); + } + auto field_variant = std::optional>(); + const auto reader = FieldVariantReader( + &_r, &field_variant); + auto err = _r.read_object(reader, *obj); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + if (!field_variant) [[unlikely]] { + return error( + "Could not parse: Expected the object to have " + "exactly one field, but found none."); + } + return std::move(*field_variant); } /** @@ -79,12 +107,7 @@ struct FieldVariantParser { "Externally tagged variants cannot have duplicate field " "names."); - _v.visit([&](const auto& _field) { - const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); - using NamedTupleType = std::remove_cvref_t; - Parser::write(_w, named_tuple, - _parent); - }); + _v.visit(FieldVariantWriter{_w, _parent}); } /** @@ -95,18 +118,13 @@ struct FieldVariantParser { */ static schema::Type to_schema( std::map* _definitions) { - return schema::Type{schema::Type::AnyOf{ - .types_ = std::vector( - {one_field_to_type(_definitions)...})}}; - } - - private: - template - static schema::Type one_field_to_type( - std::map* _definitions) noexcept { - using NamedTupleType = NamedTuple>; - return Parser::to_schema( - _definitions); + std::vector types; + types.reserve(sizeof...(FieldTypes)); + (types.emplace_back( + field_variant_alternative_to_schema( + _definitions)), + ...); + return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}}; } }; } // namespace rfl::parsing diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index b7454b1a7..001d30dd8 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -2,25 +2,80 @@ #define RFL_PARSING_FIELDVARIANTREADER_HPP_ #include -#include +#include #include #include #include +#include "../Literal.hpp" #include "../Result.hpp" #include "../Variant.hpp" -#include "../internal/is_array.hpp" -#include "../internal/nth_element_t.hpp" +#include "../internal/always_inline.hpp" +#include "../internal/cold.hpp" #include "Parser_base.hpp" +#include "find_field_index.hpp" namespace rfl::parsing { +RFL_COLD inline Error make_field_variant_unknown_field_error( + const std::string_view _disc_value) { + std::string msg; + msg.reserve(64 + _disc_value.size()); + msg.append("Could not parse rfl::Variant, could not match field named '"); + msg.append(_disc_value); + msg.append("'."); + return Error(std::move(msg)); +} + +RFL_COLD inline Error make_field_variant_field_error( + const std::string_view _disc_value, const Error& _e) { + const auto& what = _e.what(); + std::string msg; + msg.reserve(46 + _disc_value.size() + what.size()); + msg.append("Could not parse rfl::Variant with field '"); + msg.append(_disc_value); + msg.append("': "); + msg.append(what); + return Error(std::move(msg)); +} + +/// Reads one field-variant alternative. Parameterized only by +/// `(R, W, FieldType, ProcessorsType)` — never the enclosing `FieldTypes...` +/// pack — so mangled symbols and debug info stay O(1) per alternative. +template +inline std::optional> +read_field_variant_alternative(const R& _r, + const typename R::InputVarType& _var, + const std::string_view _disc_value, + std::optional* _err) noexcept { + using CleanFieldType = std::remove_cvref_t; + using ValueType = std::remove_cvref_t; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _err->emplace( + make_field_variant_field_error(_disc_value, std::move(res).error())); + return std::nullopt; + } + return std::optional(std::in_place, std::move(*res)); +} + +template +RFL_ALWAYS_INLINE void assign_field_variant_if_present( + std::optional>* _out, + std::optional&& _field) noexcept { + if (_field) [[likely]] { + _out->emplace(VariantType(std::move(*_field))); + } +} + template class FieldVariantReader { private: using InputVarType = typename R::InputVarType; using FieldVariantType = rfl::Variant; using ResultType = Result; + using NameLookup = + FieldNameLookup::name_...>>; public: /** @@ -43,52 +98,40 @@ class FieldVariantReader { */ void read(const std::string_view& _disc_value, const InputVarType& _var) const noexcept { - if (*field_variant_) { + if (*field_variant_) [[unlikely]] { *field_variant_ = error( "Could not parse rfl::Variant: Expected the object to have " "exactly one field, but found more than one."); return; } - try_matching_fields( - _disc_value, _var, - std::make_integer_sequence()); - if (!*field_variant_) { - std::stringstream stream; - stream << "Could not parse rfl::Variant, could not match field named " - "'" - << _disc_value << "'."; - *field_variant_ = error(stream.str()); + const int idx = NameLookup::find_direct(_disc_value); + if (idx < 0) [[unlikely]] { + *field_variant_ = + error(make_field_variant_unknown_field_error(_disc_value)); + return; } + read_by_index(idx, _disc_value, _var, + std::make_integer_sequence()); } private: template - void try_matching_fields(const std::string_view& _disc_value, - const InputVarType& _var, - std::integer_sequence) const noexcept { - (try_one<_is>(_disc_value, _var), ...); - } - - template - void try_one(const std::string_view& _disc_value, - const InputVarType& _var) const noexcept { - using FieldType = - std::remove_cvref_t>; - using ValueType = std::remove_cvref_t; - constexpr auto key = FieldType::name_.string_view(); - if (key == _disc_value) { - const auto to_variant = [](ValueType&& _val) { - return rfl::Variant(FieldType(std::move(_val))); - }; - const auto embellish_error = [&](const Error& _e) { - std::stringstream stream; - stream << "Could not parse rfl::Variant with field '" - << std::string(_disc_value) << "': " << _e.what(); - return Error(stream.str()); - }; - *field_variant_ = Parser::read(*r_, _var) - .transform(to_variant) - .transform_error(embellish_error); + void read_by_index(const int _idx, const std::string_view _disc_value, + const InputVarType& _var, + std::integer_sequence) const noexcept { + std::optional err; + static_cast( + ((_idx == _is + ? (assign_field_variant_if_present( + field_variant_, + read_field_variant_alternative< + R, W, std::remove_cvref_t, ProcessorsType>( + *r_, _var, _disc_value, &err)), + true) + : false) || + ...)); + if (err) [[unlikely]] { + field_variant_->emplace(error(std::move(*err))); } } diff --git a/include/rfl/parsing/ParserTaggedUnion.hpp b/include/rfl/parsing/ParserTaggedUnion.hpp index dee232752..6a66d9627 100644 --- a/include/rfl/parsing/ParserTaggedUnion.hpp +++ b/include/rfl/parsing/ParserTaggedUnion.hpp @@ -1,20 +1,31 @@ #ifndef RFL_PARSING_PARSER_TAGGED_UNION_HPP_ #define RFL_PARSING_PARSER_TAGGED_UNION_HPP_ +#include +#include #include -#include +#include +#include +#include #include #include +#include +#include "../Literal.hpp" #include "../Result.hpp" #include "../TaggedUnion.hpp" -#include "../always_false.hpp" +#include "../internal/StringLiteral.hpp" +#include "../internal/always_inline.hpp" +#include "../internal/cold.hpp" +#include "../internal/has_fields.hpp" +#include "../internal/make_tag.hpp" #include "../internal/no_field_names_v.hpp" -#include "../internal/strings/strings.hpp" +#include "../internal/tag_t.hpp" #include "../named_tuple_t.hpp" #include "../visit.hpp" #include "Parser_base.hpp" #include "TaggedUnionWrapper.hpp" +#include "find_field_index.hpp" #include "is_tagged_union_wrapper.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" @@ -35,6 +46,285 @@ template constexpr bool is_tagged_union_v = is_tagged_union>::value; +template +struct TagLiteralStrings; + +template <> +struct TagLiteralStrings> { + static constexpr std::size_t count_ = 0; + static constexpr const std::string_view* data_ = nullptr; +}; + +template +struct TagLiteralStrings> { + static constexpr std::size_t count_ = sizeof...(_names); + static constexpr std::array names_ = { + _names.string_view()...}; + static constexpr const std::string_view* data_ = names_.data(); +}; + +RFL_COLD inline Error make_tagged_union_unknown_tag_error( + const std::string_view _discriminator_name, + const std::string_view _disc_value, const std::string_view* _allowed_tags, + const std::size_t _num_allowed) { + std::string msg; + msg.append("Could not parse tagged union, could not match "); + msg.append(_discriminator_name); + msg.append(" '"); + msg.append(_disc_value); + msg.append("'. The following tags are allowed: "); + for (std::size_t i = 0; i < _num_allowed; ++i) { + if (i > 0) { + msg.append(", "); + } + msg.append(_allowed_tags[i]); + } + return Error(std::move(msg)); +} + +RFL_COLD inline Error make_tagged_union_missing_discriminator_error( + const std::string_view _discriminator_name) { + std::string msg; + msg.reserve(96 + _discriminator_name.size()); + msg.append("Could not parse tagged union: Could not find field '"); + msg.append(_discriminator_name); + msg.append("' or type of field was not a string."); + return Error(std::move(msg)); +} + +RFL_COLD inline Error make_tagged_union_alternative_error( + const std::string_view _discriminator_name, + const std::string_view _disc_value, Error _e) { + std::string prefix; + prefix.reserve(56 + _discriminator_name.size() + _disc_value.size()); + prefix.append("Could not parse tagged union with discriminator "); + prefix.append(_discriminator_name); + prefix.append(" '"); + prefix.append(_disc_value); + prefix.append("': "); + return wrap_error(prefix, std::move(_e)); +} + +/// Compile-time tag lookup table built directly from each alternative's +/// `internal::tag_t<_discriminator, AlternativeType>` (supporting both single- +/// and multi-value `rfl::Literal` tags) without `define_literal` O(K^2) +/// template peeling. +template +struct TaggedUnionTagLookup { + struct TagGroup { + const std::string_view* data; + std::size_t size; + }; + + static constexpr std::size_t total_tags_ = + (std::size_t{0} + ... + TagLiteralStrings::count_); + + static constexpr std::array groups_ = { + TagGroup{TagLiteralStrings::data_, + TagLiteralStrings::count_}...}; + + static constexpr std::array + make_sorted_table() noexcept { + std::array table{}; + std::size_t pos = 0; + for (std::size_t alt = 0; alt < groups_.size(); ++alt) { + for (std::size_t j = 0; j < groups_[alt].size; ++j) { + table[pos++] = + FieldNameEntry{groups_[alt].data[j], static_cast(alt)}; + } + } + if constexpr (total_tags_ > 1) { + sort_field_name_table(table); + } + return table; + } + + static constexpr std::array + make_decl_names() noexcept { + std::array names{}; + std::size_t pos = 0; + for (std::size_t alt = 0; alt < groups_.size(); ++alt) { + for (std::size_t j = 0; j < groups_[alt].size; ++j) { + names[pos++] = groups_[alt].data[j]; + } + } + return names; + } + + static constexpr auto sorted_table_ = make_sorted_table(); + + static constexpr bool has_duplicates() noexcept { + for (std::size_t i = 1; i < total_tags_; ++i) { + if (sorted_table_[i].name == sorted_table_[i - 1].name) { + return true; + } + } + return false; + } + + static inline int find(const std::string_view _disc_value) noexcept { + return find_in_field_name_table(sorted_table_, _disc_value); + } + + static RFL_COLD Error make_unknown_tag_error( + const std::string_view _discriminator_name, + const std::string_view _disc_value) { + if constexpr (total_tags_ == 0) { + return make_tagged_union_unknown_tag_error(_discriminator_name, + _disc_value, nullptr, 0); + } else { + static constexpr auto decl_names = make_decl_names(); + return make_tagged_union_unknown_tag_error( + _discriminator_name, _disc_value, decl_names.data(), + decl_names.size()); + } + } +}; + +/// Retrieves the discriminator string from a tagged union input object/array. +/// Parameterized only by `(R, _discriminator, _no_field_names)` — never +/// `AlternativeTypes...`. +template +inline Result get_tagged_union_discriminator( + const R& _r, const typename R::InputVarType& _var) noexcept { + if constexpr (_no_field_names) { + auto arr = _r.to_array(_var); + if (!arr) [[unlikely]] { + return error(std::move(arr).error()); + } + auto field = _r.get_field_from_array(0, *arr); + if (!field) [[unlikely]] { + return error(make_tagged_union_missing_discriminator_error( + _discriminator.string_view())); + } + auto disc = _r.template to_basic_type(*field); + if (!disc) [[unlikely]] { + return error(make_tagged_union_missing_discriminator_error( + _discriminator.string_view())); + } + return std::move(*disc); + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return error(std::move(obj).error()); + } + auto field = _r.get_field_from_object(_discriminator.str(), *obj); + if (!field) [[unlikely]] { + return error(make_tagged_union_missing_discriminator_error( + _discriminator.string_view())); + } + auto disc = _r.template to_basic_type(*field); + if (!disc) [[unlikely]] { + return error(make_tagged_union_missing_discriminator_error( + _discriminator.string_view())); + } + return std::move(*disc); + } +} + +/// Computes the wrapped (or unwrapped) representation type for one tagged union +/// alternative without requiring `T` to be copy-constructible. +template +struct tagged_union_wrapped_type { + static auto deduce() { + if constexpr (named_tuple_t::Names::template contains< + _discriminator>()) { + return std::type_identity{}; + } else { + using TagType = std::remove_cvref_t>; + if constexpr (internal::has_fields>()) { + return std::type_identity< + TaggedUnionWrapperWithFields>{}; + } else { + return std::type_identity< + TaggedUnionWrapperNoFields>{}; + } + } + } + + using Type = typename decltype(deduce())::type; +}; + +/// Reads one tagged union alternative. Parameterized only by +/// `(R, W, _discriminator, AlternativeType, ProcessorsType)` — never the +/// enclosing `AlternativeTypes...` pack. +template +inline std::optional> +read_tagged_union_alternative(const R& _r, const std::string_view _disc_value, + const typename R::InputVarType& _var, + std::optional* _err) noexcept { + using CleanAltType = std::remove_cvref_t; + using WrappedType = tagged_union_wrapper_no_ptr_t< + typename tagged_union_wrapped_type<_discriminator, CleanAltType>::Type>; + auto res = Parser::read(_r, _var); + if (!res) [[unlikely]] { + _err->emplace(make_tagged_union_alternative_error( + _discriminator.string_view(), _disc_value, std::move(res).error())); + return std::nullopt; + } + if constexpr (is_tagged_union_wrapper_v) { + return std::optional(std::in_place, + std::move((*res).fields())); + } else { + return std::optional(std::in_place, std::move(*res)); + } +} + +template +RFL_ALWAYS_INLINE void assign_tagged_union_if_present( + std::optional* _out, + std::optional&& _val) noexcept { + if (_val) [[likely]] { + _out->emplace(std::move(*_val)); + } +} + +/// Namespace-scope visitor for writing one tagged union alternative, +/// parameterized only by `(R, W, _discriminator, ProcessorsType, P)` and the +/// active alternative `T` — never `AlternativeTypes...`. +template +struct TaggedUnionWriter { + const W& w_; + const P& parent_; + + template + void operator()(const T& _val) const { + if constexpr (named_tuple_t::Names::template contains< + _discriminator>()) { + // The object already contains the tag, so it can be written as it is, + // without the copy that wrapping would make. + Parser::write(w_, _val, parent_); + } else { + const auto tag = internal::make_tag<_discriminator, T>(_val); + using TagType = std::remove_cvref_t; + if constexpr (internal::has_fields>()) { + using WrapperType = + TaggedUnionWrapperWithFields; + const auto wrapped = WrapperType{.tag = tag, .fields = &_val}; + Parser::write(w_, wrapped, parent_); + } else { + using WrapperType = + TaggedUnionWrapperNoFields; + const auto wrapped = WrapperType{.tag = tag, .fields = &_val}; + Parser::write(w_, wrapped, parent_); + } + } + } +}; + +/// Namespace-scope schema builder for one tagged union alternative, +/// parameterized only by `(R, W, _discriminator, AlternativeType, ProcessorsType)`. +template +inline schema::Type tagged_union_alternative_to_schema( + std::map* _definitions) noexcept { + using WrappedType = + typename tagged_union_wrapped_type<_discriminator, AlternativeType>::Type; + return Parser::to_schema(_definitions); +} + template struct ParserTaggedUnion; @@ -44,7 +334,8 @@ template > struct ParserTaggedUnion, ProcessorsType> { - using ResultType = Result>; + using TaggedUnionType = TaggedUnion<_discriminator, AlternativeTypes...>; + using ResultType = Result; public: using InputObjectType = typename R::InputObjectType; @@ -66,31 +357,24 @@ struct ParserTaggedUnion, */ static ResultType read(const R& _r, const InputVarType& _var) noexcept { if constexpr (schemaful::IsSchemafulReader) { - return Parser, ProcessorsType>::read( - _r, _var) - .transform([](auto&& _variant) { - return TaggedUnion<_discriminator, AlternativeTypes...>( - std::move(_variant)); - }); + auto res = + Parser, ProcessorsType>::read( + _r, _var); + if (!res) [[unlikely]] { + return error(std::move(res).error()); + } + return TaggedUnionType(std::move(*res)); } else { - const auto get_disc = - [&_r](InputObjectOrArrayType _obj_or_arr) -> Result { - return get_discriminator(_r, _obj_or_arr); - }; - - const auto to_result = - [&_r, _var](const std::string& _disc_value) -> ResultType { - return find_matching_alternative( - _r, _disc_value, _var, - std::make_integer_sequence()); - }; - - if constexpr (no_field_names_) { - return _r.to_array(_var).and_then(get_disc).and_then(to_result); - } else { - return _r.to_object(_var).and_then(get_disc).and_then(to_result); + auto disc = + get_tagged_union_discriminator( + _r, _var); + if (!disc) [[unlikely]] { + return error(std::move(disc).error()); } + return find_matching_alternative( + _r, *disc, _var, + std::make_integer_sequence()); } } @@ -103,16 +387,16 @@ struct ParserTaggedUnion, * @param _parent The parent object. */ template - static void write( - const W& _w, - const TaggedUnion<_discriminator, AlternativeTypes...>& _tagged_union, - const P& _parent) { + static void write(const W& _w, const TaggedUnionType& _tagged_union, + const P& _parent) { if constexpr (schemaful::IsSchemafulWriter) { Parser, ProcessorsType>::write( _w, _tagged_union.variant(), _parent); } else { - rfl::visit([&](const auto& _val) { write_wrapped(_w, _val, _parent); }, - _tagged_union.variant()); + rfl::visit( + TaggedUnionWriter{_w, + _parent}, + _tagged_union.variant()); } } @@ -129,151 +413,50 @@ struct ParserTaggedUnion, return Parser, ProcessorsType>::to_schema(_definitions); } else { - using VariantType = std::variant(std::declval())) - ...>; - return Parser::to_schema(_definitions); + std::vector types; + types.reserve(sizeof...(AlternativeTypes)); + (types.emplace_back( + tagged_union_alternative_to_schema( + _definitions)), + ...); + return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}}; } } private: template static ResultType find_matching_alternative( - const R& _r, const std::string& _disc_value, const InputVarType& _var, + const R& _r, const std::string_view _disc_value, const InputVarType& _var, std::integer_sequence) noexcept { - using PossibleTags = - possible_tags_t>; - static_assert(!PossibleTags::has_duplicates(), + using TagLookup = TaggedUnionTagLookup>...>; + static_assert(!TagLookup::has_duplicates(), "Duplicate tags are not allowed inside tagged unions."); - ResultType res = error(""); - bool match_found = false; - (set_if_disc_value_matches<_is>(_r, _disc_value, _var, &res, &match_found), - ...); - if (match_found) [[likely]] { - return res; - } else { - const auto names = PossibleTags::names(); - std::stringstream stream; - stream << "Could not parse tagged union, could not match " - << _discriminator.str() << " '" << _disc_value - << "'. The following tags are allowed: " - << internal::strings::join(", ", names); - return error(stream.str()); - } - } - - template - static void set_if_disc_value_matches(const R& _r, - const std::string& _disc_value, - const InputVarType& _var, - ResultType* _result, - bool* _match_found) { - using AlternativeType = std::remove_cvref_t< - std::variant_alternative_t<_i, std::variant>>; - - if (!*_match_found && contains_disc_value(_disc_value)) { - const auto get_fields = [](auto&& _val) -> AlternativeType { - if constexpr (is_tagged_union_wrapper_v) { - return std::move(_val.fields()); - } else { - return std::move(_val); - } - }; - - const auto to_tagged_union = [](auto&& _val) { - return TaggedUnion<_discriminator, AlternativeTypes...>( - std::move(_val)); - }; - - const auto embellish_error = [&](Error _e) { - std::stringstream stream; - stream << "Could not parse tagged union with " - "discriminator " - << _discriminator.str() << " '" << _disc_value << "': "; - return wrap_error(stream.str(), std::move(_e)); - }; - - using T = tagged_union_wrapper_no_ptr_t(std::declval() - ))>; - - *_result = Parser::read(_r, _var) - .transform(get_fields) - .transform(to_tagged_union) - .transform_error(embellish_error); - - *_match_found = true; - } - } - - /// Retrieves the discriminator from an object - static Result get_discriminator( - const R& _r, const InputObjectOrArrayType& _obj_or_arr) noexcept { - const auto to_type = [&_r](auto _var) { - return _r.template to_basic_type(_var); - }; - - const auto embellish_error = [](const auto&) { - std::stringstream stream; - stream << "Could not parse tagged union: Could not find field '" - << _discriminator.str() << "' or type of field was not a string."; - return Error(stream.str()); - }; - - if constexpr (no_field_names_) { - return _r.get_field_from_array(0, _obj_or_arr) - .and_then(to_type) - .transform_error(embellish_error); - } else { - return _r.get_field_from_object(_discriminator.str(), _obj_or_arr) - .and_then(to_type) - .transform_error(embellish_error); + const int idx = TagLookup::find(_disc_value); + std::optional val; + std::optional err; + if (idx >= 0) [[likely]] { + static_cast( + ((idx == _is + ? (assign_tagged_union_if_present( + &val, + read_tagged_union_alternative< + R, W, _discriminator, + std::remove_cvref_t, + ProcessorsType>(_r, _disc_value, _var, &err)), + true) + : false) || + ...)); } - } - - /// Determines whether the discriminating literal contains the value - /// retrieved from the object. - template - static inline bool contains_disc_value( - const std::string& _disc_value) noexcept { - return internal::tag_t<_discriminator, T>::contains(_disc_value); - } - - /// Writes a wrapped version of the original object, which contains the tag. - template - static void write_wrapped(const W& _w, const T& _val, const P& _parent) { - if constexpr (named_tuple_t::Names::template contains< - _discriminator>()) { - // The object already contains the tag, so it can be written as it is, - // without the copy that wrap_if_necessary would make. - Parser::write(_w, _val, _parent); - } else { - const auto wrapped = wrap_if_necessary(_val); - Parser, - ProcessorsType>::write(_w, wrapped, _parent); + if (val) [[likely]] { + return std::move(*val); } - } - - /// Generates a wrapped version of the original object, which contains the - /// tag, if the object doesn't already contain the wrap. - template - static auto wrap_if_necessary(const T& _val) { - if constexpr (named_tuple_t::Names::template contains< - _discriminator>()) { - return _val; - } else { - const auto tag = internal::make_tag<_discriminator, T>(_val); - using TagType = std::remove_cvref_t; - if constexpr (internal::has_fields>()) { - using WrapperType = - TaggedUnionWrapperWithFields; - return WrapperType{.tag = tag, .fields = &_val}; - } else { - using WrapperType = - TaggedUnionWrapperNoFields; - return WrapperType{.tag = tag, .fields = &_val}; - } + if (err) [[unlikely]] { + return error(std::move(*err)); } + return error(TagLookup::make_unknown_tag_error(_discriminator.string_view(), + _disc_value)); } }; diff --git a/include/rfl/parsing/find_field_index.hpp b/include/rfl/parsing/find_field_index.hpp index dd4827390..7982591e1 100644 --- a/include/rfl/parsing/find_field_index.hpp +++ b/include/rfl/parsing/find_field_index.hpp @@ -93,6 +93,43 @@ constexpr void sort_field_name_table( } } +/// Looks up `_name` in a `FieldNameEntry` table (linear scan with +/// `field_name_equals` for small tables `<= 8`, binary search on a sorted +/// table for `> 8`), returning the matching `field_idx` or `-1` if not found. +inline int find_in_field_name_table(const std::array&, + const std::string_view) noexcept { + return -1; +} + +template +inline int find_in_field_name_table( + const std::array& _table, + const std::string_view _name) noexcept { + if constexpr (_n <= 8) { + for (std::size_t i = 0; i < _n; ++i) { + if (field_name_equals(_table[i].name, _name)) { + return _table[i].field_idx; + } + } + return -1; + } else { + std::size_t lo = 0; + std::size_t hi = _n; + 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 < _n && field_name_equals(_table[lo].name, _name)) { + return _table[lo].field_idx; + } + return -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 @@ -105,6 +142,8 @@ struct FieldNameLookup> { static constexpr std::size_t size_ = 0; static constexpr std::array decl_names_{}; + static inline int find_direct(const std::string_view) noexcept { return -1; } + static RFL_COLD int find(const std::string_view) noexcept { return -1; } static RFL_ALWAYS_INLINE int find_with_hint(const std::string_view, @@ -133,7 +172,7 @@ struct FieldNameLookup> { return table; } - static RFL_COLD int find(const std::string_view _name) noexcept { + static inline int find_direct(const std::string_view _name) noexcept { if constexpr (size_ <= 8) { for (std::size_t i = 0; i < size_; ++i) { if (field_name_equals(decl_names_[i], _name)) { @@ -143,23 +182,14 @@ struct FieldNameLookup> { return -1; } else { static constexpr auto table = make_table(); - 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() && field_name_equals(table[lo].name, _name)) { - return table[lo].field_idx; - } - return -1; + return find_in_field_name_table(table, _name); } } + static RFL_COLD int find(const std::string_view _name) noexcept { + return find_direct(_name); + } + static RFL_ALWAYS_INLINE int find_with_hint(const std::string_view _name, std::size_t& _next_idx) noexcept { if (_next_idx < size_ && field_name_equals(decl_names_[_next_idx], _name))