Using std::array instead of std::vector for retrieving the fields

This commit is contained in:
Patrick Urbanke
2023-10-15 14:29:41 +02:00
parent 383dde14f5
commit 4c020e7e82
2 changed files with 16 additions and 12 deletions
+6 -4
View File
@@ -3,6 +3,7 @@
#include <yyjson.h>
#include <array>
#include <exception>
#include <map>
#include <memory>
@@ -102,10 +103,11 @@ struct Reader {
return InputArrayType(_var->val_);
}
std::vector<std::optional<InputVarType>> to_fields_vec(
template <size_t size>
std::array<std::optional<InputVarType>, size> to_fields_array(
const std::unordered_map<std::string_view, size_t>& _field_indices,
InputObjectType* _obj) const noexcept {
std::vector<std::optional<InputVarType>> f_vec(_field_indices.size());
std::array<std::optional<InputVarType>, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj->val_, &iter);
yyjson_val* key;
@@ -113,10 +115,10 @@ struct Reader {
const char* k = yyjson_get_str(key);
const auto it = _field_indices.find(std::string_view(k, strlen(k)));
if (it != _field_indices.end()) {
f_vec[it->second] = InputVarType(yyjson_obj_iter_get_val(key));
f_arr[it->second] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_vec;
return f_arr;
}
std::map<std::string, InputVarType> to_map(
+10 -8
View File
@@ -351,13 +351,14 @@ struct Parser<ReaderType, WriterType, NamedTuple<FieldTypes...>> {
/// Generates a NamedTuple from a JSON Object.
static Result<NamedTuple<FieldTypes...>> read(const ReaderType& _r,
InputVarType* _var) noexcept {
const auto to_fields_vec = [&](auto _obj) {
return _r.to_fields_vec(field_indices(), &_obj);
const auto to_fields_array = [&](auto _obj) {
return _r.template to_fields_array<sizeof...(FieldTypes)>(
field_indices(), &_obj);
};
const auto build = [&](auto _fields_vec) {
return build_named_tuple_recursively(_r, _fields_vec);
};
return _r.to_object(_var).transform(to_fields_vec).and_then(build);
return _r.to_object(_var).transform(to_fields_array).and_then(build);
}
/// Transforms a NamedTuple into a JSON object.
@@ -373,19 +374,20 @@ struct Parser<ReaderType, WriterType, NamedTuple<FieldTypes...>> {
template <class... Args>
static Result<NamedTuple<FieldTypes...>> build_named_tuple_recursively(
const ReaderType& _r,
const std::vector<std::optional<InputVarType>>& _fields_vec,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_vec,
Args&&... _args) noexcept {
const auto size = sizeof...(Args);
constexpr auto i = sizeof...(Args);
if constexpr (size == sizeof...(FieldTypes)) {
if constexpr (i == sizeof...(FieldTypes)) {
return NamedTuple<FieldTypes...>(std::move(_args)...);
} else {
using FieldType = typename std::tuple_element<
size, typename NamedTuple<FieldTypes...>::Fields>::type;
i, typename NamedTuple<FieldTypes...>::Fields>::type;
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = _fields_vec[size];
const auto& f = std::get<i>(_fields_vec);
if (!f) {
if constexpr (is_required<ValueType>()) {