diff --git a/.gitignore b/.gitignore index ac3e020b..abddd157 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.swp # Build directory build/ +install/ # Visual Studio user configuration files. *.vcxproj.user *.sdf diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index b85bf12b..ded8b543 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -390,6 +391,33 @@ class Cdr return *this; } + /*! + * @brief Decodes a value that determines how the rest of the stream is read, such as a length, a DHEADER, a + * member header, a presence flag or a union discriminator. + * + * The elements of a sequence or map that do not fit in the destination, when a + * @ref CdrTryConstructFlag::DEFAULT_VALUE or @ref CdrTryConstructFlag::TRIM policy is applied, are consumed + * from the stream without storing their decoded values. Values like the ones above are needed to know how many + * bytes those elements occupy, so they must be stored anyway. The regular @c deserialize overloads do not store + * them in that situation; this function always does. + * + * Fast CDR uses it for the values it decodes itself. Code decoding a type whose layout depends on a value it + * reads, like the discriminator of a union, must decode that value with this function instead of + * @c deserialize or @c operator>> , so the type is consumed correctly when it is discarded. + * + * @param[out] value Reference to the variable where the decoded value will be stored. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to decode from a buffer + * position that exceeds the internal memory size. + */ + template + Cdr& deserialize_framing( + _T& value) + { + fake_mode_scope storing {*this, false}; + return deserialize(value); + } + /*! * @brief Encodes the value of a type into the buffer. * @@ -1761,6 +1789,35 @@ class Cdr Cdr_DllAPI Cdr& deserialize( char*& string_t); + /*! + * @brief This function deserializes a string applying a type consistency policy when the + * string read does not fit in the supplied @p max_length . + * + * This function allocates memory to store the string, which the user has to free using free(). An empty + * serialized string sets @p string_t to @c nullptr without allocating, as the overload without a policy does. + * + * Except when an exception is thrown, the whole string is consumed from the stream. If an exception is thrown, + * the stream is left where it was before the call. + * + * If the string is longer than @p max_length characters (the terminating null character, when + * the encoder serialized one, is not counted): + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException , leaving @p string_t unchanged. + * - @ref CdrTryConstructFlag::DEFAULT_VALUE allocates an empty string. + * - @ref CdrTryConstructFlag::TRIM reads until position @p max_length so the string is truncated to @p max_length characters. + * + * @param[out] string_t The pointer that will point to the string read from the buffer. + * @param[in] consistency_flag Policy applied when the string read does not fit in @p max_length . + * @param[in] max_length Maximum visible length accepted for the destination string. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . + */ + Cdr_DllAPI Cdr& deserialize( + char*& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length); + /*! * @brief This function deserializes a wide-string. * This function allocates memory to store the wide string. The user pointer will be set to point this allocated memory. @@ -1772,6 +1829,35 @@ class Cdr Cdr_DllAPI Cdr& deserialize( wchar_t*& string_t); + /*! + * @brief This function deserializes a wide-string applying a type consistency policy when the + * wide string read does not fit in the supplied @p max_length . + * + * This function allocates memory to store the wide string, which the user has to free using free(). An empty + * serialized string sets @p string_t to @c nullptr without allocating, as the overload without a policy does. + * + * Except when an exception is thrown, the whole string is consumed from the stream. If an exception is thrown, + * the stream is left where it was before the call. + * + * If the number of wide characters read is larger than @p max_length (unlike narrow strings, no + * terminating null character is serialized, so every character read is counted): + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException , leaving @p string_t unchanged. + * - @ref CdrTryConstructFlag::DEFAULT_VALUE allocates an empty string. + * - @ref CdrTryConstructFlag::TRIM reads at position @p max_length so the visible string is truncated to @p max_length characters. + * + * @param[out] string_t The pointer that will point to the wide string read from the buffer. + * @param[in] consistency_flag Policy applied when the string read does not fit in @p max_length . + * @param[in] max_length Maximum visible length accepted for the destination wide string. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . + */ + Cdr_DllAPI Cdr& deserialize( + wchar_t*& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length); + /*! * @brief This function deserializes a std::string. * @param string_t The variable that will store the string read from the buffer. @@ -1782,8 +1868,40 @@ class Cdr Cdr& deserialize( std::string& string_t) { - uint32_t length = 0; - const char* str = read_string(length); + uint32_t length {(std::numeric_limits::max)()}; + const char* str = read_string(length, CdrTryConstructFlag::FAIL); + string_t.assign(str, length); + return *this; + } + + /*! + * @brief This function deserializes a std::string applying a type consistency policy when + * the string read does not fit in the supplied @p max_length . + * + * Except when an exception is thrown, the whole string is consumed from the stream. If an exception is thrown, + * the stream is left where it was before the call. + * + * If the string read is longer than @p max_length characters, not counting the terminating null character + * when the encoder serialized one: + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE clears @p string_t . + * - @ref CdrTryConstructFlag::TRIM resizes @p string_t to @p max_length . + * + * @param[out] string_t The variable that will store the string read from the buffer. + * @param[in] consistency_flag Policy applied when the string read does not fit in @p max_length . + * @param[in] max_length Maximum length accepted for the destination string. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . + */ + Cdr& deserialize( + std::string& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + uint32_t length {max_length}; + const char* str = read_string(length, consistency_flag); string_t.assign(str, length); return *this; } @@ -1798,8 +1916,39 @@ class Cdr Cdr& deserialize( std::wstring& string_t) { - uint32_t length = 0; - string_t = read_wstring(length); + uint32_t length {(std::numeric_limits::max)()}; + string_t = read_wstring(length, CdrTryConstructFlag::FAIL); + return *this; + } + + /*! + * @brief This function deserializes a std::wstring applying a type consistency policy when + * the wide string read does not fit in the supplied @p max_length . + * + * Except when an exception is thrown, the whole string is consumed from the stream. If an exception is thrown, + * the stream is left where it was before the call. + * + * If the number of wide characters read is larger than @p max_length (no terminating null character is + * serialized, so every character counts): + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE clears @p string_t . + * - @ref CdrTryConstructFlag::TRIM resizes @p string_t to @p max_length . + * + * @param[out] string_t The variable that will store the wide string read from the buffer. + * @param[in] consistency_flag Policy applied when the string read does not fit in @p max_length . + * @param[in] max_length Maximum length accepted for the destination wide string. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . + */ + Cdr& deserialize( + std::wstring& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + uint32_t length {max_length}; + string_t = read_wstring(length, consistency_flag); return *this; } @@ -1814,8 +1963,42 @@ class Cdr Cdr& deserialize( fixed_string& value) { - uint32_t length = 0; - const char* str = read_string(length); + uint32_t length {MAX_CHARS}; + const char* str = read_string(length, CdrTryConstructFlag::FAIL); + value.assign(str, length); + return *this; + } + + /*! + * @brief Decodes a fixed string applying a type consistency policy when the deserialized + * string does not fit in @c MAX_CHARS . + * + * Except when an exception is thrown, the whole string is consumed from the stream. If an exception is thrown, + * the stream is left where it was before the call. + * + * When the number of characters read, excluding the terminating null character, is larger than + * @c MAX_CHARS : + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE resets @p value to an empty fixed_string. + * - @ref CdrTryConstructFlag::TRIM keeps the first @c MAX_CHARS characters. This is the + * only overload able to truncate: the regular @c deserialize(fixed_string&) + * applies @ref CdrTryConstructFlag::FAIL and throws instead. + * + * @param[out] value Reference to the variable where the fixed string will be stored after decoding from the buffer. + * @param[in] consistency_flag Policy applied when the deserialized string does not fit in @c MAX_CHARS . + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to decode from a buffer + * position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the deserialized string does not fit in @c MAX_CHARS . + */ + template + Cdr& deserialize( + fixed_string& value, + CdrTryConstructFlag consistency_flag) + { + uint32_t length {MAX_CHARS}; + const char* str = read_string(length, consistency_flag); value.assign(str, length); return *this; } @@ -1835,7 +2018,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_ && !is_multi_array_primitive(&array_t)) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if ((end_ - offset_) < dheader) { @@ -1893,7 +2076,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -1905,7 +2088,7 @@ class Cdr auto last_offset = offset_; last_offset += dheader; - deserialize(sequence_length); + deserialize_framing(sequence_length); if (0 == sequence_length) { @@ -1946,7 +2129,7 @@ class Cdr } else { - deserialize(sequence_length); + deserialize_framing(sequence_length); if (sequence_length == 0) { @@ -1990,7 +2173,7 @@ class Cdr uint32_t sequence_length = 0; state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); if (sequence_length == 0) { @@ -2029,7 +2212,289 @@ class Cdr Cdr& deserialize( std::vector& vector_t) { - return deserialize_bool_sequence(vector_t); + return deserialize_bool_sequence(vector_t, CdrTryConstructFlag::FAIL, + (std::numeric_limits::max)()); + } + + /*! + * @brief This function template deserializes a sequence of primitives or enumerations applying a type consistency policy + * when the serialized length exceeds the supplied @p max_length . + * + * If the serialized sequence has more than @p max_length elements: + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE leaves @p vector_t empty. + * - @ref CdrTryConstructFlag::TRIM keeps the first @p max_length elements. + * + * Except when an exception is thrown, the whole sequence is consumed from the stream, including the elements + * that are discarded. If an exception is thrown, the stream is left where it was before the call. + * + * @param[out] vector_t The variable that will store the sequence read from the buffer. + * @param[in] consistency_flag Policy applied when the serialized length exceeds @p max_length . + * @param[in] max_length Maximum length accepted for the destination sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the serialized length exceeds @p max_length . + */ + template::value || + std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::vector<_T>& vector_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + uint32_t sequence_length = 0; + state state_before_error(*this); + + deserialize_framing(sequence_length); + + vector_t.clear(); + + if (sequence_length == 0) + { + return *this; + } + + if ((end_ - offset_) < sequence_length) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + uint32_t length_to_read {sequence_length}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + vector_t.resize(length_to_read); + + try + { + deserialize_array(vector_t.data(), length_to_read); + + // Consume the elements that do not fit in the destination. They are read into a + // discarded object instead of the destination, which may be shorter or empty. + if (sequence_length > length_to_read) + { + fake_mode_scope discarding {*this, true}; + + for (uint32_t count {length_to_read}; count < sequence_length; ++count) + { + _T discarded; + deserialize(discarded); + } + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template deserializes a sequence of non-primitive elements applying a type consistency policy + * when the serialized length exceeds the supplied @p max_length . + * + * If the serialized sequence has more than @p max_length elements: + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE leaves @p vector_t empty. + * - @ref CdrTryConstructFlag::TRIM keeps the first @p max_length elements. + * + * Except when an exception is thrown, the whole sequence is consumed from the stream, including the elements + * that are discarded. If an exception is thrown, the stream is left where it was before the call. + * + * @param[out] vector_t The variable that will store the sequence read from the buffer. + * @param[in] consistency_flag Policy applied when the serialized length exceeds @p max_length . + * @param[in] max_length Maximum length accepted for the destination sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the serialized length exceeds @p max_length , or when + * the elements read do not match the size given by the DHEADER. + */ + template::value && + !std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::vector<_T>& vector_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + uint32_t sequence_length {0}; + state state_before_error(*this); + + if (CdrVersion::XCDRv2 == cdr_version_) + { + uint32_t dheader {0}; + deserialize_framing(dheader); + + if (((end_ - offset_) < dheader) || (dheader < 4)) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + auto offset = offset_; + + deserialize_framing(sequence_length); + + vector_t.clear(); + + if ((dheader - static_cast(offset_ - offset)) < sequence_length) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + uint32_t length_to_read {sequence_length}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + uint32_t count {0}; + + try + { + vector_t.resize(length_to_read); + + while (offset_ - offset < dheader && count < length_to_read) + { + deserialize(vector_t.data()[count]); + ++count; + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + + // The elements kept must fit in the DHEADER, and must fill it exactly when none is discarded. Discarded + // elements are skipped using the DHEADER. + if (count < length_to_read || offset_ - offset > dheader || + (sequence_length == length_to_read && offset_ - offset != dheader)) + { + set_state(state_before_error); + throw exception::BadParamException("Member size differs from the size specified by DHEADER"); + } + + if (offset_ - offset < dheader) + { + uint32_t remaining_bytes = dheader - static_cast(offset_ - offset); + if (!jump(remaining_bytes)) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + } + } + else + { + deserialize_framing(sequence_length); + + vector_t.clear(); + + if (sequence_length == 0) + { + return *this; + } + + if ((end_ - offset_) < sequence_length) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + uint32_t length_to_read {sequence_length}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + vector_t.resize(length_to_read); + + try + { + deserialize_array(vector_t.data(), length_to_read); + + // Consume the elements that do not fit in the destination. They are read into a + // discarded object instead of the destination, which may be shorter or empty. + if (sequence_length > length_to_read) + { + fake_mode_scope discarding {*this, true}; + + for (uint32_t count {length_to_read}; count < sequence_length; ++count) + { + _T discarded; + deserialize(discarded); + } + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + } + + return *this; + } + + TEMPLATE_SPEC + Cdr& deserialize( + std::vector& vector_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + return deserialize_bool_sequence(vector_t, consistency_flag, max_length); } /*! @@ -2050,7 +2515,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -2063,7 +2528,7 @@ class Cdr last_offset += dheader; uint32_t map_length {0}; - deserialize(map_length); + deserialize_framing(map_length); try { @@ -2094,7 +2559,7 @@ class Cdr { uint32_t sequence_length = 0; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2135,7 +2600,7 @@ class Cdr state state_(*this); std::map<_K, _T> map; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2159,6 +2624,269 @@ class Cdr return *this; } + /*! + * @brief This function template deserializes a map of non-primitive values applying a type consistency policy + * when the serialized map has more entries than the supplied @p max_length . + * + * The whole map is consumed from the stream. If the serialized map has more than @p max_length entries: + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE leaves @p map_t empty. + * - @ref CdrTryConstructFlag::TRIM keeps the first @p max_length entries in the order they were + * serialized and discards the rest. If the stream repeats a key, the repeated entry does not replace the + * first one, so @p map_t may end up with fewer than @p max_length entries. + * + * The content of @p map_t is only replaced when the whole deserialization succeeds. If an exception is thrown, + * @p map_t keeps its previous content and the stream is left where it was before the call. + * + * @param[out] map_t The variable that will store the map read from the buffer. + * @param[in] consistency_flag Policy applied when the serialized map has more than @p max_length entries. + * @param[in] max_length Maximum number of entries accepted for the destination map. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the serialized map has more than @p max_length entries, or when + * the entries read do not match the size given by the DHEADER. + */ + template::value && + !std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::map<_K, _T>& map_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + state state_before_error(*this); + std::map<_K, _T> map; + + if (CdrVersion::XCDRv2 == cdr_version_) + { + uint32_t dheader {0}; + deserialize_framing(dheader); + + if (((end_ - offset_) < dheader) || (dheader < 4)) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + auto offset = offset_; + + uint32_t map_length {0}; + deserialize_framing(map_length); + + uint32_t length_to_read {map_length}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized map contains more entries than the destination map can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + uint32_t count {0}; + + try + { + while (offset_ - offset < dheader && count < length_to_read) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + map.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + ++count; + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + + // The entries kept must fit in the DHEADER, and must fill it exactly when none is discarded. Discarded + // entries are skipped using the DHEADER. + if (count < length_to_read || offset_ - offset > dheader || + (map_length == length_to_read && offset_ - offset != dheader)) + { + set_state(state_before_error); + throw exception::BadParamException("Member size differs from the size specified by DHEADER"); + } + + if (offset_ - offset < dheader) + { + uint32_t remaining_bytes = dheader - static_cast(offset_ - offset); + if (!jump(remaining_bytes)) + { + set_state(state_before_error); + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + } + } + else + { + uint32_t map_length {0}; + deserialize_framing(map_length); + + uint32_t length_to_read {map_length}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized map contains more entries than the destination map can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + try + { + for (uint32_t i {0}; i < length_to_read; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + map.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + } + + // Consume the entries that do not fit in the destination. They are read into discarded + // objects instead of the destination, which may be smaller or empty. + if (map_length > length_to_read) + { + fake_mode_scope discarding {*this, true}; + + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + } + + map_t = std::move(map); + + return *this; + } + + /*! + * @brief This function template deserializes a map of primitive values applying a type consistency policy when + * the serialized map has more entries than the supplied @p max_length . + * + * The whole map is consumed from the stream. If the serialized map has more than @p max_length entries: + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE leaves @p map_t empty. + * - @ref CdrTryConstructFlag::TRIM keeps the first @p max_length entries in the order they were + * serialized and discards the rest. If the stream repeats a key, the repeated entry does not replace the + * first one, so @p map_t may end up with fewer than @p max_length entries. + * + * The content of @p map_t is only replaced when the whole deserialization succeeds. If an exception is thrown, + * @p map_t keeps its previous content and the stream is left where it was before the call. + * + * @param[out] map_t The variable that will store the map read from the buffer. + * @param[in] consistency_flag Policy applied when the serialized map has more than @p max_length entries. + * @param[in] max_length Maximum number of entries accepted for the destination map. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when @p consistency_flag is + * @ref CdrTryConstructFlag::FAIL and the serialized map has more than @p max_length entries, or when + * the entries read do not match the size given by the DHEADER. + */ + template::value || + std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::map<_K, _T>& map_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) + { + state state_before_error(*this); + std::map<_K, _T> map; + + uint32_t map_length {0}; + deserialize_framing(map_length); + + uint32_t length_to_read {map_length}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized map contains more entries than the destination map can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + try + { + for (uint32_t i {0}; i < length_to_read; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + map.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + } + + // Consume the entries that do not fit in the destination. They are read into discarded + // objects instead of the destination, which may be smaller or empty. + if (map_length > length_to_read) + { + fake_mode_scope discarding {*this, true}; + + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } + } + } + catch (exception::Exception& ex) + { + set_state(state_before_error); + ex.raise(); + } + + map_t = std::move(map); + + return *this; + } + /*! * @brief Decodes a bitset from the buffer. * @param[out] value Reference to the variable where the bitset will be stored after decoding from the buffer. @@ -2476,7 +3204,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if ((end_ - offset_) < dheader) { @@ -2590,7 +3318,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -2602,7 +3330,7 @@ class Cdr auto last_offset = offset_; last_offset += dheader; - deserialize(sequence_length); + deserialize_framing(sequence_length); if (0 == sequence_length) { sequence_t = NULL; @@ -2643,7 +3371,7 @@ class Cdr } else { - deserialize(sequence_length); + deserialize_framing(sequence_length); if ((end_ - offset_) < sequence_length) { @@ -2688,7 +3416,7 @@ class Cdr uint32_t sequence_length = 0; state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -3024,7 +3752,7 @@ class Cdr bool is_present = true; if (CdrVersion::XCDRv2 == cdr_version_ && EncodingAlgorithmFlag::PL_CDR2 != current_encoding_) { - deserialize(is_present); + deserialize_framing(is_present); } value.reset(is_present); if (is_present) @@ -3080,7 +3808,7 @@ class Cdr bool is_present = true; if (CdrVersion::XCDRv2 == cdr_version_ && EncodingAlgorithmFlag::PL_CDR2 != current_encoding_) { - deserialize(is_present); + deserialize_framing(is_present); } value.reset(is_present); if (is_present) @@ -3124,7 +3852,9 @@ class Cdr std::vector& vector_t); Cdr_DllAPI Cdr& deserialize_bool_sequence( - std::vector& vector_t); + std::vector& vector_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length); Cdr_DllAPI Cdr& deserialize_string_sequence( std::string*& sequence_t, @@ -3234,11 +3964,53 @@ class Cdr bool resize( size_t min_size_inc); + /*! + * @brief Sets @c fake_mode_ for the lifetime of the object, restoring its previous value on destruction + * even when an exception is thrown. + */ + class fake_mode_scope + { + public: + + fake_mode_scope( + Cdr& cdr, + bool enabled) + : cdr_(cdr) + , previous_(cdr.fake_mode_) + { + cdr_.fake_mode_ = enabled; + } + + ~fake_mode_scope() + { + cdr_.fake_mode_ = previous_; + } + + fake_mode_scope( + const fake_mode_scope&) = delete; + + fake_mode_scope& operator =( + const fake_mode_scope&) = delete; + + private: + + Cdr& cdr_; + + bool previous_; + }; + Cdr_DllAPI const char* read_string( uint32_t& length); Cdr_DllAPI const std::wstring read_wstring( uint32_t& length); + Cdr_DllAPI const char* read_string( + uint32_t& length, + CdrTryConstructFlag consistency_flag); + Cdr_DllAPI const std::wstring read_wstring( + uint32_t& length, + CdrTryConstructFlag consistency_flag); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// XCDR extensions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -3725,10 +4497,12 @@ class Cdr //! Whether the encapsulation was serialized. bool encapsulation_serialized_ {false}; + //! Whether fake deserialization mode is enabled. + bool fake_mode_ {false}; + //! Custom serialization context. std::shared_ptr context_; - uint32_t get_long_lc( SerializedMemberSizeForNextInt serialized_member_size); diff --git a/include/fastcdr/CdrEncoding.hpp b/include/fastcdr/CdrEncoding.hpp index 6e128f55..ed00885e 100644 --- a/include/fastcdr/CdrEncoding.hpp +++ b/include/fastcdr/CdrEncoding.hpp @@ -48,6 +48,17 @@ typedef enum : uint8_t PL_CDR2 = 0xa } EncodingAlgorithmFlag; +//! @brief This enumeration represents Cdr's behavior when there is type inconsistency between the serialized data and the type used to deserialize the data. +enum class CdrTryConstructFlag : uint32_t +{ + //! @brief Cdr will fail deserialization if there is type inconsistency. + FAIL = 0, + //! @brief Cdr will use default values for the fields that are not compatible between the serialized data and the type used to deserialize the data. + DEFAULT_VALUE = 1, + //! @brief Cdr will trim the serialized data so it can be assigned to the type used for deserialization. + TRIM = 2 +}; + } // namespace fastcdr } // namespace eprosima diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index 3adb2f1f..4f40d2b8 100644 --- a/src/cpp/Cdr.cpp +++ b/src/cpp/Cdr.cpp @@ -13,6 +13,7 @@ // limitations under the License. #include +#include #include #include @@ -1337,7 +1338,14 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(char_t); - offset_++ >> char_t; + if (!fake_mode_) + { + offset_++ >> char_t; + } + else + { + offset_++; + } return *this; } @@ -1356,16 +1364,23 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(short_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(&short_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(&short_t); - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + else + { + offset_ >> short_t; + offset_ += sizeof(short_t); + } } else { - offset_ >> short_t; offset_ += sizeof(short_t); } @@ -1387,18 +1402,25 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(long_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(&long_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(&long_t); - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + else + { + offset_ >> long_t; + offset_ += sizeof(long_t); + } } else { - offset_ >> long_t; offset_ += sizeof(long_t); } @@ -1420,22 +1442,29 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(&longlong_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(&longlong_t); - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + else + { + offset_ >> longlong_t; + offset_ += sizeof(longlong_t); + } } else { - offset_ >> longlong_t; offset_ += sizeof(longlong_t); } @@ -1457,18 +1486,25 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(float_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(&float_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(&float_t); - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + else + { + offset_ >> float_t; + offset_ += sizeof(float_t); + } } else { - offset_ >> float_t; offset_ += sizeof(float_t); } @@ -1490,22 +1526,29 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(&double_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(&double_t); - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + else + { + offset_ >> double_t; + offset_ += sizeof(double_t); + } } else { - offset_ >> double_t; offset_ += sizeof(double_t); } @@ -1527,63 +1570,79 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (swap_bytes_) + if (!fake_mode_) { + if (swap_bytes_) + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp = ldouble_t; - char* dst = reinterpret_cast(&tmp); + __float128 tmp = ldouble_t; + char* dst = reinterpret_cast(&tmp); #else - char* dst = reinterpret_cast(&ldouble_t); + char* dst = reinterpret_cast(&ldouble_t); #endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 #if FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - offset_++ >> dst[15]; - offset_++ >> dst[14]; - offset_++ >> dst[13]; - offset_++ >> dst[12]; - offset_++ >> dst[11]; - offset_++ >> dst[10]; - offset_++ >> dst[9]; - offset_++ >> dst[8]; - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_++ >> dst[15]; + offset_++ >> dst[14]; + offset_++ >> dst[13]; + offset_++ >> dst[12]; + offset_++ >> dst[11]; + offset_++ >> dst[10]; + offset_++ >> dst[9]; + offset_++ >> dst[8]; + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - ldouble_t = static_cast(tmp); + ldouble_t = static_cast(tmp); #endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - offset_ += 8; - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_ += 8; + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; #else #error unsupported long double type and no __float128 available #endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 #endif // FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 + } + else + { +#if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + __float128 tmp; + offset_ >> tmp; + offset_ += 16; + ldouble_t = static_cast(tmp); +#else +#if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#if FASTCDR_SIZEOF_LONG_DOUBLE == 8 + offset_ += 8; +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 + offset_ >> ldouble_t; + offset_ += sizeof(ldouble_t); +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + } } else { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp; - offset_ >> tmp; offset_ += 16; - ldouble_t = static_cast(tmp); #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 offset_ += 8; #endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 - offset_ >> ldouble_t; offset_ += sizeof(ldouble_t); #endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 #endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 @@ -1605,16 +1664,24 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint8_t); - offset_++ >> value; - - if (value == 1) + if (!fake_mode_) { - bool_t = true; - return *this; + offset_++ >> value; + + if (value == 1) + { + bool_t = true; + return *this; + } + else if (value == 0) + { + bool_t = false; + return *this; + } } - else if (value == 0) + else { - bool_t = false; + offset_++; return *this; } @@ -1630,7 +1697,7 @@ Cdr& Cdr::deserialize( uint32_t length = 0; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1643,10 +1710,13 @@ Cdr& Cdr::deserialize( last_data_size_ = sizeof(uint8_t); // Allocate memory. - string_t = - reinterpret_cast(calloc(length + ((&offset_)[length - 1] == '\0' ? 0 : 1), - sizeof(char))); - memcpy(string_t, &offset_, length); + if (!fake_mode_) + { + string_t = + reinterpret_cast(calloc(length + ((&offset_)[length - 1] == '\0' ? 0 : 1), + sizeof(char))); + memcpy(string_t, &offset_, length); + } offset_ += length; return *this; } @@ -1661,7 +1731,7 @@ Cdr& Cdr::deserialize( uint32_t length = 0; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1672,10 +1742,147 @@ Cdr& Cdr::deserialize( { // Save last datasize. last_data_size_ = sizeof(uint16_t); - // Allocate memory. - string_t = reinterpret_cast(calloc(length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero - deserialize_array(string_t, length); + if (!fake_mode_) + { + // Allocate memory. + string_t = reinterpret_cast(calloc(length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero + + deserialize_array(string_t, length); + } + else + { + offset_ += length * 2; + } + + return *this; + } + + set_state(state_before_error); + throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); +} + +Cdr& Cdr::deserialize( + char*& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) +{ + uint32_t length {0}; + Cdr::state state_before_error(*this); + + deserialize_framing(length); + + if (length == 0) + { + string_t = nullptr; + return *this; + } + if ((end_ - offset_) >= length) + { + // Number of visible characters, i.e. excluding the terminating null character when the + // encoder serialized one. The consistency policy is applied to this value because + // `max_length` bounds the characters the destination type can hold. + uint32_t visible_length {length}; + + if ((&offset_)[length - 1] == '\0') + { + --visible_length; + } + + uint32_t length_to_read {visible_length}; + + if (visible_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw BadParamException( + "Deserialized string length exceeds the maximum length allowed by the destination type"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + // Save last datasize. + last_data_size_ = sizeof(uint8_t); + + if (!fake_mode_) + { + // Allocate memory. The extra byte always reserved for the terminating null character + // is zeroed by calloc, so the result is null-terminated whether or not the stream + // carried a terminator and whether or not the string was trimmed. A string with no + // characters to keep becomes an empty string, as with the std::string overload. + string_t = reinterpret_cast(calloc(length_to_read + 1, sizeof(char))); + memcpy(string_t, &offset_, length_to_read); + } + offset_ += length; + return *this; + } + + set_state(state_before_error); + throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); +} + +Cdr& Cdr::deserialize( + wchar_t*& string_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) +{ + + uint32_t length = 0; + Cdr::state state_before_error(*this); + + deserialize_framing(length); + + if (length == 0) + { + string_t = nullptr; + return *this; + } + else if ((end_ - offset_) >= (length * 2)) + { + uint32_t length_to_read {length}; + + if (length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw BadParamException( + "Deserialized wide string length exceeds the maximum length allowed by the destination type"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + break; + } + } + + // Save last datasize. + last_data_size_ = sizeof(uint16_t); + + if (!fake_mode_) + { + // Allocate memory. WStrings never serialize the terminating zero, so the extra + // character zeroed by calloc terminates the result. A string with no characters to + // keep becomes an empty string, as with the std::wstring overload. + string_t = reinterpret_cast(calloc(length_to_read + 1, sizeof(wchar_t))); + + deserialize_array(string_t, length_to_read); + + offset_ += (length - length_to_read) * 2; + } + else + { + offset_ += length * 2; + } return *this; } @@ -1686,27 +1893,77 @@ Cdr& Cdr::deserialize( const char* Cdr::read_string( uint32_t& length) +{ + length = (std::numeric_limits::max)(); + return read_string(length, CdrTryConstructFlag::FAIL); +} + +const std::wstring Cdr::read_wstring( + uint32_t& length) +{ + length = (std::numeric_limits::max)(); + return read_wstring(length, CdrTryConstructFlag::FAIL); +} + +const char* Cdr::read_string( + uint32_t& length, + CdrTryConstructFlag consistency_flag) { const char* ret_value = ""; + uint32_t read_length {0}; state state_before_error(*this); - *this >> length; + deserialize_framing(read_length); - if (length == 0) + if (read_length == 0) { + length = 0; return ret_value; } - else if ((end_ - offset_) >= length) + else if ((end_ - offset_) >= read_length) { + // Number of visible characters, i.e. excluding the terminating null character when the + // encoder serialized one. The consistency policy is applied to this value because + // `length` bounds the characters the destination type can hold. + uint32_t visible_length {read_length}; + + if ((&offset_)[read_length - 1] == '\0') + { + --visible_length; + } + + uint32_t length_to_read {visible_length}; + + if (visible_length > length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw BadParamException( + "Deserialized string length exceeds the maximum length allowed by the destination type"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = length; + break; + } + } + // Save last datasize. last_data_size_ = sizeof(uint8_t); - ret_value = &offset_; - offset_ += length; - if (ret_value[length - 1] == '\0') + // In fake mode the stream is only consumed, so the returned pointer is left empty and the + // reported length must be zero to stay consistent with it. + length = fake_mode_ ? 0 : length_to_read; + + if (length > 0) { - --length; + ret_value = &offset_; } + + offset_ += read_length; return ret_value; } @@ -1716,13 +1973,15 @@ const char* Cdr::read_string( } const std::wstring Cdr::read_wstring( - uint32_t& length) + uint32_t& length, + CdrTryConstructFlag consistency_flag) { std::wstring ret_value = L""; + uint32_t read_length {0}; state state_(*this); - *this >> length; - uint32_t bytes_length = length * 2; + deserialize_framing(read_length); + uint32_t bytes_length = read_length * 2; if (bytes_length == 0) { @@ -1730,15 +1989,49 @@ const std::wstring Cdr::read_wstring( } else if ((end_ - offset_) >= bytes_length) { + uint32_t length_to_read {read_length}; + + if (read_length > length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_); + throw BadParamException( + "Deserialized wstring length exceeds the maximum length allowed by the destination type"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = length; + break; + } + } + // Save last datasize. last_data_size_ = sizeof(uint16_t); - ret_value.resize(length); - deserialize_array(const_cast(ret_value.c_str()), length); - if (ret_value[length - 1] == L'\0') + // In fake mode the stream is only consumed, so the returned string is left empty and the + // reported length must be zero to stay consistent with it. + length = fake_mode_ ? 0 : length_to_read; + + if (!fake_mode_) + { + if (length_to_read > 0) + { + ret_value.resize(length); + deserialize_array(const_cast(ret_value.c_str()), length); + if (ret_value[length - 1] == L'\0') + { + --length; + ret_value.erase(length); + } + } + offset_ += (read_length - length_to_read) * 2; + } + else { - --length; - ret_value.erase(length); + offset_ += bytes_length; } return ret_value; } @@ -1759,20 +2052,27 @@ Cdr& Cdr::deserialize_array( // Save last datasize. last_data_size_ = sizeof(*bool_t); - for (size_t count = 0; count < num_elements; ++count) + if (!fake_mode_) { - uint8_t value = 0; - offset_++ >> value; - - if (value == 1) + for (size_t count = 0; count < num_elements; ++count) { - bool_t[count] = true; - } - else if (value == 0) - { - bool_t[count] = false; + uint8_t value = 0; + offset_++ >> value; + + if (value == 1) + { + bool_t[count] = true; + } + else if (value == 0) + { + bool_t[count] = false; + } } } + else + { + offset_ += num_elements; + } return *this; } @@ -1791,7 +2091,10 @@ Cdr& Cdr::deserialize_array( // Save last datasize. last_data_size_ = sizeof(*char_t); - offset_.rmemcopy(char_t, total_size); + if (!fake_mode_) + { + offset_.rmemcopy(char_t, total_size); + } offset_ += total_size; return *this; } @@ -1818,20 +2121,27 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*short_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(short_t); - char* end = dst + total_size; + if (swap_bytes_) + { + char* dst = reinterpret_cast(short_t); + char* end = dst + total_size; - for (; dst < end; dst += sizeof(*short_t)) + for (; dst < end; dst += sizeof(*short_t)) + { + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_.rmemcopy(short_t, total_size); + offset_ += total_size; } } else { - offset_.rmemcopy(short_t, total_size); offset_ += total_size; } @@ -1860,22 +2170,29 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*long_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(long_t); - char* end = dst + total_size; + if (swap_bytes_) + { + char* dst = reinterpret_cast(long_t); + char* end = dst + total_size; - for (; dst < end; dst += sizeof(*long_t)) + for (; dst < end; dst += sizeof(*long_t)) + { + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_.rmemcopy(long_t, total_size); + offset_ += total_size; } } else { - offset_.rmemcopy(long_t, total_size); offset_ += total_size; } @@ -1922,26 +2239,33 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(longlong_t); - char* end = dst + total_size; + if (swap_bytes_) + { + char* dst = reinterpret_cast(longlong_t); + char* end = dst + total_size; - for (; dst < end; dst += sizeof(*longlong_t)) + for (; dst < end; dst += sizeof(*longlong_t)) + { + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_.rmemcopy(longlong_t, total_size); + offset_ += total_size; } } else { - offset_.rmemcopy(longlong_t, total_size); offset_ += total_size; } @@ -1970,22 +2294,29 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*float_t); - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(float_t); - char* end = dst + total_size; + if (swap_bytes_) + { + char* dst = reinterpret_cast(float_t); + char* end = dst + total_size; - for (; dst < end; dst += sizeof(*float_t)) + for (; dst < end; dst += sizeof(*float_t)) + { + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_.rmemcopy(float_t, total_size); + offset_ += total_size; } } else { - offset_.rmemcopy(float_t, total_size); offset_ += total_size; } @@ -2014,26 +2345,33 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; - if (swap_bytes_) + if (!fake_mode_) { - char* dst = reinterpret_cast(double_t); - char* end = dst + total_size; + if (swap_bytes_) + { + char* dst = reinterpret_cast(double_t); + char* end = dst + total_size; - for (; dst < end; dst += sizeof(*double_t)) + for (; dst < end; dst += sizeof(*double_t)) + { + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; + offset_.rmemcopy(double_t, total_size); + offset_ += total_size; } } else { - offset_.rmemcopy(double_t, total_size); offset_ += total_size; } @@ -2063,89 +2401,98 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; -#if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - if (swap_bytes_) + if (!fake_mode_) { - for (size_t i = 0; i < num_elements; ++i) +#if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + if (swap_bytes_) { - __float128 tmp; - char* dst = reinterpret_cast(&tmp); - offset_++ >> dst[15]; - offset_++ >> dst[14]; - offset_++ >> dst[13]; - offset_++ >> dst[12]; - offset_++ >> dst[11]; - offset_++ >> dst[10]; - offset_++ >> dst[9]; - offset_++ >> dst[8]; - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; - ldouble_t[i] = static_cast(tmp); + for (size_t i = 0; i < num_elements; ++i) + { + __float128 tmp; + char* dst = reinterpret_cast(&tmp); + offset_++ >> dst[15]; + offset_++ >> dst[14]; + offset_++ >> dst[13]; + offset_++ >> dst[12]; + offset_++ >> dst[11]; + offset_++ >> dst[10]; + offset_++ >> dst[9]; + offset_++ >> dst[8]; + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + ldouble_t[i] = static_cast(tmp); + } } - } - else - { - for (size_t i = 0; i < num_elements; ++i) + else { - __float128 tmp; - offset_ >> tmp; - offset_ += 16; - ldouble_t[i] = static_cast(tmp); + for (size_t i = 0; i < num_elements; ++i) + { + __float128 tmp; + offset_ >> tmp; + offset_ += 16; + ldouble_t[i] = static_cast(tmp); + } } - } #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - if (swap_bytes_) - { - char* dst = reinterpret_cast(ldouble_t); - char* end = dst + num_elements * sizeof(*ldouble_t); + if (swap_bytes_) + { + char* dst = reinterpret_cast(ldouble_t); + char* end = dst + num_elements * sizeof(*ldouble_t); - for (; dst < end; dst += sizeof(*ldouble_t)) + for (; dst < end; dst += sizeof(*ldouble_t)) + { +#if FASTCDR_SIZEOF_LONG_DOUBLE == 16 + offset_++ >> dst[15]; + offset_++ >> dst[14]; + offset_++ >> dst[13]; + offset_++ >> dst[12]; + offset_++ >> dst[11]; + offset_++ >> dst[10]; + offset_++ >> dst[9]; + offset_++ >> dst[8]; +#else + offset_ += 8; +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 + offset_++ >> dst[7]; + offset_++ >> dst[6]; + offset_++ >> dst[5]; + offset_++ >> dst[4]; + offset_++ >> dst[3]; + offset_++ >> dst[2]; + offset_++ >> dst[1]; + offset_++ >> dst[0]; + } + } + else { #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - offset_++ >> dst[15]; - offset_++ >> dst[14]; - offset_++ >> dst[13]; - offset_++ >> dst[12]; - offset_++ >> dst[11]; - offset_++ >> dst[10]; - offset_++ >> dst[9]; - offset_++ >> dst[8]; + offset_.rmemcopy(ldouble_t, total_size); + offset_ += total_size; #else - offset_ += 8; + for (size_t i = 0; i < num_elements; ++i) + { + offset_ += 8; // ignore first 8 bytes + offset_ >> ldouble_t[i]; + offset_ += 8; + } #endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 - offset_++ >> dst[7]; - offset_++ >> dst[6]; - offset_++ >> dst[5]; - offset_++ >> dst[4]; - offset_++ >> dst[3]; - offset_++ >> dst[2]; - offset_++ >> dst[1]; - offset_++ >> dst[0]; } +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 } else { -#if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - offset_.rmemcopy(ldouble_t, total_size); + // Long doubles always occupy 16 bytes on the wire, regardless of the platform's + // sizeof(long double), so the whole array is skipped with a single jump. offset_ += total_size; -#else - for (size_t i = 0; i < num_elements; ++i) - { - offset_ += 8; // ignore first 8 bytes - offset_ >> ldouble_t[i]; - offset_ += 8; - } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 return *this; } @@ -2295,22 +2642,49 @@ Cdr& Cdr::deserialize_bool_array( } Cdr& Cdr::deserialize_bool_sequence( - std::vector& vector_t) + std::vector& vector_t, + CdrTryConstructFlag consistency_flag, + uint32_t max_length) { uint32_t sequence_length {0}; state state_before_error(*this); - *this >> sequence_length; + deserialize_framing(sequence_length); + + vector_t.clear(); size_t total_size = sequence_length * sizeof(bool); if ((end_ - offset_) >= total_size) { - vector_t.resize(sequence_length); + uint32_t length_to_read {sequence_length}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTryConstructFlag::FAIL: + set_state(state_before_error); + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTryConstructFlag::TRIM: + length_to_read = max_length; + vector_t.resize(length_to_read); + break; + } + } + else + { + vector_t.resize(sequence_length); + } + // Save last datasize. last_data_size_ = sizeof(bool); - for (uint32_t count = 0; count < sequence_length; ++count) + for (uint32_t count = 0; count < length_to_read; ++count) { uint8_t value = 0; offset_++ >> value; @@ -2325,9 +2699,12 @@ Cdr& Cdr::deserialize_bool_sequence( } else { + set_state(state_before_error); throw BadParamException("Unexpected byte value in Cdr::deserialize_bool_sequence, expected 0 or 1"); } } + + offset_ += sequence_length - length_to_read; } else { @@ -2347,11 +2724,11 @@ Cdr& Cdr::deserialize_string_sequence( if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); auto offset = offset_; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2380,7 +2757,7 @@ Cdr& Cdr::deserialize_string_sequence( { state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2409,11 +2786,11 @@ Cdr& Cdr::deserialize_wstring_sequence( if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); auto offset = offset_; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2442,7 +2819,7 @@ Cdr& Cdr::deserialize_wstring_sequence( { state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2564,7 +2941,7 @@ bool Cdr::xcdr1_deserialize_member_header( bool ret_value = true; make_alignment(alignment(4)); uint16_t flags_and_member_id = 0; - deserialize(flags_and_member_id); + deserialize_framing(flags_and_member_id); member_id.must_understand = (flags_and_member_id & 0x4000); uint16_t id = (flags_and_member_id & 0x3FFF); @@ -2573,7 +2950,7 @@ bool Cdr::xcdr1_deserialize_member_header( { member_id.id = id; uint16_t size = 0; - deserialize(size); + deserialize_framing(size); current_state.member_size_ = size; current_state.header_serialized_ = XCdrHeaderSelection::SHORT_HEADER; reset_alignment(); @@ -2581,22 +2958,22 @@ bool Cdr::xcdr1_deserialize_member_header( else if (PID_EXTENDED == id) // PID_EXTENDED { uint16_t size = 0; - deserialize(size); + deserialize_framing(size); if (PID_EXTENDED_LENGTH != size) { throw BadParamException("PID_EXTENDED comes with a size different than 8"); } uint32_t mid = 0; - deserialize(mid); + deserialize_framing(mid); member_id.id = mid; - deserialize(current_state.member_size_); + deserialize_framing(current_state.member_size_); current_state.header_serialized_ = XCdrHeaderSelection::LONG_HEADER; reset_alignment(); } else if (PID_SENTINEL == id) // PID_SENTINEL { uint16_t size = 0; - deserialize(size); + deserialize_framing(size); if (0 != size) { throw BadParamException("PID_SENTINEL comes with a size different than 0"); @@ -3096,7 +3473,7 @@ void Cdr::xcdr2_deserialize_member_header( Cdr::state& current_state) { uint32_t flags_and_member_id = 0; - deserialize(flags_and_member_id); + deserialize_framing(flags_and_member_id); member_id.must_understand = (flags_and_member_id & 0x80000000); uint32_t mid = (flags_and_member_id & 0x0FFFFFFF); uint32_t lc = (flags_and_member_id & 0x70000000) >> 28; @@ -3127,14 +3504,14 @@ void Cdr::xcdr2_deserialize_member_header( else if (4 == lc) { uint32_t size = 0; - deserialize(size); + deserialize_framing(size); current_state.member_size_ = size; current_state.header_serialized_ = XCdrHeaderSelection::LONG_HEADER; } else { uint32_t size = 0; - deserialize(size); + deserialize_framing(size); current_state.member_size_ = 4 + (size * (5 == lc ? 1 : (6 == lc ? 4 : 8))); current_state.header_serialized_ = XCdrHeaderSelection::SHORT_HEADER; // Avoid take into account DHEADER after. offset_ -= sizeof(uint32_t); @@ -3277,7 +3654,7 @@ Cdr& Cdr::xcdr2_deserialize_type( if (EncodingAlgorithmFlag::PLAIN_CDR2 != type_encoding) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); Cdr::state current_state(*this); current_encoding_ = type_encoding; diff --git a/test/xcdr/CMakeLists.txt b/test/xcdr/CMakeLists.txt index 09861750..8cf406d2 100644 --- a/test/xcdr/CMakeLists.txt +++ b/test/xcdr/CMakeLists.txt @@ -22,9 +22,10 @@ set(XCDR_TEST_SOURCE final.cpp mutable.cpp optional.cpp + type_consistency.cpp xcdrv1.cpp xcdrv2.cpp - ) +) add_executable(xcdr_tests ${XCDR_TEST_SOURCE}) set_common_compile_options(xcdr_tests) target_link_libraries(xcdr_tests fastcdr GTest::gtest_main) diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp new file mode 100644 index 00000000..d3e9244c --- /dev/null +++ b/test/xcdr/type_consistency.cpp @@ -0,0 +1,2775 @@ +// Copyright 2026 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include "utility.hpp" + +using namespace eprosima::fastcdr; +using eprosima::fastcdr::exception::BadParamException; + +namespace { + +constexpr size_t TEST_BUFFER_LENGTH = 1024; + +//! Serializes @p value with the encoding and endianness currently under test. +template +void serialize_into( + char* buffer, + size_t buffer_size, + const SerializedT& value, + EncodingAlgorithmFlag encoding, + Cdr::Endianness endianness) +{ + FastBuffer fast_buffer(buffer, buffer_size); + Cdr cdr_ser(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_ser.set_encoding_flag(encoding); + cdr_ser << value; +} + +//! Serializes @p value followed by @p trailer, so tests can check where the stream is left. +template +void serialize_into_with_trailer( + char* buffer, + size_t buffer_size, + const SerializedT& value, + const TrailerT& trailer, + EncodingAlgorithmFlag encoding, + Cdr::Endianness endianness) +{ + FastBuffer fast_buffer(buffer, buffer_size); + Cdr cdr_ser(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_ser.set_encoding_flag(encoding); + cdr_ser << value << trailer; +} + +} // namespace + +/*! + * The try-construct policies are exercised against every supported CDR version. XCDRv1 and XCDRv2 + * take different code paths when discarding the part of a collection that does not fit in the + * destination: XCDRv2 skips it using the DHEADER, while XCDRv1 has no DHEADER and must consume the + * remainder element by element. + */ +class XCdrTypeConsistencyTest : public ::testing::TestWithParam> +{ +}; + + +/*! + * Element type used to check the policies on a sequence of non-primitive values holding a @c bool . + * Discarding such an element goes through @c deserialize(bool&) , which takes a dedicated path when + * the value is consumed without being stored. The second member of a different type makes an + * incorrect skip visible as misaligned data rather than as a plausible value. + */ +struct InnerBoolStruct +{ + InnerBoolStruct() = default; + + InnerBoolStruct( + bool b, + uint16_t v) + : value1(b) + , value2(v) + { + } + + bool operator ==( + const InnerBoolStruct& other) const + { + return value1 == other.value1 && value2 == other.value2; + } + + bool value1 {false}; + + uint16_t value2 {0}; +}; + +namespace eprosima { +namespace fastcdr { + +template<> +void serialize( + Cdr& cdr, + const InnerBoolStruct& data) +{ + Cdr::state current_status(cdr); + cdr.begin_serialize_type(current_status, cdr.get_encoding_flag()); + cdr << MemberId(0) << data.value1; + cdr << MemberId(1) << data.value2; + cdr.end_serialize_type(current_status); +} + +template<> +void deserialize( + Cdr& cdr, + InnerBoolStruct& data) +{ + cdr.deserialize_type(cdr.get_encoding_flag(), [&data](Cdr& cdr_inner, const MemberId& mid) -> bool + { + bool ret_value = true; + + switch (mid.id) + { + case 0: + cdr_inner >> data.value1; + break; + case 1: + cdr_inner >> data.value2; + break; + default: + ret_value = false; + break; + } + + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + +/*! + * Element type used to check that discarding a mutable structure consumes exactly its bytes. Skipping it requires + * the member headers (member id and size) and the length of the string member, which are only known by decoding + * them, so it fails if any of those values is not stored while the element is discarded. + */ +struct InnerMutableStruct +{ + InnerMutableStruct() = default; + + InnerMutableStruct( + const std::string& t, + int32_t n) + : text(t) + , number(n) + { + } + + bool operator ==( + const InnerMutableStruct& other) const + { + return text == other.text && number == other.number; + } + + std::string text; + + int32_t number {0}; +}; + +namespace eprosima { +namespace fastcdr { + +template<> +void serialize( + Cdr& cdr, + const InnerMutableStruct& data) +{ + Cdr::state current_status(cdr); + cdr.begin_serialize_type(current_status, cdr.get_cdr_version() == CdrVersion::XCDRv1 + ? EncodingAlgorithmFlag::PL_CDR + : EncodingAlgorithmFlag::PL_CDR2); + cdr << MemberId(0) << data.text; + cdr << MemberId(1) << data.number; + cdr.end_serialize_type(current_status); +} + +template<> +void deserialize( + Cdr& cdr, + InnerMutableStruct& data) +{ + cdr.deserialize_type(cdr.get_cdr_version() == CdrVersion::XCDRv1 + ? EncodingAlgorithmFlag::PL_CDR + : EncodingAlgorithmFlag::PL_CDR2, + [&data](Cdr& cdr_inner, const MemberId& mid) -> bool + { + bool ret_value = true; + + switch (mid.id) + { + case 0: + cdr_inner >> data.text; + break; + case 1: + cdr_inner >> data.number; + break; + default: + ret_value = false; + break; + } + + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + +/*! + * Element type used to check that discarding a structure with an optional member consumes exactly its bytes. + * Whether the optional value follows is only known by decoding the presence flag (XCDRv2) or the member header size + * (XCDRv1), so skipping fails if that value is not stored while the element is discarded. Elements with and without + * the optional value are both needed: each one fails under a different wrong default. + */ +struct InnerOptionalStruct +{ + InnerOptionalStruct() = default; + + InnerOptionalStruct( + const optional& o, + uint16_t v) + : value1(o) + , value2(v) + { + } + + bool operator ==( + const InnerOptionalStruct& other) const + { + return value1 == other.value1 && value2 == other.value2; + } + + optional value1; + + uint16_t value2 {0}; +}; + +namespace eprosima { +namespace fastcdr { + +template<> +void serialize( + Cdr& cdr, + const InnerOptionalStruct& data) +{ + Cdr::state current_status(cdr); + cdr.begin_serialize_type(current_status, cdr.get_encoding_flag()); + cdr << MemberId(0) << data.value1; + cdr << MemberId(1) << data.value2; + cdr.end_serialize_type(current_status); +} + +template<> +void deserialize( + Cdr& cdr, + InnerOptionalStruct& data) +{ + cdr.deserialize_type(cdr.get_encoding_flag(), [&data](Cdr& cdr_inner, const MemberId& mid) -> bool + { + bool ret_value = true; + + switch (mid.id) + { + case 0: + cdr_inner >> data.value1; + break; + case 1: + cdr_inner >> data.value2; + break; + default: + ret_value = false; + break; + } + + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + +/*! + * Union-like element type, (de)serialized as the code generated by Fast DDS-Gen for a final union: the + * discriminator is member 0 and selects which member follows. Discarding it consumes the right bytes only if the + * discriminator is stored while the element is discarded, which is why it is decoded with + * @c Cdr::deserialize_framing . + */ +struct InnerUnion +{ + InnerUnion() = default; + + InnerUnion( + int32_t n) + : discriminator(1) + , number(n) + { + } + + InnerUnion( + const std::string& t) + : discriminator(2) + , text(t) + { + } + + bool operator ==( + const InnerUnion& other) const + { + return discriminator == other.discriminator && + (1 != discriminator || number == other.number) && + (2 != discriminator || text == other.text); + } + + int32_t discriminator {0}; + + int32_t number {0}; + + std::string text; +}; + +namespace eprosima { +namespace fastcdr { + +template<> +void serialize( + Cdr& cdr, + const InnerUnion& data) +{ + Cdr::state current_status(cdr); + cdr.begin_serialize_type(current_status, cdr.get_cdr_version() == CdrVersion::XCDRv1 + ? EncodingAlgorithmFlag::PLAIN_CDR + : EncodingAlgorithmFlag::PLAIN_CDR2); + cdr << MemberId(0) << data.discriminator; + + switch (data.discriminator) + { + case 1: + cdr << MemberId(1) << data.number; + break; + case 2: + cdr << MemberId(2) << data.text; + break; + default: + break; + } + + cdr.end_serialize_type(current_status); +} + +template<> +void deserialize( + Cdr& cdr, + InnerUnion& data) +{ + cdr.deserialize_type(cdr.get_cdr_version() == CdrVersion::XCDRv1 + ? EncodingAlgorithmFlag::PLAIN_CDR + : EncodingAlgorithmFlag::PLAIN_CDR2, + [&data](Cdr& cdr_inner, const MemberId& mid) -> bool + { + bool ret_value = true; + + if (0 == mid.id) + { + cdr_inner.deserialize_framing(data.discriminator); + } + else + { + switch (data.discriminator) + { + case 1: + cdr_inner >> data.number; + break; + case 2: + cdr_inner >> data.text; + break; + default: + break; + } + + ret_value = false; + } + + return ret_value; + }); +} + +} // namespace fastcdr +} // namespace eprosima + +// ===================================================================================== +// std::string +// ===================================================================================== + +/*! + * @brief Checks that a std::string shorter than the bound is deserialized unchanged. + * + * The serialized string is well inside the bound, so no try-construct policy applies. This is the control case the + * three policy cases for std::string are compared against. The case is repeated for XCDRv1 and XCDRv2, in big and + * little endian. + * + * @test XCdrTypeConsistencyTest.StdString_Fit + * @pre A 5 character std::string ("hello") is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original string. + */ +TEST_P(XCdrTypeConsistencyTest, StdString_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that a std::string filling the bound exactly is accepted. + * + * CDR serializes a narrow string with a terminating null character counted in its length field, whereas the bound + * counts only the characters of the value. A string of exactly @c max_length characters must therefore be accepted + * instead of being treated as too long. Reading the trailer afterwards also proves the whole serialized string, + * terminator included, was consumed. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdString_ExactFit + * @pre A 5 character std::string ("hello") followed by a uint32_t trailer are serialized. + * @post Deserializing with @c FAIL and a bound of 5 does not throw, yields the original string, and leaves the + * stream positioned on the trailer, which is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdString_ExactFit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5)); + EXPECT_EQ(output, input); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that @c FAIL rejects a std::string longer than the bound. + * + * @c FAIL is the policy that refuses to build a value that does not fit, reporting the inconsistency to the caller + * instead of silently altering the data. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdString_Fail + * @pre An 11 character std::string ("hello world") is serialized. + * @post Deserializing with @c FAIL and a bound of 5 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdString_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a std::string longer than the bound. + * + * The destination is pre-filled before the call so that an empty result proves the value was actively reset, + * rather than merely left untouched. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdString_DefaultValue + * @pre An 11 character std::string is serialized and the destination holds "prefilled". + * @post Deserializing with @c DEFAULT_VALUE and a bound of 5 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdString_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output {"prefilled"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM truncates a std::string longer than the bound. + * + * @c TRIM keeps as much of the received value as the destination can hold, discarding the excess characters. The + * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdString_Trim + * @pre An 11 character std::string ("hello world") is serialized. + * @post Deserializing with @c TRIM and a bound of 5 does not throw and yields "hello". + */ +TEST_P(XCdrTypeConsistencyTest, StdString_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); + EXPECT_EQ(output, std::string("hello")); +} + + +// ===================================================================================== +// std::wstring +// ===================================================================================== + +/*! + * @brief Checks that a std::wstring shorter than the bound is deserialized unchanged. + * + * The serialized wide string is well inside the bound, so no try-construct policy applies. This is the control + * case for the std::wstring policies. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdWstring_Fit + * @pre A 5 character std::wstring (L"hello") is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original wide string. + */ +TEST_P(XCdrTypeConsistencyTest, StdWstring_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::wstring output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that a std::wstring filling the bound exactly is accepted. + * + * Unlike narrow strings, wide strings are serialized without a terminating null character, so the length field + * already matches the number of characters of the value. The case guards that boundary and, through the trailer, + * that the whole wide string was consumed. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdWstring_ExactFit + * @pre A 5 character std::wstring (L"hello") followed by a uint32_t trailer are serialized. + * @post Deserializing with @c FAIL and a bound of 5 does not throw, yields the original wide string, and leaves + * the stream positioned on the trailer, which is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdWstring_ExactFit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::wstring output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5)); + EXPECT_EQ(output, input); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that @c FAIL rejects a std::wstring longer than the bound. + * + * @c FAIL reports the inconsistency to the caller instead of silently altering the received wide string. The case + * is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdWstring_Fail + * @pre An 11 character std::wstring (L"hello world") is serialized. + * @post Deserializing with @c FAIL and a bound of 5 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdWstring_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::wstring output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a std::wstring longer than the bound. + * + * The destination is pre-filled before the call so that an empty result proves the value was actively reset. The + * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdWstring_DefaultValue + * @pre An 11 character std::wstring is serialized and the destination holds L"prefilled". + * @post Deserializing with @c DEFAULT_VALUE and a bound of 5 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdWstring_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::wstring output {L"prefilled"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM truncates a std::wstring longer than the bound. + * + * @c TRIM keeps as many wide characters as the destination can hold and discards the excess. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdWstring_Trim + * @pre An 11 character std::wstring (L"hello world") is serialized. + * @post Deserializing with @c TRIM and a bound of 5 does not throw and yields L"hello". + */ +TEST_P(XCdrTypeConsistencyTest, StdWstring_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::wstring output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); + EXPECT_EQ(output, std::wstring(L"hello")); +} + + +// ===================================================================================== +// char*& +// ===================================================================================== + +/*! + * @brief Checks that a C string shorter than the bound is deserialized unchanged. + * + * The @c char*& overload allocates the returned buffer, which the caller owns and releases. The serialized string + * is well inside the bound, so no policy applies. The case is repeated for XCDRv1 and XCDRv2, in big and little + * endian. + * + * @test XCdrTypeConsistencyTest.CharPtr_Fit + * @pre A 5 character string ("hello") is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields a non-null, null-terminated + * "hello", which the test frees. + */ +TEST_P(XCdrTypeConsistencyTest, CharPtr_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, "hello"); + free(output); +} + +/*! + * @brief Checks that a C string filling the bound exactly is accepted. + * + * The serialized length of a narrow string counts the terminating null character, while the bound counts only the + * characters of the value, so a string of exactly @c max_length characters must be accepted. The trailer + * additionally proves the terminator was consumed and not left in the stream. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.CharPtr_ExactFit + * @pre A 5 character string ("hello") followed by a uint32_t trailer are serialized. + * @post Deserializing with @c FAIL and a bound of 5 does not throw, yields "hello", and leaves the stream + * positioned on the trailer, which is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, CharPtr_ExactFit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, "hello"); + free(output); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that @c FAIL rejects a C string longer than the bound and allocates nothing. + * + * Besides reporting the inconsistency, the overload must not hand back a buffer the caller would have to release + * after a failed call. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.CharPtr_Fail + * @pre An 11 character string ("hello world") is serialized and the destination pointer is null. + * @post Deserializing with @c FAIL and a bound of 5 throws @c BadParamException and the destination pointer is + * left null. + */ +TEST_P(XCdrTypeConsistencyTest, CharPtr_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + char* output {nullptr}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); + EXPECT_EQ(output, nullptr); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a C string longer than the bound. + * + * The discarded value is an allocated empty string, as with the std::string overload, so the caller can use the + * result without checking for a null pointer. The case is repeated for XCDRv1 and XCDRv2, in big and little + * endian. + * + * @test XCdrTypeConsistencyTest.CharPtr_DefaultValue + * @pre An 11 character string is serialized and the destination pointer is null. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 5 does not throw and yields an allocated empty string. + */ +TEST_P(XCdrTypeConsistencyTest, CharPtr_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, ""); + free(output); +} + +/*! + * @brief Checks that @c TRIM truncates a C string longer than the bound. + * + * The truncated result must still be null-terminated even though the characters kept do not include the terminator + * that was serialized. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.CharPtr_Trim + * @pre An 11 character string ("hello world") is serialized. + * @post Deserializing with @c TRIM and a bound of 5 does not throw and yields a null-terminated "hello", which the + * test frees. + */ +TEST_P(XCdrTypeConsistencyTest, CharPtr_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, "hello"); + free(output); +} + + +// ===================================================================================== +// wchar_t*& +// ===================================================================================== + +/*! + * @brief Checks that a C wide string shorter than the bound is deserialized unchanged. + * + * The @c wchar_t*& overload allocates the returned buffer, which the caller owns and releases. The case is + * repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.WcharPtr_Fit + * @pre A 5 character wide string (L"hello") is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields a non-null, null-terminated + * L"hello", which the test frees. + */ +TEST_P(XCdrTypeConsistencyTest, WcharPtr_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L"hello"), 0); + free(output); +} + +/*! + * @brief Checks that a C wide string filling the bound exactly is accepted. + * + * Wide strings carry no terminating null character on the wire, so the serialized length already matches the + * number of characters of the value. The trailer proves the whole wide string was consumed. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.WcharPtr_ExactFit + * @pre A 5 character wide string (L"hello") followed by a uint32_t trailer are serialized. + * @post Deserializing with @c FAIL and a bound of 5 does not throw, yields L"hello", and leaves the stream + * positioned on the trailer, which is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, WcharPtr_ExactFit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L"hello"), 0); + free(output); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that @c FAIL rejects a C wide string longer than the bound and allocates nothing. + * + * The overload must not hand back a buffer the caller would have to release after a failed call. The case is + * repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.WcharPtr_Fail + * @pre An 11 character wide string (L"hello world") is serialized and the destination pointer is null. + * @post Deserializing with @c FAIL and a bound of 5 throws @c BadParamException and the destination pointer is + * left null. + */ +TEST_P(XCdrTypeConsistencyTest, WcharPtr_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + wchar_t* output {nullptr}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); + EXPECT_EQ(output, nullptr); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a C wide string longer than the bound. + * + * The discarded value is an allocated empty wide string, as with the std::wstring overload, so the caller can use + * the result without checking for a null pointer. The case is repeated for XCDRv1 and XCDRv2, in big and little + * endian. + * + * @test XCdrTypeConsistencyTest.WcharPtr_DefaultValue + * @pre An 11 character wide string is serialized and the destination pointer is null. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 5 does not throw and yields an allocated empty wide + * string. + */ +TEST_P(XCdrTypeConsistencyTest, WcharPtr_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L""), 0); + free(output); +} + +/*! + * @brief Checks that @c TRIM truncates a C wide string longer than the bound. + * + * The truncated result must still be null-terminated even though no terminator was received. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.WcharPtr_Trim + * @pre An 11 character wide string (L"hello world") is serialized. + * @post Deserializing with @c TRIM and a bound of 5 does not throw and yields a null-terminated L"hello", which + * the test frees. + */ +TEST_P(XCdrTypeConsistencyTest, WcharPtr_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L"hello"), 0); + free(output); +} + + +// ===================================================================================== +// fixed_string +// ===================================================================================== + +/*! + * @brief Checks that a string shorter than the fixed_string capacity is deserialized unchanged. + * + * For @c fixed_string the bound is the @c MAX_CHARS template argument rather than an explicit argument, so the + * policy is the only extra parameter. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_Fit + * @pre A 2 character string ("hi") is serialized and the destination is a @c fixed_string<8> . + * @post Deserializing with @c FAIL does not throw and yields "hi". + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hi"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<8> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL)); + EXPECT_STREQ(output.c_str(), "hi"); +} + +/*! + * @brief Checks that a string filling the fixed_string capacity exactly is accepted. + * + * The serialized length of a narrow string counts the terminating null character, while @c MAX_CHARS counts only + * the characters the destination can hold, so a string of exactly @c MAX_CHARS characters must be accepted rather + * than reported as too long. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_ExactFit + * @pre A 5 character string ("hello") is serialized and the destination is a @c fixed_string<5> . + * @post Deserializing with @c FAIL does not throw and yields "hello". + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_ExactFit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<5> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL)); + EXPECT_STREQ(output.c_str(), "hello"); +} + +/*! + * @brief Checks that the overload without a policy accepts a string filling the fixed_string exactly. + * + * The overload that takes no policy behaves as @c FAIL, so it rejects strings longer than the destination. A + * string that fills the destination exactly is a valid value and must still be accepted; this case pins that + * boundary so it cannot be lost while adjusting the rejection of longer strings. The case is repeated for XCDRv1 + * and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_ExactFitWithoutPolicy + * @pre A 5 character string ("hello") is serialized and the destination is a @c fixed_string<5> . + * @post Deserializing without a policy does not throw and yields "hello". + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_ExactFitWithoutPolicy) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<5> output; + ASSERT_NO_THROW(cdr_des.deserialize(output)); + EXPECT_STREQ(output.c_str(), "hello"); +} + +/*! + * @brief Checks that @c FAIL rejects a string longer than the fixed_string capacity. + * + * @c FAIL reports the inconsistency instead of silently truncating, which is the behaviour bounded strings rely on + * to detect mismatched types. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_Fail + * @pre A 29 character string is serialized and the destination is a @c fixed_string<8> . + * @post Deserializing with @c FAIL throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"too long for the fixed string"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<8> output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a string longer than the fixed_string capacity. + * + * The destination is pre-filled before the call so that an empty result proves the value was actively reset. The + * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_DefaultValue + * @pre A 29 character string is serialized and the destination is a @c fixed_string<8> holding "prefill". + * @post Deserializing with @c DEFAULT_VALUE does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"too long for the fixed string"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<8> output {"prefill"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE)); + EXPECT_STREQ(output.c_str(), ""); +} + +/*! + * @brief Checks that @c TRIM truncates a string longer than the fixed_string capacity. + * + * @c TRIM is the only way to obtain the legacy truncating behaviour, since the overload without a policy now + * reports an error instead. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.FixedString_Trim + * @pre A 12 character string ("abcdefghijkl") is serialized and the destination is a @c fixed_string<8> . + * @post Deserializing with @c TRIM does not throw and yields "abcdefgh". + */ +TEST_P(XCdrTypeConsistencyTest, FixedString_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"abcdefghijkl"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + fixed_string<8> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM)); + EXPECT_STREQ(output.c_str(), "abcdefgh"); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +/*! + * @brief Checks that a sequence of primitives shorter than the bound is deserialized unchanged. + * + * For collections the bound is a number of elements. The sequence is well inside it, so no policy applies. The + * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorPrimitive_Fit + * @pre A 3 element std::vector is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original sequence. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorPrimitive_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a sequence of primitives longer than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial sequence. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorPrimitive_Fail + * @pre A 5 element std::vector is serialized. + * @post Deserializing with @c FAIL and a bound of 3 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorPrimitive_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 3), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a sequence of primitives longer than the bound. + * + * The surplus elements still have to be consumed from the stream even though none of them is stored. The + * destination is pre-filled so that an empty result proves it was actively cleared. The case is repeated for + * XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorPrimitive_DefaultValue + * @pre A 5 element std::vector is serialized and the destination holds one element. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 3 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorPrimitive_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {99}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 3)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading elements of a sequence of primitives longer than the bound. + * + * The elements beyond the bound are consumed from the stream but not stored. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorPrimitive_Trim + * @pre A 5 element std::vector ({1, 2, 3, 4, 5}) is serialized. + * @post Deserializing with @c TRIM and a bound of 3 does not throw and yields {1, 2, 3}. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorPrimitive_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 3)); + const std::vector expected {1, 2, 3}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +/*! + * @brief Checks that a sequence of non-primitives shorter than the bound is deserialized unchanged. + * + * Sequences of non-primitive elements take a different code path from primitive ones, and under XCDRv2 they + * additionally carry a DHEADER. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_Fit + * @pre A 2 element std::vector is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original sequence. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a sequence of non-primitives longer than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial sequence. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_Fail + * @pre A 4 element std::vector is serialized. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a sequence of non-primitives longer than the bound. + * + * The surplus elements must be consumed without being written to the destination, which has already been emptied. + * XCDRv2 skips them using the DHEADER, while XCDRv1 has to read each one and throw it away. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_DefaultValue + * @pre A 4 element std::vector is serialized and the destination holds one element. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {"x"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading elements of a sequence of non-primitives longer than the bound. + * + * The elements beyond the bound are consumed without being written to the destination, which is shorter than the + * received sequence. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_Trim + * @pre A 4 element std::vector ({"alpha", "beta", "gamma", "delta"}) is serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw and yields {"alpha", "beta"}. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {"alpha", "beta"}; + EXPECT_EQ(output, expected); +} + +/*! + * @brief Checks that discarding a whole sequence of strings leaves the stream just past it. + * + * Skipping a string requires its length prefix, so the discarded elements must be read rather than only stepped + * over. A trailer serialized after the sequence makes a wrong stream position visible. The case is repeated for + * XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {"x"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence of strings leaves the stream just past it. + * + * The strings dropped must be consumed by exactly the bytes they occupy, which is observable only by reading what + * was serialized next. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_TrimConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields {"alpha", "beta"}, and the trailer is + * read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {"alpha", "beta"}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +/*! + * @brief Checks that a sequence of booleans shorter than the bound is deserialized unchanged. + * + * @c std::vector is a bit-packed specialization and is handled by a dedicated code path, so it is covered + * separately from the other sequences. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBool_Fit + * @pre A 3 element std::vector is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original sequence. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBool_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a sequence of booleans longer than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial sequence. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBool_Fail + * @pre A 5 element std::vector is serialized. + * @post Deserializing with @c FAIL and a bound of 3 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBool_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 3), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a sequence of booleans longer than the bound. + * + * The destination is pre-filled so that an empty result proves it was actively cleared. The case is repeated for + * XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBool_DefaultValue + * @pre A 5 element std::vector is serialized and the destination holds one element. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 3 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBool_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {true}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 3)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading elements of a sequence of booleans longer than the bound. + * + * The booleans beyond the bound are consumed from the stream but not stored. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBool_Trim + * @pre A 5 element std::vector ({true, false, true, true, false}) is serialized. + * @post Deserializing with @c TRIM and a bound of 3 does not throw and yields {true, false, true}. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBool_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 3)); + const std::vector expected {true, false, true}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::map +// ===================================================================================== + +/*! + * @brief Checks that a map of primitives smaller than the bound is deserialized unchanged. + * + * For maps the bound is a number of entries. The map is well inside it, so no policy applies. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapPrimitive_Fit + * @pre A 2 entry std::map is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original map. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a map of primitives larger than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial map. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapPrimitive_Fail + * @pre A 4 entry std::map is serialized. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a map of primitives larger than the bound. + * + * Both the key and the value of every surplus entry have to be consumed from the stream even though none of them + * is stored. The destination is pre-filled so that an empty result proves it was actively cleared. The case is + * repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapPrimitive_DefaultValue + * @pre A 4 entry std::map is serialized and the destination holds one entry. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output {{99, 99}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading entries of a map of primitives larger than the bound. + * + * Entries are read in serialization order, so the entries kept are the first ones received. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapPrimitive_Trim + * @pre A 4 entry std::map ({1, 10}, {2, 20}, {3, 30}, {4, 40}) is serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw and yields {{1, 10}, {2, 20}}. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::map expected {{1, 10}, {2, 20}}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::map +// ===================================================================================== + +/*! + * @brief Checks that a map with non-primitive values smaller than the bound is deserialized unchanged. + * + * Maps with non-primitive values take a different code path from fully primitive ones, and under XCDRv2 they + * additionally carry a DHEADER. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_Fit + * @pre A 2 entry std::map is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original map. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a map with non-primitive values larger than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial map. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_Fail + * @pre A 4 entry std::map is serialized. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a map with non-primitive values larger than the bound. + * + * The surplus entries must be consumed without being stored. XCDRv2 skips them using the DHEADER, while XCDRv1 has + * to read each key and value and throw them away. The case is repeated for XCDRv1 and XCDRv2, in big and little + * endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_DefaultValue + * @pre A 4 entry std::map is serialized and the destination holds one entry. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output {{99, "prefill"}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading entries of a map with non-primitive values larger than the bound. + * + * Entries are read in serialization order, so the entries kept are the first ones received. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_Trim + * @pre A 4 entry std::map ({1, "one"} .. {4, "four"}) is serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw and yields {{1, "one"}, {2, "two"}}. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::map expected {{1, "one"}, {2, "two"}}; + EXPECT_EQ(output, expected); +} + +/*! + * @brief Checks that discarding a whole map with string values leaves the stream just past it. + * + * Skipping a string value requires its length prefix, so the discarded entries must be read rather than only + * stepped over. A trailer serialized after the map makes a wrong stream position visible. The case is repeated + * for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_DefaultValueConsumesWholeMap + * @pre A 4 entry std::map followed by a uint32_t trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_DefaultValueConsumesWholeMap) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output {{0, "x"}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a map with string values leaves the stream just past it. + * + * The entries dropped must be consumed by exactly the bytes they occupy, which is observable only by reading what + * was serialized next. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_TrimConsumesWholeMap + * @pre A 4 entry std::map followed by a uint32_t trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields {{1, "one"}, {2, "two"}}, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_TrimConsumesWholeMap) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::map expected {{1, "one"}, {2, "two"}}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +/*! + * @brief Checks that a sequence of structures shorter than the bound is deserialized unchanged. + * + * @c InnerBoolStruct holds a @c bool and a @c uint16_t , so this group also covers the boolean and the alignment + * handling inside a non-primitive element. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_Fit + * @pre A 2 element std::vector is serialized with the encoding and endianness under test. + * @post Deserializing with @c FAIL and a bound of 10 does not throw and yields the original sequence. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_Fit) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +/*! + * @brief Checks that @c FAIL rejects a sequence of structures longer than the bound. + * + * @c FAIL reports the inconsistency rather than delivering a partial sequence. The case is repeated for XCDRv1 and + * XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_Fail + * @pre A 4 element std::vector is serialized. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException . + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_Fail) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}, {true, 33}, {false, 44}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); +} + +/*! + * @brief Checks that @c DEFAULT_VALUE discards a sequence of structures longer than the bound. + * + * Discarding an element reads its @c bool member without storing it, which is a dedicated path in the boolean + * decoder: an ordinary read validates the byte and rejects anything other than 0 or 1, whereas a discarded one + * only has to advance the stream. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_DefaultValue + * @pre A 4 element std::vector is serialized and the destination holds one element. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw and leaves the destination empty. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_DefaultValue) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}, {true, 33}, {false, 44}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {{true, 99}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +/*! + * @brief Checks that @c TRIM keeps the leading elements of a sequence of structures longer than the bound. + * + * The elements beyond the bound are discarded, which exercises reading their @c bool member without storing it. + * The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_Trim + * @pre A 4 element std::vector is serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw and yields the first two elements unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_Trim) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}, {true, 33}, {false, 44}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {{true, 11}, {false, 22}}; + EXPECT_EQ(output, expected); +} + +/*! + * @brief Checks that discarding a whole sequence leaves the stream just past it. + * + * Inspecting only the destination cannot tell whether the discarded elements were consumed by the right number of + * bytes, because an empty result is expected either way. Serializing a known trailer after the sequence turns a + * wrong stream position into a visible failure. The case is repeated for XCDRv1 and XCDRv2, in big and little + * endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}, {true, 33}, {false, 44}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence leaves the stream just past it. + * + * The elements kept are verified by the other @c TRIM cases; what this one adds is that the elements dropped were + * consumed by exactly the bytes they occupy, which is observable only by reading what was serialized next. The + * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorBoolStruct_TrimConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields the first two elements, and the trailer + * is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{true, 11}, {false, 22}, {true, 33}, {false, 44}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {{true, 11}, {false, 22}}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +// ===================================================================================== +// Discarded elements whose size is only known by decoding them +// ===================================================================================== + +/*! + * @brief Checks that discarding a whole sequence of sequences leaves the stream just past it. + * + * Each discarded element starts with its own length, which must be decoded to know how many bytes it occupies. + * A trailer serialized after the sequence makes a wrong stream position visible. + * The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNestedSequence_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector> followed by a uint32_t trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNestedSequence_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector> input {{1, 2}, {3}, {4, 5, 6}, {7, 8, 9, 10}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector> output {{0}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence of sequences leaves the stream just past it. + * + * Each discarded element starts with its own length, which must be decoded to know how many bytes it occupies. + * A trailer serialized after the sequence makes a wrong stream position visible. + * The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNestedSequence_TrimConsumesWholeSequence + * @pre A 4 element std::vector> followed by a uint32_t trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields the first two elements, and the trailer + * is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNestedSequence_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector> input {{1, 2}, {3}, {4, 5, 6}, {7, 8, 9, 10}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector> expected {{1, 2}, {3}}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that discarding a whole sequence of mutable structures leaves the stream just past it. + * + * Discarded elements are mutable structures holding a string, so skipping them requires decoding their member + * headers and the string length. A trailer serialized after the sequence makes a wrong stream position visible. + * The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorMutableStruct_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorMutableStruct_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{"alpha", 1}, {"beta", 2}, {"gamma", 3}, {"delta", 4}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {{"x", 0}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence of mutable structures leaves the stream just past it. + * + * Discarded elements are mutable structures holding a string, so skipping them requires decoding their member + * headers and the string length. A trailer serialized after the sequence makes a wrong stream position visible. + * The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorMutableStruct_TrimConsumesWholeSequence + * @pre A 4 element std::vector followed by a uint32_t trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields {{"alpha", 1}, {"beta", 2}}, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorMutableStruct_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{"alpha", 1}, {"beta", 2}, {"gamma", 3}, {"delta", 4}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {{"alpha", 1}, {"beta", 2}}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that discarding a whole sequence of structures with an optional member leaves the stream just past + * it. + * + * The discarded elements alternate between having and not having the optional value, which is only known by + * decoding the presence flag (XCDRv2) or the member header size (XCDRv1). A trailer serialized after the sequence + * makes a wrong stream position visible. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorOptionalStruct_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector, two of them without the optional value, followed by a uint32_t + * trailer are serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorOptionalStruct_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{optional{}, 1}, {7, 2}, {optional{}, 3}, {9, 4}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {{5, 0}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence of structures with an optional member leaves the stream just past it. + * + * The discarded elements are one without and one with the optional value, which is only known by decoding the + * presence flag (XCDRv2) or the member header size (XCDRv1). A trailer serialized after the sequence makes a wrong + * stream position visible. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorOptionalStruct_TrimConsumesWholeSequence + * @pre A 4 element std::vector, two of them without the optional value, followed by a uint32_t + * trailer are serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields the first two elements, and the trailer + * is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorOptionalStruct_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {{optional{}, 1}, {7, 2}, {optional{}, 3}, {9, 4}}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {{optional{}, 1}, {7, 2}}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +// ===================================================================================== +// FAIL leaves the stream and the destination unchanged +// ===================================================================================== + +/*! + * @brief Checks that @c FAIL leaves the stream where it was before the call for a std::string. + * + * Reading the same value again with a policy that accepts it proves the stream was not advanced. The case is + * repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdString_FailLeavesStreamUnchanged + * @pre An 11 character string ("hello world") is serialized. + * @post Deserializing with @c FAIL and a bound of 5 throws @c BadParamException , and deserializing again with + * @c TRIM and a bound of 5 yields "hello". + */ +TEST_P(XCdrTypeConsistencyTest, StdString_FailLeavesStreamUnchanged) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::string output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); + EXPECT_EQ(output, "hello"); +} + +/*! + * @brief Checks that @c FAIL leaves the stream where it was before the call for a sequence of non-primitives. + * + * Reading the same value again with a policy that accepts it proves the stream was not advanced. The case is + * repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorNonPrimitive_FailLeavesStreamUnchanged + * @pre A 4 element std::vector ({"alpha", "beta", "gamma", "delta"}) is serialized. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException , and deserializing again with + * @c TRIM and a bound of 2 yields {"alpha", "beta"}. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_FailLeavesStreamUnchanged) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {"alpha", "beta"}; + EXPECT_EQ(output, expected); +} + +/*! + * @brief Checks that @c FAIL leaves both the stream and the destination unchanged for a map. + * + * The destination map is only replaced when the whole deserialization succeeds, and reading the same value again + * with a policy that accepts it proves the stream was not advanced. The case is repeated for XCDRv1 and XCDRv2, + * in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapNonPrimitive_FailLeavesStreamAndDestinationUnchanged + * @pre A 4 entry std::map is serialized and the destination holds one entry. + * @post Deserializing with @c FAIL and a bound of 2 throws @c BadParamException and keeps the destination entry, + * and deserializing again with @c TRIM and a bound of 2 yields {{1, "one"}, {2, "two"}}. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_FailLeavesStreamAndDestinationUnchanged) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + const std::map previous {{0, "x"}}; + std::map output {previous}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); + EXPECT_EQ(output, previous); + + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::map expected {{1, "one"}, {2, "two"}}; + EXPECT_EQ(output, expected); +} + +/*! + * @brief Checks that a map with primitive values is left unchanged when the deserialization fails midway. + * + * The buffer is cut inside the second entry, so the first entry is read before the failure. The destination + * must not receive it. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdMapPrimitive_ErrorKeepsDestination + * @pre A 2 entry std::map is serialized, the buffer is cut inside the second entry, and the + * destination holds one entry. + * @post Deserializing with @c TRIM and a bound of 2 throws @c NotEnoughMemoryException and keeps the destination + * entry. + */ +TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_ErrorKeepsDestination) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}}; + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); + + // Length (4 bytes), first entry (8 bytes) and the key of the second entry (4 bytes). + FastBuffer fast_buffer(buffer, 16); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + const std::map previous {{0, 0}}; + std::map output {previous}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2), + eprosima::fastcdr::exception::NotEnoughMemoryException); + EXPECT_EQ(output, previous); +} + +/*! + * @brief Checks that discarding a whole sequence of unions leaves the stream just past it. + * + * The discarded elements select members of different sizes, so a discriminator that is not stored while they are + * discarded selects the wrong member and leaves the stream misaligned, which the trailer serialized after the + * sequence makes visible. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorUnion_DefaultValueConsumesWholeSequence + * @pre A 4 element std::vector ({10}, {"alpha"}, {"beta"}, {20}) followed by a uint32_t trailer are + * serialized. + * @post Deserializing with @c DEFAULT_VALUE and a bound of 2 does not throw, leaves the destination empty, and the + * trailer is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorUnion_DefaultValueConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {InnerUnion(10), InnerUnion(std::string("alpha")), + InnerUnion(std::string("beta")), InnerUnion(20)}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output {InnerUnion(5)}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + +/*! + * @brief Checks that truncating a sequence of unions leaves the stream just past it. + * + * The discarded elements select members of different sizes, so a discriminator that is not stored while they are + * discarded selects the wrong member and leaves the stream misaligned, which the trailer serialized after the + * sequence makes visible. The case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * + * @test XCdrTypeConsistencyTest.StdVectorUnion_TrimConsumesWholeSequence + * @pre A 4 element std::vector ({10}, {"alpha"}, {"beta"}, {20}) followed by a uint32_t trailer are + * serialized. + * @post Deserializing with @c TRIM and a bound of 2 does not throw, yields the first two elements, and the trailer + * is read back unchanged. + */ +TEST_P(XCdrTypeConsistencyTest, StdVectorUnion_TrimConsumesWholeSequence) +{ + const EncodingAlgorithmFlag encoding {std::get<0>(GetParam())}; + const Cdr::Endianness endianness {std::get<1>(GetParam())}; + + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {InnerUnion(10), InnerUnion(std::string("alpha")), + InnerUnion(std::string("beta")), InnerUnion(20)}; + const uint32_t trailer {0xCAFEBABEu}; + serialize_into_with_trailer(buffer, sizeof(buffer), input, trailer, encoding, endianness); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_des.set_encoding_flag(encoding); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); + const std::vector expected {InnerUnion(10), InnerUnion(std::string("alpha"))}; + EXPECT_EQ(output, expected); + + uint32_t read_trailer {0}; + ASSERT_NO_THROW(cdr_des.deserialize(read_trailer)); + EXPECT_EQ(read_trailer, trailer); +} + + +INSTANTIATE_TEST_SUITE_P( + XCdrTest, + XCdrTypeConsistencyTest, + ::testing::Values( + std::make_tuple(EncodingAlgorithmFlag::PLAIN_CDR, Cdr::Endianness::BIG_ENDIANNESS), + std::make_tuple(EncodingAlgorithmFlag::PLAIN_CDR, Cdr::Endianness::LITTLE_ENDIANNESS), + std::make_tuple(EncodingAlgorithmFlag::PLAIN_CDR2, Cdr::Endianness::BIG_ENDIANNESS), + std::make_tuple(EncodingAlgorithmFlag::PLAIN_CDR2, Cdr::Endianness::LITTLE_ENDIANNESS) + )); + + +// ===================================================================================== +// XCDRv2 DHEADER consistency +// ===================================================================================== + +namespace { + +//! Overwrites the little endian DHEADER at the start of @p buffer . +void patch_dheader( + char* buffer, + uint32_t dheader) +{ + buffer[0] = static_cast(dheader & 0xFF); + buffer[1] = static_cast((dheader >> 8) & 0xFF); + buffer[2] = static_cast((dheader >> 16) & 0xFF); + buffer[3] = static_cast((dheader >> 24) & 0xFF); +} + +//! Deserializes @p buffer as XCDRv2 little endian into @p output with @p flag and @p max_length . +template +void deserialize_xcdrv2( + char* buffer, + size_t buffer_size, + T& output, + CdrTryConstructFlag flag, + uint32_t max_length) +{ + FastBuffer fast_buffer(buffer, buffer_size); + Cdr cdr_des(fast_buffer, Cdr::Endianness::LITTLE_ENDIANNESS, CdrVersion::XCDRv2); + cdr_des.set_encoding_flag(EncodingAlgorithmFlag::PLAIN_CDR2); + cdr_des.deserialize(output, flag, max_length); +} + +} // namespace + +/*! + * @brief Checks that a sequence whose DHEADER is too small for the elements it announces is rejected. + * + * Layout of {"a", "b"}: DHEADER at 0, length at 4, "a" at 8 (length) and 12 (characters), "b" at 16 and 20. A + * DHEADER of 10 covers the length and the first string only, so the second element cannot be read from it. It + * must not be silently left default-constructed. + * + * @test XCdrTypeConsistencyDheaderTest.StdVectorNonPrimitive_DheaderTooSmall + * @pre A 2 element std::vector is serialized with XCDRv2 and its DHEADER is patched to 10. + * @post Deserializing with @c TRIM and a bound of 2 throws @c BadParamException . + */ +TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_DheaderTooSmall) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"a", "b"}; + serialize_into(buffer, sizeof(buffer), input, EncodingAlgorithmFlag::PLAIN_CDR2, + Cdr::Endianness::LITTLE_ENDIANNESS); + patch_dheader(buffer, 10); + + std::vector output; + EXPECT_THROW(deserialize_xcdrv2(buffer, sizeof(buffer), output, CdrTryConstructFlag::TRIM, 2), + BadParamException); +} + +/*! + * @brief Checks that a sequence announcing more elements than its DHEADER can hold is rejected before allocating. + * + * The buffer holds a DHEADER of 4, covering only the length, and a length of 1000000. Every element takes at least + * one byte, so the sequence is malformed whatever the policy, and the stream must be left where it was. + * + * @test XCdrTypeConsistencyDheaderTest.StdVectorNonPrimitive_LengthExceedsDheader + * @pre A buffer holds an XCDRv2 DHEADER of 4 followed by a sequence length of 1000000. + * @post Deserializing with every policy throws @c NotEnoughMemoryException , leaves the destination empty and the + * stream at its start. + */ +TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_LengthExceedsDheader) +{ + char buffer[8] {}; + patch_dheader(buffer, 4); + patch_dheader(buffer + 4, 1000000); + + for (CdrTryConstructFlag flag : {CdrTryConstructFlag::FAIL, CdrTryConstructFlag::DEFAULT_VALUE, + CdrTryConstructFlag::TRIM}) + { + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, Cdr::Endianness::LITTLE_ENDIANNESS, CdrVersion::XCDRv2); + cdr_des.set_encoding_flag(EncodingAlgorithmFlag::PLAIN_CDR2); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, flag, (std::numeric_limits::max)()), + eprosima::fastcdr::exception::NotEnoughMemoryException); + EXPECT_TRUE(output.empty()); + EXPECT_EQ(0u, output.capacity()); + EXPECT_EQ(0u, cdr_des.get_serialized_data_length()); + } +} + +/*! + * @brief Checks that an empty sequence whose DHEADER covers more than its length is rejected. + * + * The buffer holds a DHEADER of 8 and a length of 0, leaving four bytes inside the DHEADER that no element accounts + * for. Returning without consuming them would leave the stream misaligned, so the stream must be left where it was. + * + * @test XCdrTypeConsistencyDheaderTest.StdVectorNonPrimitive_EmptyDheaderMismatch + * @pre A buffer holds an XCDRv2 DHEADER of 8 followed by a sequence length of 0 and four padding bytes. + * @post Deserializing with every policy throws @c BadParamException , leaves the destination empty and the stream + * at its start. + */ +TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_EmptyDheaderMismatch) +{ + char buffer[12] {}; + patch_dheader(buffer, 8); + patch_dheader(buffer + 4, 0); + + for (CdrTryConstructFlag flag : {CdrTryConstructFlag::FAIL, CdrTryConstructFlag::DEFAULT_VALUE, + CdrTryConstructFlag::TRIM}) + { + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer, Cdr::Endianness::LITTLE_ENDIANNESS, CdrVersion::XCDRv2); + cdr_des.set_encoding_flag(EncodingAlgorithmFlag::PLAIN_CDR2); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, flag, 1), + eprosima::fastcdr::exception::BadParamException); + EXPECT_TRUE(output.empty()); + EXPECT_EQ(0u, cdr_des.get_serialized_data_length()); + } +} + +/*! + * @brief Checks that a truncated sequence whose kept elements overrun the DHEADER is rejected. + * + * With the layout of {"a", "b"} (see StdVectorNonPrimitive_DheaderTooSmall), a DHEADER of 6 ends inside the first + * string, which is the element kept when trimming to one. + * + * @test XCdrTypeConsistencyDheaderTest.StdVectorNonPrimitive_TrimOverrunsDheader + * @pre A 2 element std::vector is serialized with XCDRv2 and its DHEADER is patched to 6. + * @post Deserializing with @c TRIM and a bound of 1 throws @c BadParamException . + */ +TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_TrimOverrunsDheader) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"a", "b"}; + serialize_into(buffer, sizeof(buffer), input, EncodingAlgorithmFlag::PLAIN_CDR2, + Cdr::Endianness::LITTLE_ENDIANNESS); + patch_dheader(buffer, 6); + + std::vector output; + EXPECT_THROW(deserialize_xcdrv2(buffer, sizeof(buffer), output, CdrTryConstructFlag::TRIM, 1), + BadParamException); +} + +/*! + * @brief Checks that a map whose DHEADER is too small for the entries it announces is rejected. + * + * Layout of {{1, "a"}, {2, "b"}}: DHEADER at 0, length at 4, first key at 8 and value at 12 (length) and 16 + * (characters), second key at 20. A DHEADER of 14 covers the length and the first entry only. + * + * @test XCdrTypeConsistencyDheaderTest.StdMapNonPrimitive_DheaderTooSmall + * @pre A 2 entry std::map is serialized with XCDRv2 and its DHEADER is patched to 14. + * @post Deserializing with @c TRIM and a bound of 2 throws @c BadParamException . + */ +TEST(XCdrTypeConsistencyDheaderTest, StdMapNonPrimitive_DheaderTooSmall) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "a"}, {2, "b"}}; + serialize_into(buffer, sizeof(buffer), input, EncodingAlgorithmFlag::PLAIN_CDR2, + Cdr::Endianness::LITTLE_ENDIANNESS); + patch_dheader(buffer, 14); + + std::map output; + EXPECT_THROW(deserialize_xcdrv2(buffer, sizeof(buffer), output, CdrTryConstructFlag::TRIM, 2), + BadParamException); +} + +/*! + * @brief Checks that a truncated map whose kept entries overrun the DHEADER is rejected. + * + * With the layout of {{1, "a"}, {2, "b"}} (see StdMapNonPrimitive_DheaderTooSmall), a DHEADER of 6 ends inside + * the first entry, which is the entry kept when trimming to one. + * + * @test XCdrTypeConsistencyDheaderTest.StdMapNonPrimitive_TrimOverrunsDheader + * @pre A 2 entry std::map is serialized with XCDRv2 and its DHEADER is patched to 6. + * @post Deserializing with @c TRIM and a bound of 1 throws @c BadParamException . + */ +TEST(XCdrTypeConsistencyDheaderTest, StdMapNonPrimitive_TrimOverrunsDheader) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "a"}, {2, "b"}}; + serialize_into(buffer, sizeof(buffer), input, EncodingAlgorithmFlag::PLAIN_CDR2, + Cdr::Endianness::LITTLE_ENDIANNESS); + patch_dheader(buffer, 6); + + std::map output; + EXPECT_THROW(deserialize_xcdrv2(buffer, sizeof(buffer), output, CdrTryConstructFlag::TRIM, 1), + BadParamException); +}