Skip to content
Open
Show file tree
Hide file tree
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
18 changes: 18 additions & 0 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ reflect-cpp currently supports the following processors:
- `rfl::DurationsAsCount`
- `rfl::EnumNamesOnly`
- `rfl::FailFast`
- `rfl::NoDuplicateKeys`
- `rfl::NoExtraFields`
- `rfl::NoFieldNames`
- `rfl::NoOptionals`
Expand Down Expand Up @@ -366,6 +367,23 @@ Failed to parse field 'color': Invalid enum value: '2'. Must be one of [red, gre
This processor only affects reading. Enum values that cannot be matched to
a declared name are still written as their integer representation.

### `rfl::NoDuplicateKeys`

By default, `rfl::json::read` and `rfl::yaml::read` keep their existing behavior
when an input object or mapping contains repeated keys. Pass
`rfl::NoDuplicateKeys` to reject duplicate keys and report each repeated key as
an error. Works across structs, maps, `rfl::Object`, `rfl::Generic`,
`rfl::FieldVariant`, and `rfl::TaggedUnion`. Passing `rfl::NoDuplicateKeys` to a
reader that does not support duplicate-key detection fails at compile time
(`static_assert`):

```cpp
const auto json_res =
rfl::json::read<Config, rfl::NoExtraFields, rfl::NoDuplicateKeys>(json_str);
const auto yaml_res =
rfl::yaml::read<Config, rfl::NoExtraFields, rfl::NoDuplicateKeys>(yaml_str);
```

### `rfl::NoExtraFields`

When reading an object and the object contains a field that cannot be
Expand Down
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#include "rfl/Hex.hpp"
#include "rfl/Literal.hpp"
#include "rfl/NamedTuple.hpp"
#include "rfl/NoDuplicateKeys.hpp"
#include "rfl/NoExtraFields.hpp"
#include "rfl/NoFieldNames.hpp"
#include "rfl/NoOptionals.hpp"
Expand Down
25 changes: 25 additions & 0 deletions include/rfl/NoDuplicateKeys.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#ifndef RFL_NODUPLICATEKEYS_HPP_
#define RFL_NODUPLICATEKEYS_HPP_

#include <utility>

namespace rfl {

/// Reject duplicate keys in input objects/mappings for readers that support
/// duplicate-key detection (JSON and YAML).
///
/// By default, duplicate keys keep existing reader behavior for backwards
/// compatibility. Pass rfl::NoDuplicateKeys to report each repeated key as an
/// error:
/// rfl::json::read<MyStruct, rfl::NoExtraFields, rfl::NoDuplicateKeys>(json)
/// rfl::yaml::read<MyStruct, rfl::NoExtraFields, rfl::NoDuplicateKeys>(yaml)
struct NoDuplicateKeys {
template <class StructType>
static auto process(auto&& _named_tuple) {
return std::forward<decltype(_named_tuple)>(_named_tuple);
}
};

} // namespace rfl

#endif
36 changes: 36 additions & 0 deletions include/rfl/internal/no_duplicate_keys_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#ifndef RFL_INTERNAL_NODUPLICATEKEYS_HPP_
#define RFL_INTERNAL_NODUPLICATEKEYS_HPP_

#include <type_traits>

#include "../NoDuplicateKeys.hpp"
#include "../Processors.hpp"

namespace rfl::internal {

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

template <>
struct no_duplicate_keys<NoDuplicateKeys> : std::true_type {};

template <class... Ps>
struct no_duplicate_keys<Processors<Ps...>>
: std::bool_constant<(no_duplicate_keys<Ps>::value || ...)> {};

template <class T>
inline constexpr bool no_duplicate_keys_v =
no_duplicate_keys<std::remove_cvref_t<T>>::value;

template <class R>
inline constexpr bool reader_supports_no_duplicate_keys_v = []() constexpr {
if constexpr (requires { R::supports_no_duplicate_keys; }) {
return static_cast<bool>(R::supports_no_duplicate_keys);
} else {
return false;
}
}();

} // namespace rfl::internal

#endif
55 changes: 50 additions & 5 deletions include/rfl/json/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_set>
#include <utility>
#include <vector>

#include "../Bytestring.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/base64.hpp"
#include "../parsing/to_single_error_message.hpp"
#include "../parsing/wrap_error.hpp"

namespace rfl {
namespace json {
Expand Down Expand Up @@ -60,6 +65,9 @@ struct Reader {
static constexpr bool has_custom_constructor =
(requires(InputVarType var) { T::from_json_obj(var); });

/// Advertises support for the opt-in rfl::NoDuplicateKeys processor.
static constexpr bool supports_no_duplicate_keys = true;

/// Retrieves an element from a JSON array by index.
/// @param _idx The zero-based index of the element to retrieve
/// @param _arr The JSON array to read from
Expand Down Expand Up @@ -132,12 +140,39 @@ struct Reader {
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const auto name =
std::string_view(yyjson_get_str(key), yyjson_get_len(key));
_object_reader.read(name, InputVarType(yyjson_obj_iter_get_val(key)));
if constexpr (is_no_duplicate_keys<ObjectReader>()) {
std::unordered_set<std::string_view> seen_keys;
seen_keys.reserve(yyjson_obj_size(_obj.val_));
std::vector<Error> duplicate_errors;
while ((key = yyjson_obj_iter_next(&iter))) {
const auto name =
std::string_view(yyjson_get_str(key), yyjson_get_len(key));
if (!seen_keys.insert(name).second) {
auto dup_err = parsing::make_nested_error(
std::string(name), "Duplicate key '" + std::string(name) + "'.");
if constexpr (requires {
_object_reader.add_error(std::move(dup_err));
}) {
_object_reader.add_error(std::move(dup_err));
} else {
duplicate_errors.emplace_back(std::move(dup_err));
}
continue;
}
_object_reader.read(name, InputVarType(yyjson_obj_iter_get_val(key)));
}
if (!duplicate_errors.empty()) {
return parsing::to_single_error(std::move(duplicate_errors));
}
return std::nullopt;
} else {
while ((key = yyjson_obj_iter_next(&iter))) {
const auto name =
std::string_view(yyjson_get_str(key), yyjson_get_len(key));
_object_reader.read(name, InputVarType(yyjson_obj_iter_get_val(key)));
}
return std::nullopt;
}
return std::nullopt;
}

/// Converts a JSON value to a basic C++ type.
Expand Down Expand Up @@ -235,6 +270,16 @@ struct Reader {
return error(e.what());
}
}

private:
template <class ObjectReader>
static constexpr bool is_no_duplicate_keys() noexcept {
if constexpr (requires { ObjectReader::no_duplicate_keys; }) {
return ObjectReader::no_duplicate_keys;
} else {
return false;
}
}
};

} // namespace json
Expand Down
7 changes: 7 additions & 0 deletions include/rfl/parsing/FieldVariantReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/nth_element_t.hpp"
#include "Parser_base.hpp"

Expand All @@ -23,6 +24,12 @@ class FieldVariantReader {
using ResultType = Result<FieldVariantType>;

public:
static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

/**
* @brief Constructor.
*
Expand Down
15 changes: 15 additions & 0 deletions include/rfl/parsing/MapReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/has_reflection_type_v.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "Parser_base.hpp"
#include "wrap_error.hpp"

Expand All @@ -24,6 +25,12 @@ class MapReader {
std::remove_cvref_t<typename MapType::value_type::second_type>;

public:
static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

/**
* @brief Constructor.
*
Expand Down Expand Up @@ -52,6 +59,14 @@ class MapReader {
}
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const noexcept {
errors_->emplace_back(std::move(_err));
}

private:
template <class T>
Result<T> key_to_numeric(auto& _pair) const noexcept {
Expand Down
4 changes: 4 additions & 0 deletions include/rfl/parsing/Parser_default.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "../internal/is_description.hpp"
#include "../internal/is_literal.hpp"
#include "../internal/is_validator.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/processed_t.hpp"
#include "../internal/ptr_cast.hpp"
#include "../internal/to_ptr_named_tuple.hpp"
Expand Down Expand Up @@ -92,6 +93,9 @@ struct Parser {
* @return A Result containing the parsed value or an error.
*/
static RFL_ALWAYS_INLINE auto read(const R& _r, const InputVarType& _var) {
static_assert(!internal::no_duplicate_keys_v<ProcessorsType> ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");
if constexpr (internal::is_basic_type_v<T>) {
return ParserBasicType<R, W, T, ProcessorsType>::read(_r, _var);

Expand Down
17 changes: 17 additions & 0 deletions include/rfl/parsing/ViewReader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../Tuple.hpp"
#include "../internal/always_inline.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/no_extra_fields_v.hpp"
#include "FieldErrors.hpp"
#include "Parser_base.hpp"
Expand All @@ -25,6 +26,12 @@ class ViewReader {
using InputVarType = typename R::InputVarType;
using ViewType = _ViewType;

static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

static constexpr size_t size_ = ViewType::size();

/**
Expand Down Expand Up @@ -55,6 +62,16 @@ class ViewReader {
std::make_integer_sequence<int, size_>());
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const {
if (should_stop_on_field_error<ProcessorsType>(*errors_)) return;
errors_->reserve(size_);
errors_->emplace_back(std::move(_err));
}

/**
* @brief Reads a single field into the view.
*
Expand Down
16 changes: 16 additions & 0 deletions include/rfl/parsing/ViewReaderWithDefault.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../Ref.hpp"
#include "../Tuple.hpp"
#include "../internal/is_array.hpp"
#include "../internal/no_duplicate_keys_v.hpp"
#include "../internal/no_extra_fields_v.hpp"
#include "FieldErrors.hpp"
#include "Parser_base.hpp"
Expand All @@ -24,6 +25,12 @@ class ViewReaderWithDefault {
using InputVarType = typename R::InputVarType;
using ViewType = _ViewType;

static constexpr bool no_duplicate_keys =
internal::no_duplicate_keys_v<ProcessorsType>;
static_assert(!no_duplicate_keys ||
internal::reader_supports_no_duplicate_keys_v<R>,
"rfl::NoDuplicateKeys is not supported by this reader.");

static constexpr size_t size_ = ViewType::size();

/**
Expand Down Expand Up @@ -60,6 +67,15 @@ class ViewReaderWithDefault {
std::make_integer_sequence<int, size_>());
}

/**
* @brief Records a field-level error reported directly by the reader (for
* example, a duplicate key).
*/
void add_error(Error&& _err) const {
if (should_stop_on_field_error<ProcessorsType>(*errors_)) return;
errors_->emplace_back(std::move(_err));
}

/**
* @brief Returns the size of the view.
*
Expand Down
Loading
Loading