Skip to content

Commit

Permalink
feat(ffi): Add type checking to only accept JSON objects as user-defi…
Browse files Browse the repository at this point in the history
…ned stream-level metadata for the new IR format. (#691)

Co-authored-by: kirkrodrigues <[email protected]>
  • Loading branch information
LinZhihao-723 and kirkrodrigues authored Jan 24, 2025
1 parent 230d518 commit b80f756
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
3 changes: 3 additions & 0 deletions components/core/src/clp/ffi/ir_stream/Serializer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,9 @@ auto Serializer<encoded_variable_t>::create(
cVariableEncodingMethodsVersion
);
if (optional_user_defined_metadata.has_value()) {
if (false == optional_user_defined_metadata.value().is_object()) {
return std::errc::protocol_not_supported;
}
metadata.emplace(
string{cProtocol::Metadata::UserDefinedMetadataKey},
std::move(optional_user_defined_metadata.value())
Expand Down
6 changes: 4 additions & 2 deletions components/core/src/clp/ffi/ir_stream/Serializer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ class Serializer {
// Factory functions
/**
* Creates an IR serializer and serializes the stream's preamble.
* @param optional_user_defined_metadata Stream-level user-defined metadata.
* @param optional_user_defined_metadata Stream-level user-defined metadata, given as a JSON
* object.
* @return A result containing the serializer or an error code indicating the failure:
* - std::errc::protocol_error on failure to serialize the preamble.
* - std::errc::protocol_error if the stream's metadata couldn't be serialized.
* - std::errc::protocol_not_supported if the given user-defined metadata is not a JSON object.
*/
[[nodiscard]] static auto create(
std::optional<nlohmann::json> optional_user_defined_metadata = std::nullopt
Expand Down
20 changes: 20 additions & 0 deletions components/core/tests/test-ir_encoding_methods.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1494,3 +1494,23 @@ TEMPLATE_TEST_CASE(
};
REQUIRE(assert_invalid_serialization(array_with_invalid_submap));
}

// NOLINTNEXTLINE(readability-function-cognitive-complexity)
TEMPLATE_TEST_CASE(
"ffi_ir_stream_Serializer_serialize_invalid_user_defined_metadata",
"[clp][ffi][ir_stream][Serializer]",
four_byte_encoded_variable_t,
eight_byte_encoded_variable_t
) {
auto invalid_user_defined_metadata = GENERATE(
nlohmann::json(std::string{"str"}),
nlohmann::json(int{0}),
nlohmann::json(double{0.0}),
nlohmann::json(true),
nlohmann::json(nullptr),
nlohmann::json(vector<int>{0, 1, 2})
);
auto const serializer_result{Serializer<TestType>::create(invalid_user_defined_metadata)};
REQUIRE(serializer_result.has_error());
REQUIRE((std::errc::protocol_not_supported == serializer_result.error()));
}

0 comments on commit b80f756

Please sign in to comment.