From e764c273e62d7cc270fef7cbe10f0d8a8ca204b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Wed, 10 Jun 2026 12:52:06 +0200 Subject: [PATCH 1/8] Refs #23437. Initial support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 689 ++++++++++++++++++++++++++- include/fastcdr/CdrEncoding.hpp | 11 + src/cpp/Cdr.cpp | 808 +++++++++++++++++++++++--------- test/xcdr/CMakeLists.txt | 1 + test/xcdr/type_consistency.cpp | 676 ++++++++++++++++++++++++++ 5 files changed, 1941 insertions(+), 244 deletions(-) create mode 100644 test/xcdr/type_consistency.cpp diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index b85bf12b..4fa19bbb 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1761,6 +1762,28 @@ class Cdr Cdr_DllAPI Cdr& deserialize( char*& string_t); + /*! + * @brief This function deserializes a string applying a type consistency policy when the + * serialized length exceeds the supplied @p max_length . + * + * If the string is longer than @p max_length characters (excluding the null terminator): + * - @ref CdrTypeConsistencyFlag::FAIL resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @ref CdrTypeConsistencyFlag::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 serialized length exceeds @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + */ + Cdr_DllAPI Cdr& deserialize( + char*& string_t, + CdrTypeConsistencyFlag 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 +1795,28 @@ class Cdr Cdr_DllAPI Cdr& deserialize( wchar_t*& string_t); + /*! + * @brief This function deserializes a wide-string applying a type consistency policy when the + * serialized length exceeds the supplied @p max_length . + * + * If the wide string is longer than @p max_length characters (excluding the null terminator): + * - @ref CdrTypeConsistencyFlag::FAIL resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @ref CdrTypeConsistencyFlag::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 serialized length exceeds @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + */ + Cdr_DllAPI Cdr& deserialize( + wchar_t*& string_t, + CdrTypeConsistencyFlag 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 +1827,37 @@ 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, CdrTypeConsistencyFlag::FAIL); + string_t.assign(str, length); + return *this; + } + + /*! + * @brief This function deserializes a std::string applying a type consistency policy when + * the serialized length exceeds the supplied @p max_length . + * + * The stream is always fully consumed first. After deserialization, if the resulting string + * is longer than @p max_length : + * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p string_t . + * - @ref CdrTypeConsistencyFlag::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 serialized length exceeds @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + */ + Cdr& deserialize( + std::string& string_t, + CdrTypeConsistencyFlag 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 +1872,36 @@ 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, CdrTypeConsistencyFlag::FAIL); + return *this; + } + + /*! + * @brief This function deserializes a std::wstring applying a type consistency policy when + * the serialized length exceeds the supplied @p max_length . + * + * The stream is always fully consumed first. After deserialization, if the resulting string + * is longer than @p max_length : + * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p string_t . + * - @ref CdrTypeConsistencyFlag::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 serialized length exceeds @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + */ + Cdr& deserialize( + std::wstring& string_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + uint32_t length {max_length}; + string_t = read_wstring(length, consistency_flag); return *this; } @@ -1814,8 +1916,53 @@ 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, CdrTypeConsistencyFlag::FAIL); + value.assign(str, length); + return *this; + } + + /*! + * @brief Decodes a fixed string applying a type consistency policy when the serialized length + * exceeds @c MAX_CHARS . + * + * The stream is always fully consumed first. When the serialized length is larger than + * @c MAX_CHARS : + * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p value to an empty fixed_string. + * - @ref CdrTypeConsistencyFlag::TRIM keeps the first @c MAX_CHARS characters (this is the + * same behaviour as the regular @c deserialize(fixed_string&) overload, since + * @ref fixed_string::assign already truncates). + * + * @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 serialized length exceeds @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @c MAX_CHARS . + */ + template + Cdr& deserialize( + fixed_string& value, + CdrTypeConsistencyFlag consistency_flag) + { + uint32_t length {MAX_CHARS}; + const char* str = read_string(length, consistency_flag); + if (length > MAX_CHARS) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Deserialized string length exceeds the fixed_string maximum size"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + value = fixed_string{}; + return *this; + case CdrTypeConsistencyFlag::TRIM: + break; + } + } value.assign(str, length); return *this; } @@ -2029,7 +2176,273 @@ class Cdr Cdr& deserialize( std::vector& vector_t) { - return deserialize_bool_sequence(vector_t); + return deserialize_bool_sequence(vector_t, CdrTypeConsistencyFlag::FAIL, + (std::numeric_limits::max)()); + } + + /*! + * @brief This function template deserializes a sequence applying a type consistency policy + * when the serialized length exceeds the supplied @p max_length . + * + * The stream is always fully consumed first. After deserialization, if the resulting + * sequence is longer than @p max_length : + * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p vector_t . + * - @ref CdrTypeConsistencyFlag::TRIM resizes @p vector_t to @p max_length . + * + * The overload covers all element types, including @c bool , primitives, enumerations and + * user-defined types, dispatching through the regular @c deserialize overload to read the + * sequence before applying the policy. + * + * @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 CdrTypeConsistencyFlag::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, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + uint32_t sequence_length = 0; + state state_before_error(*this); + + deserialize(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}; + bool i_set_fake {false}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + vector_t.resize(length_to_read); + break; + } + } + else + { + vector_t.resize(length_to_read); + } + + + try + { + deserialize_array(vector_t.data(), length_to_read); + uint32_t remaining_elements = sequence_length - length_to_read; + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + deserialize_array(vector_t.data(), remaining_elements); + } + catch (exception::Exception& ex) + { + if (i_set_fake) + { + fake_mode = false; + } + set_state(state_before_error); + ex.raise(); + } + + if (i_set_fake) + { + fake_mode = false; + } + + return *this; + } + + template::value && + !std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::vector<_T>& vector_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + uint32_t sequence_length {0}; + + if (CdrVersion::XCDRv2 == cdr_version_) + { + uint32_t dheader {0}; + deserialize(dheader); + + auto offset = offset_; + + deserialize(sequence_length); + + vector_t.clear(); + + if (0 == sequence_length) + { + return *this; + } + + uint32_t length_to_read {sequence_length}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + vector_t.resize(length_to_read); + break; + } + } + else + { + vector_t.resize(length_to_read); + } + + uint32_t count {0}; + while (offset_ - offset < dheader && count < length_to_read) + { + deserialize(vector_t.data()[count]); + ++count; + } + + if (sequence_length == length_to_read) + { + if (offset_ - offset != dheader) + { + throw exception::BadParamException("Member size differs from the size specified by DHEADER"); + } + } + else if (offset_ - offset < dheader) + { + uint32_t remaining_bytes = dheader - static_cast(offset_ - offset); + if (!jump(remaining_bytes)) + { + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + } + } + else + { + state state_before_error(*this); + + deserialize(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}; + bool i_set_fake {false}; + + if (sequence_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + vector_t.resize(length_to_read); + break; + } + } + else + { + vector_t.resize(length_to_read); + } + + try + { + deserialize_array(vector_t.data(), length_to_read); + uint32_t remaining_elements = sequence_length - length_to_read; + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + deserialize_array(vector_t.data(), remaining_elements); + } + catch (exception::Exception& ex) + { + if (i_set_fake) + { + fake_mode = false; + } + set_state(state_before_error); + ex.raise(); + } + + if (i_set_fake) + { + fake_mode = false; + } + } + + return *this; + } + + TEMPLATE_SPEC + Cdr& deserialize( + std::vector& vector_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + return deserialize_bool_sequence(vector_t, consistency_flag, max_length); } /*! @@ -2159,6 +2572,256 @@ class Cdr return *this; } + template::value && + !std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::map<_K, _T>& map_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + if (CdrVersion::XCDRv2 == cdr_version_) + { + uint32_t dheader {0}; + deserialize(dheader); + + auto offset = offset_; + + uint32_t map_length {0}; + deserialize(map_length); + + map_t.clear(); + + if (0 == map_length) + { + return *this; + } + + uint32_t length_to_read {map_length}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + break; + } + } + + uint32_t count {0}; + while (offset_ - offset < dheader && count < length_to_read) + { + _K key; + _T val; + deserialize(key); + deserialize(val); + map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(val))); + ++count; + } + + if (map_length == length_to_read) + { + if (offset_ - offset != dheader) + { + throw exception::BadParamException("Member size greater than size specified by DHEADER"); + } + } + else if (offset_ - offset < dheader) + { + uint32_t remaining_bytes = dheader - static_cast(offset_ - offset); + if (!jump(remaining_bytes)) + { + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + } + } + else + { + uint32_t map_length = 0; + state state_(*this); + + deserialize(map_length); + + map_t.clear(); + + if (map_length == 0) + { + return *this; + } + + uint32_t length_to_read {map_length}; + bool i_set_fake {false}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::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_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + } + + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } + } + catch (exception::Exception& ex) + { + if (i_set_fake) + { + fake_mode = false; + } + set_state(state_); + ex.raise(); + } + + if (i_set_fake) + { + fake_mode = false; + } + } + + return *this; + } + + /*! + * @brief This function template deserializes a map applying a type consistency policy when + * the serialized length exceeds the supplied @p max_length . + * + * The stream is always fully consumed first. After deserialization, if the resulting map + * has more than @p max_length entries: + * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p map_t . + * - @ref CdrTypeConsistencyFlag::TRIM erases the highest-keyed entries until @p map_t + * holds exactly @p max_length entries. + * + * The overload covers both primitive and non-primitive value types, dispatching through the + * regular @c deserialize overload to read the map before applying the policy. + * + * @param[out] map_t The variable that will store the map read from the buffer. + * @param[in] consistency_flag Policy applied when the serialized length exceeds @p max_length . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + */ + template::value || + std::is_arithmetic<_T>::value>::type* = nullptr> + Cdr& deserialize( + std::map<_K, _T>& map_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) + { + uint32_t map_length = 0; + state state_(*this); + + deserialize(map_length); + + map_t.clear(); + + if (map_length == 0) + { + return *this; + } + + uint32_t length_to_read {map_length}; + bool i_set_fake {false}; + + if (map_length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::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_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + } + + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } + } + catch (exception::Exception& ex) + { + if (i_set_fake) + { + fake_mode = false; + } + set_state(state_); + ex.raise(); + } + + if (i_set_fake) + { + fake_mode = false; + } + + 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. @@ -3124,7 +3787,9 @@ class Cdr std::vector& vector_t); Cdr_DllAPI Cdr& deserialize_bool_sequence( - std::vector& vector_t); + std::vector& vector_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length); Cdr_DllAPI Cdr& deserialize_string_sequence( std::string*& sequence_t, @@ -3235,9 +3900,11 @@ class Cdr size_t min_size_inc); Cdr_DllAPI const char* read_string( - uint32_t& length); + uint32_t& length, + CdrTypeConsistencyFlag consistency_flag); Cdr_DllAPI const std::wstring read_wstring( - uint32_t& length); + uint32_t& length, + CdrTypeConsistencyFlag consistency_flag); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// XCDR extensions @@ -3728,6 +4395,8 @@ class Cdr //! Custom serialization context. std::shared_ptr context_; + //! Whether fake deserialization mode is enabled. + bool fake_mode {false}; uint32_t get_long_lc( SerializedMemberSizeForNextInt serialized_member_size); diff --git a/include/fastcdr/CdrEncoding.hpp b/include/fastcdr/CdrEncoding.hpp index 6e128f55..574e8852 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. +typedef enum +{ + //! @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 trims the serialized data so it can be assigned to the type used for deserialization. + TRIM = 2 +} CdrTypeConsistencyFlag; + } // namespace fastcdr } // namespace eprosima diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index 3adb2f1f..bbbe46de 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,30 @@ 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 +1571,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,17 +1665,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; - return *this; + offset_++; } throw BadParamException("Unexpected byte value in Cdr::deserialize(bool), expected 0 or 1"); @@ -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; } @@ -1672,10 +1742,136 @@ 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); + } + + return *this; + } + + set_state(state_before_error); + throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); +} + +Cdr& Cdr::deserialize( + char*& string_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) +{ + uint32_t length {0}; + Cdr::state state_before_error(*this); + + deserialize(length); + + if (length == 0) + { + string_t = nullptr; + return *this; + } + if ((end_ - offset_) >= length) + { + uint32_t length_to_read {length}; + + if (length > max_length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + string_t = nullptr; + throw BadParamException( + "Deserialized string length exceeds the maximum length allowed by the destination type"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + string_t = nullptr; + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + break; + } + } + + // Save last datasize. + last_data_size_ = sizeof(uint8_t); + + if (0 < length_to_read && !fake_mode) + { + // Allocate memory. + string_t = + reinterpret_cast(calloc(length_to_read + ((&offset_)[length_to_read - 1] == '\0' ? 0 : 1), + sizeof(char))); + memcpy(string_t, &offset_, max_length); + } + offset_ += length; + return *this; + + } + + set_state(state_before_error); + throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); +} + +Cdr& Cdr::deserialize( + wchar_t*& string_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) +{ + + uint32_t length = 0; + Cdr::state state_before_error(*this); + + deserialize(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 CdrTypeConsistencyFlag::FAIL: + string_t = nullptr; + throw BadParamException( + "Deserialized wide string length exceeds the maximum length allowed by the destination type"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + string_t = nullptr; + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::TRIM: + length_to_read = max_length; + break; + } + } + + // Save last datasize. + last_data_size_ = sizeof(uint16_t); + + if (!fake_mode) + { + if (0 < length_to_read) + { + // Allocate memory. + string_t = reinterpret_cast(calloc(length_to_read + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero + + deserialize_array(string_t, length_to_read); + } + + offset_ += (length - length_to_read) * 2; + } + else + { + offset_ += length * 2; + } return *this; } @@ -1685,28 +1881,54 @@ Cdr& Cdr::deserialize( } const char* Cdr::read_string( - uint32_t& length) + uint32_t& length, + CdrTypeConsistencyFlag consistency_flag) { const char* ret_value = ""; + uint32_t read_length {0}; state state_before_error(*this); - *this >> length; + *this >> read_length; - if (length == 0) + if (read_length == 0) { return ret_value; } - else if ((end_ - offset_) >= length) + else if ((end_ - offset_) >= read_length) { + uint32_t length_to_read {read_length}; + + if (read_length > length) + { + switch (consistency_flag) + { + case CdrTypeConsistencyFlag::FAIL: + throw BadParamException( + "Deserialized string length exceeds the maximum length allowed by the destination type"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::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') + length = length_to_read; + + if (length_to_read > 0 && !fake_mode) { - --length; + ret_value = &offset_; + if (ret_value[length - 1] == '\0') + { + --length; + } } + + offset_ += read_length; return ret_value; } @@ -1716,13 +1938,15 @@ const char* Cdr::read_string( } const std::wstring Cdr::read_wstring( - uint32_t& length) + uint32_t& length, + CdrTypeConsistencyFlag consistency_flag) { std::wstring ret_value = L""; + uint32_t read_length {0}; state state_(*this); - *this >> length; - uint32_t bytes_length = length * 2; + *this >> read_length; + uint32_t bytes_length = read_length * 2; if (bytes_length == 0) { @@ -1730,15 +1954,46 @@ 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 CdrTypeConsistencyFlag::FAIL: + throw BadParamException( + "Deserialized wstring length exceeds the maximum length allowed by the destination type"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::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') + length = length_to_read; + + if (!fake_mode) { - --length; - ret_value.erase(length); + 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 + { + offset_ += bytes_length; } return ret_value; } @@ -1759,20 +2014,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 +2053,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 +2083,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 +2132,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 +2201,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 +2256,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 +2307,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 +2363,101 @@ 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); 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; - } + offset_ += 8 * num_elements; + } #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 +2607,48 @@ Cdr& Cdr::deserialize_bool_array( } Cdr& Cdr::deserialize_bool_sequence( - std::vector& vector_t) + std::vector& vector_t, + CdrTypeConsistencyFlag consistency_flag, + uint32_t max_length) { uint32_t sequence_length {0}; state state_before_error(*this); *this >> 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 CdrTypeConsistencyFlag::FAIL: + throw exception::BadParamException( + "Serialized vector contains more elements than the destination array can hold"); + case CdrTypeConsistencyFlag::DEFAULT_VALUE: + length_to_read = 0; + break; + case CdrTypeConsistencyFlag::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; @@ -2328,6 +2666,8 @@ Cdr& Cdr::deserialize_bool_sequence( throw BadParamException("Unexpected byte value in Cdr::deserialize_bool_sequence, expected 0 or 1"); } } + + offset_ += sequence_length - length_to_read; } else { diff --git a/test/xcdr/CMakeLists.txt b/test/xcdr/CMakeLists.txt index 09861750..bbe0a507 100644 --- a/test/xcdr/CMakeLists.txt +++ b/test/xcdr/CMakeLists.txt @@ -22,6 +22,7 @@ set(XCDR_TEST_SOURCE final.cpp mutable.cpp optional.cpp + type_consistency.cpp xcdrv1.cpp xcdrv2.cpp ) diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp new file mode 100644 index 00000000..1d772cee --- /dev/null +++ b/test/xcdr/type_consistency.cpp @@ -0,0 +1,676 @@ +// 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 + +using namespace eprosima::fastcdr; +using eprosima::fastcdr::exception::BadParamException; + +namespace { + +constexpr size_t TEST_BUFFER_LENGTH = 1024; + +template +void serialize_into( + char* buffer, + size_t buffer_size, + const SerializedT& value, + Configure configure) +{ + FastBuffer fast_buffer(buffer, buffer_size); + Cdr cdr_ser(fast_buffer); + configure(cdr_ser); + cdr_ser << value; +} + +template +void serialize_into( + char* buffer, + size_t buffer_size, + const SerializedT& value) +{ + serialize_into(buffer, buffer_size, value, [](Cdr&) + { + }); +} + +} // namespace + + +// ===================================================================================== +// std::string +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdString_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::string output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdString_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::string output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); +} + +TEST(XCdrTypeConsistency, StdString_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::string output {"prefilled"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdString_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::string output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 5)); + EXPECT_EQ(output, std::string("hello")); +} + + +// ===================================================================================== +// std::wstring +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdWstring_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::wstring output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdWstring_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::wstring output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); +} + +TEST(XCdrTypeConsistency, StdWstring_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::wstring output {L"prefilled"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdWstring_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::wstring output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 5)); + EXPECT_EQ(output, std::wstring(L"hello")); +} + + +// ===================================================================================== +// char*& +// ===================================================================================== + +TEST(XCdrTypeConsistency, CharPtr_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, "hello"); + free(output); +} + +TEST(XCdrTypeConsistency, CharPtr_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + char* output {nullptr}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_EQ(output, nullptr); +} + +TEST(XCdrTypeConsistency, CharPtr_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + EXPECT_EQ(output, nullptr); +} + +TEST(XCdrTypeConsistency, CharPtr_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + char* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, "hello"); + free(output); +} + + +// ===================================================================================== +// wchar_t*& +// ===================================================================================== + +TEST(XCdrTypeConsistency, WcharPtr_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L"hello"), 0); + free(output); +} + +TEST(XCdrTypeConsistency, WcharPtr_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + wchar_t* output {nullptr}; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_EQ(output, nullptr); +} + +TEST(XCdrTypeConsistency, WcharPtr_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + EXPECT_EQ(output, nullptr); +} + +TEST(XCdrTypeConsistency, WcharPtr_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::wstring input {L"hello world"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + wchar_t* output {nullptr}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L"hello"), 0); + free(output); +} + + +// ===================================================================================== +// fixed_string +// ===================================================================================== + +TEST(XCdrTypeConsistency, FixedString_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"hi"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + fixed_string<8> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL)); + EXPECT_STREQ(output.c_str(), "hi"); +} + +TEST(XCdrTypeConsistency, FixedString_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"too long for the fixed string"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + fixed_string<8> output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL), BadParamException); +} + +TEST(XCdrTypeConsistency, FixedString_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"too long for the fixed string"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + fixed_string<8> output {"prefill"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE)); + EXPECT_STREQ(output.c_str(), ""); +} + +TEST(XCdrTypeConsistency, FixedString_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::string input {"abcdefghijkl"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + fixed_string<8> output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM)); + EXPECT_STREQ(output.c_str(), "abcdefgh"); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdVectorPrimitive_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdVectorPrimitive_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 3), BadParamException); +} + +TEST(XCdrTypeConsistency, StdVectorPrimitive_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output {99}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 3)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdVectorPrimitive_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {1, 2, 3, 4, 5}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 3)); + const std::vector expected {1, 2, 3}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); +} + +TEST(XCdrTypeConsistency, StdVectorNonPrimitive_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output {"x"}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {"alpha", "beta", "gamma", "delta"}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 2)); + const std::vector expected {"alpha", "beta"}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::vector +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdVectorBool_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdVectorBool_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 3), BadParamException); +} + +TEST(XCdrTypeConsistency, StdVectorBool_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output {true}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 3)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdVectorBool_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::vector input {true, false, true, true, false}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::vector output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 3)); + const std::vector expected {true, false, true}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::map +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdMapPrimitive_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdMapPrimitive_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); +} + +TEST(XCdrTypeConsistency, StdMapPrimitive_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output {{99, 99}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdMapPrimitive_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, 10}, {2, 20}, {3, 30}, {4, 40}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 2)); + const std::map expected {{1, 10}, {2, 20}}; + EXPECT_EQ(output, expected); +} + + +// ===================================================================================== +// std::map +// ===================================================================================== + +TEST(XCdrTypeConsistency, StdMapNonPrimitive_Fit) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 10)); + EXPECT_EQ(output, input); +} + +TEST(XCdrTypeConsistency, StdMapNonPrimitive_Fail) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + EXPECT_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); +} + +TEST(XCdrTypeConsistency, StdMapNonPrimitive_DefaultValue) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output {{99, "prefill"}}; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + EXPECT_TRUE(output.empty()); +} + +TEST(XCdrTypeConsistency, StdMapNonPrimitive_Trim) +{ + char buffer[TEST_BUFFER_LENGTH]; + const std::map input {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}}; + serialize_into(buffer, sizeof(buffer), input); + + FastBuffer fast_buffer(buffer, sizeof(buffer)); + Cdr cdr_des(fast_buffer); + + std::map output; + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTypeConsistencyFlag::TRIM, 2)); + const std::map expected {{1, "one"}, {2, "two"}}; + EXPECT_EQ(output, expected); +} From 319c0e1622c3c7e9e2ab3e8cff27c1c074d59e12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Thu, 17 Sep 2026 07:58:27 +0200 Subject: [PATCH 2/8] Refs #23437. Tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ricardo González Moreno --- .gitignore | 1 + include/fastcdr/Cdr.h | 241 +++--- include/fastcdr/CdrEncoding.hpp | 2 +- src/cpp/Cdr.cpp | 101 ++- test/xcdr/CMakeLists.txt | 2 +- test/xcdr/type_consistency.cpp | 1413 +++++++++++++++++++++++++++---- 6 files changed, 1430 insertions(+), 330 deletions(-) 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 4fa19bbb..10b0e66d 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -1764,24 +1764,25 @@ class Cdr /*! * @brief This function deserializes a string applying a type consistency policy when the - * serialized length exceeds the supplied @p max_length . + * string read does not fit in the supplied @p max_length . * - * If the string is longer than @p max_length characters (excluding the null terminator): - * - @ref CdrTypeConsistencyFlag::FAIL resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . - * - @ref CdrTypeConsistencyFlag::TRIM reads until position @p max_length so the string is truncated to @p max_length characters. + * 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 resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @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 serialized length exceeds @p max_length . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . */ Cdr_DllAPI Cdr& deserialize( char*& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length); /*! @@ -1797,24 +1798,25 @@ class Cdr /*! * @brief This function deserializes a wide-string applying a type consistency policy when the - * serialized length exceeds the supplied @p max_length . + * wide string read does not fit in the supplied @p max_length . * - * If the wide string is longer than @p max_length characters (excluding the null terminator): - * - @ref CdrTypeConsistencyFlag::FAIL resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . - * - @ref CdrTypeConsistencyFlag::TRIM reads at position @p max_length so the visible string is truncated to @p max_length characters. + * 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 resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @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 serialized length exceeds @p max_length . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . */ Cdr_DllAPI Cdr& deserialize( wchar_t*& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length); /*! @@ -1828,32 +1830,32 @@ class Cdr std::string& string_t) { uint32_t length {(std::numeric_limits::max)()}; - const char* str = read_string(length, CdrTypeConsistencyFlag::FAIL); + 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 serialized length exceeds the supplied @p max_length . + * the string read does not fit in the supplied @p max_length . * - * The stream is always fully consumed first. After deserialization, if the resulting string - * is longer than @p max_length : - * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p string_t . - * - @ref CdrTypeConsistencyFlag::TRIM resizes @p string_t to @p max_length . + * The stream is always fully consumed first. 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 serialized length exceeds @p max_length . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . */ Cdr& deserialize( std::string& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t length {max_length}; @@ -1873,31 +1875,31 @@ class Cdr std::wstring& string_t) { uint32_t length {(std::numeric_limits::max)()}; - string_t = read_wstring(length, CdrTypeConsistencyFlag::FAIL); + string_t = read_wstring(length, CdrTryConstructFlag::FAIL); return *this; } /*! * @brief This function deserializes a std::wstring applying a type consistency policy when - * the serialized length exceeds the supplied @p max_length . + * the wide string read does not fit in the supplied @p max_length . * - * The stream is always fully consumed first. After deserialization, if the resulting string - * is longer than @p max_length : - * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p string_t . - * - @ref CdrTypeConsistencyFlag::TRIM resizes @p string_t to @p max_length . + * The stream is always fully consumed first. 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 serialized length exceeds @p max_length . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @ref CdrTryConstructFlag::FAIL and the string read does not fit in @p max_length . */ Cdr& deserialize( std::wstring& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t length {max_length}; @@ -1917,35 +1919,35 @@ class Cdr fixed_string& value) { uint32_t length {MAX_CHARS}; - const char* str = read_string(length, CdrTypeConsistencyFlag::FAIL); + 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 serialized length - * exceeds @c MAX_CHARS . + * @brief Decodes a fixed string applying a type consistency policy when the deserialized + * string does not fit in @c MAX_CHARS . * - * The stream is always fully consumed first. When the serialized length is larger than - * @c MAX_CHARS : - * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE resets @p value to an empty fixed_string. - * - @ref CdrTypeConsistencyFlag::TRIM keeps the first @c MAX_CHARS characters (this is the - * same behaviour as the regular @c deserialize(fixed_string&) overload, since - * @ref fixed_string::assign already truncates). + * The stream is always fully consumed first. 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 serialized length exceeds @c MAX_CHARS . + * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @c MAX_CHARS . + * @ref CdrTryConstructFlag::FAIL and the deserialized string does not fit in @c MAX_CHARS . */ template Cdr& deserialize( fixed_string& value, - CdrTypeConsistencyFlag consistency_flag) + CdrTryConstructFlag consistency_flag) { uint32_t length {MAX_CHARS}; const char* str = read_string(length, consistency_flag); @@ -1953,13 +1955,13 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Deserialized string length exceeds the fixed_string maximum size"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: value = fixed_string{}; return *this; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: break; } } @@ -2176,7 +2178,7 @@ class Cdr Cdr& deserialize( std::vector& vector_t) { - return deserialize_bool_sequence(vector_t, CdrTypeConsistencyFlag::FAIL, + return deserialize_bool_sequence(vector_t, CdrTryConstructFlag::FAIL, (std::numeric_limits::max)()); } @@ -2186,9 +2188,9 @@ class Cdr * * The stream is always fully consumed first. After deserialization, if the resulting * sequence is longer than @p max_length : - * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p vector_t . - * - @ref CdrTypeConsistencyFlag::TRIM resizes @p vector_t to @p max_length . + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE clears @p vector_t . + * - @ref CdrTryConstructFlag::TRIM resizes @p vector_t to @p max_length . * * The overload covers all element types, including @c bool , primitives, enumerations and * user-defined types, dispatching through the regular @c deserialize overload to read the @@ -2200,13 +2202,13 @@ class Cdr * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @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, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t sequence_length = 0; @@ -2235,38 +2237,40 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: - if (!fake_mode) - { - fake_mode = true; - i_set_fake = true; - } + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; - vector_t.resize(length_to_read); break; } } - else - { - vector_t.resize(length_to_read); - } + vector_t.resize(length_to_read); try { deserialize_array(vector_t.data(), length_to_read); - uint32_t remaining_elements = sequence_length - length_to_read; - if (!fake_mode) + + // 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 = true; - i_set_fake = true; + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + + for (uint32_t count {length_to_read}; count < sequence_length; ++count) + { + _T discarded; + deserialize(discarded); + } } - deserialize_array(vector_t.data(), remaining_elements); } catch (exception::Exception& ex) { @@ -2290,7 +2294,7 @@ class Cdr !std::is_arithmetic<_T>::value>::type* = nullptr> Cdr& deserialize( std::vector<_T>& vector_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t sequence_length {0}; @@ -2317,13 +2321,13 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; vector_t.resize(length_to_read); break; @@ -2385,37 +2389,40 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: - if (!fake_mode) - { - fake_mode = true; - i_set_fake = true; - } + case CdrTryConstructFlag::DEFAULT_VALUE: + length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; - vector_t.resize(length_to_read); break; } } - else - { - vector_t.resize(length_to_read); - } + + vector_t.resize(length_to_read); try { deserialize_array(vector_t.data(), length_to_read); - uint32_t remaining_elements = sequence_length - length_to_read; - if (!fake_mode) + + // 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 = true; - i_set_fake = true; + if (!fake_mode) + { + fake_mode = true; + i_set_fake = true; + } + + for (uint32_t count {length_to_read}; count < sequence_length; ++count) + { + _T discarded; + deserialize(discarded); + } } - deserialize_array(vector_t.data(), remaining_elements); } catch (exception::Exception& ex) { @@ -2439,7 +2446,7 @@ class Cdr TEMPLATE_SPEC Cdr& deserialize( std::vector& vector_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { return deserialize_bool_sequence(vector_t, consistency_flag, max_length); @@ -2576,7 +2583,7 @@ class Cdr !std::is_arithmetic<_T>::value>::type* = nullptr> Cdr& deserialize( std::map<_K, _T>& map_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { if (CdrVersion::XCDRv2 == cdr_version_) @@ -2602,13 +2609,13 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; break; } @@ -2663,13 +2670,13 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; break; } @@ -2725,9 +2732,9 @@ class Cdr * * The stream is always fully consumed first. After deserialization, if the resulting map * has more than @p max_length entries: - * - @ref CdrTypeConsistencyFlag::FAIL throws @ref exception::BadParamException . - * - @ref CdrTypeConsistencyFlag::DEFAULT_VALUE clears @p map_t . - * - @ref CdrTypeConsistencyFlag::TRIM erases the highest-keyed entries until @p map_t + * - @ref CdrTryConstructFlag::FAIL throws @ref exception::BadParamException . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE clears @p map_t . + * - @ref CdrTryConstructFlag::TRIM erases the highest-keyed entries until @p map_t * holds exactly @p max_length entries. * * The overload covers both primitive and non-primitive value types, dispatching through the @@ -2739,13 +2746,13 @@ class Cdr * @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 CdrTypeConsistencyFlag::FAIL and the serialized length exceeds @p max_length . + * @ref CdrTryConstructFlag::FAIL and the serialized length exceeds @p max_length . */ template::value || std::is_arithmetic<_T>::value>::type* = nullptr> Cdr& deserialize( std::map<_K, _T>& map_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t map_length = 0; @@ -2767,13 +2774,13 @@ class Cdr { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; break; } @@ -3788,7 +3795,7 @@ class Cdr Cdr_DllAPI Cdr& deserialize_bool_sequence( std::vector& vector_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length); Cdr_DllAPI Cdr& deserialize_string_sequence( @@ -3901,10 +3908,10 @@ class Cdr Cdr_DllAPI const char* read_string( uint32_t& length, - CdrTypeConsistencyFlag consistency_flag); + CdrTryConstructFlag consistency_flag); Cdr_DllAPI const std::wstring read_wstring( uint32_t& length, - CdrTypeConsistencyFlag consistency_flag); + CdrTryConstructFlag consistency_flag); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// XCDR extensions diff --git a/include/fastcdr/CdrEncoding.hpp b/include/fastcdr/CdrEncoding.hpp index 574e8852..e48c3d36 100644 --- a/include/fastcdr/CdrEncoding.hpp +++ b/include/fastcdr/CdrEncoding.hpp @@ -57,7 +57,7 @@ typedef enum DEFAULT_VALUE = 1, //! @brief Cdr will trims the serialized data so it can be assigned to the type used for deserialization. TRIM = 2 -} CdrTypeConsistencyFlag; +} CdrTryConstructFlag; } // namespace fastcdr } // namespace eprosima diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index bbbe46de..e9de7f9b 100644 --- a/src/cpp/Cdr.cpp +++ b/src/cpp/Cdr.cpp @@ -1683,6 +1683,7 @@ Cdr& Cdr::deserialize( else { offset_++; + return *this; } throw BadParamException("Unexpected byte value in Cdr::deserialize(bool), expected 0 or 1"); @@ -1760,7 +1761,7 @@ Cdr& Cdr::deserialize( Cdr& Cdr::deserialize( char*& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t length {0}; @@ -1775,21 +1776,31 @@ Cdr& Cdr::deserialize( } if ((end_ - offset_) >= length) { - uint32_t length_to_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 + // `max_length` bounds the characters the destination type can hold. + uint32_t visible_length {length}; - if (length > max_length) + if ((&offset_)[length - 1] == '\0') + { + --visible_length; + } + + uint32_t length_to_read {visible_length}; + + if (visible_length > max_length) { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: string_t = nullptr; throw BadParamException( "Deserialized string length exceeds the maximum length allowed by the destination type"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: string_t = nullptr; length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; break; } @@ -1800,11 +1811,11 @@ Cdr& Cdr::deserialize( if (0 < length_to_read && !fake_mode) { - // Allocate memory. - string_t = - reinterpret_cast(calloc(length_to_read + ((&offset_)[length_to_read - 1] == '\0' ? 0 : 1), - sizeof(char))); - memcpy(string_t, &offset_, max_length); + // 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. + string_t = reinterpret_cast(calloc(length_to_read + 1, sizeof(char))); + memcpy(string_t, &offset_, length_to_read); } offset_ += length; return *this; @@ -1817,7 +1828,7 @@ Cdr& Cdr::deserialize( Cdr& Cdr::deserialize( wchar_t*& string_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { @@ -1839,15 +1850,15 @@ Cdr& Cdr::deserialize( { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: string_t = nullptr; throw BadParamException( "Deserialized wide string length exceeds the maximum length allowed by the destination type"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: string_t = nullptr; length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; break; } @@ -1882,7 +1893,7 @@ Cdr& Cdr::deserialize( const char* Cdr::read_string( uint32_t& length, - CdrTypeConsistencyFlag consistency_flag) + CdrTryConstructFlag consistency_flag) { const char* ret_value = ""; uint32_t read_length {0}; @@ -1892,23 +1903,34 @@ const char* Cdr::read_string( if (read_length == 0) { + length = 0; return ret_value; } else if ((end_ - offset_) >= read_length) { - uint32_t length_to_read {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 (read_length > length) + if ((&offset_)[read_length - 1] == '\0') + { + --visible_length; + } + + uint32_t length_to_read {visible_length}; + + if (visible_length > length) { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw BadParamException( "Deserialized string length exceeds the maximum length allowed by the destination type"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = length; break; } @@ -1917,15 +1939,13 @@ const char* Cdr::read_string( // Save last datasize. last_data_size_ = sizeof(uint8_t); - length = length_to_read; + // 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_to_read > 0 && !fake_mode) + if (length > 0) { ret_value = &offset_; - if (ret_value[length - 1] == '\0') - { - --length; - } } offset_ += read_length; @@ -1939,7 +1959,7 @@ const char* Cdr::read_string( const std::wstring Cdr::read_wstring( uint32_t& length, - CdrTypeConsistencyFlag consistency_flag) + CdrTryConstructFlag consistency_flag) { std::wstring ret_value = L""; uint32_t read_length {0}; @@ -1960,13 +1980,13 @@ const std::wstring Cdr::read_wstring( { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw BadParamException( "Deserialized wstring length exceeds the maximum length allowed by the destination type"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = length; break; } @@ -1975,7 +1995,9 @@ const std::wstring Cdr::read_wstring( // Save last datasize. last_data_size_ = sizeof(uint16_t); - length = length_to_read; + // 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) { @@ -2451,12 +2473,9 @@ Cdr& Cdr::deserialize_array( } else { -#if FASTCDR_SIZEOF_LONG_DOUBLE == 16 + // 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 - offset_ += 8 * num_elements; - } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 } return *this; @@ -2608,7 +2627,7 @@ Cdr& Cdr::deserialize_bool_array( Cdr& Cdr::deserialize_bool_sequence( std::vector& vector_t, - CdrTypeConsistencyFlag consistency_flag, + CdrTryConstructFlag consistency_flag, uint32_t max_length) { uint32_t sequence_length {0}; @@ -2628,13 +2647,13 @@ Cdr& Cdr::deserialize_bool_sequence( { switch (consistency_flag) { - case CdrTypeConsistencyFlag::FAIL: + case CdrTryConstructFlag::FAIL: throw exception::BadParamException( "Serialized vector contains more elements than the destination array can hold"); - case CdrTypeConsistencyFlag::DEFAULT_VALUE: + case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; - case CdrTypeConsistencyFlag::TRIM: + case CdrTryConstructFlag::TRIM: length_to_read = max_length; vector_t.resize(length_to_read); break; diff --git a/test/xcdr/CMakeLists.txt b/test/xcdr/CMakeLists.txt index bbe0a507..8cf406d2 100644 --- a/test/xcdr/CMakeLists.txt +++ b/test/xcdr/CMakeLists.txt @@ -25,7 +25,7 @@ set(XCDR_TEST_SOURCE 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 index 1d772cee..44c4db77 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -26,6 +27,7 @@ #include #include #include +#include "utility.hpp" using namespace eprosima::fastcdr; using eprosima::fastcdr::exception::BadParamException; @@ -34,89 +36,273 @@ namespace { constexpr size_t TEST_BUFFER_LENGTH = 1024; -template +//! Serializes @p value with the encoding and endianness currently under test. +template void serialize_into( char* buffer, size_t buffer_size, const SerializedT& value, - Configure configure) + EncodingAlgorithmFlag encoding, + Cdr::Endianness endianness) { FastBuffer fast_buffer(buffer, buffer_size); - Cdr cdr_ser(fast_buffer); - configure(cdr_ser); + Cdr cdr_ser(fast_buffer, endianness, get_version_from_algorithm(encoding)); + cdr_ser.set_encoding_flag(encoding); cdr_ser << value; } -template -void serialize_into( +//! 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 SerializedT& value, + const TrailerT& trailer, + EncodingAlgorithmFlag encoding, + Cdr::Endianness endianness) { - serialize_into(buffer, buffer_size, value, [](Cdr&) - { - }); + 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 // ===================================================================================== // std::string // ===================================================================================== -TEST(XCdrTypeConsistency, StdString_Fit) +/*! + * @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"}; - serialize_into(buffer, sizeof(buffer), input); + 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); + 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, CdrTypeConsistencyFlag::FAIL, 10)); + 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); } -TEST(XCdrTypeConsistency, StdString_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); } -TEST(XCdrTypeConsistency, StdString_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdString_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); EXPECT_EQ(output, std::string("hello")); } @@ -125,58 +311,149 @@ TEST(XCdrTypeConsistency, StdString_Trim) // std::wstring // ===================================================================================== -TEST(XCdrTypeConsistency, StdWstring_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdWstring_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); } -TEST(XCdrTypeConsistency, StdWstring_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdWstring_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); EXPECT_EQ(output, std::wstring(L"hello")); } @@ -185,61 +462,160 @@ TEST(XCdrTypeConsistency, StdWstring_Trim) // char*& // ===================================================================================== -TEST(XCdrTypeConsistency, CharPtr_Fit) +/*! + * @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"}; - serialize_into(buffer, sizeof(buffer), input); + 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); + 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, CdrTypeConsistencyFlag::FAIL, 10)); + 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); } -TEST(XCdrTypeConsistency, CharPtr_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); EXPECT_EQ(output, nullptr); } -TEST(XCdrTypeConsistency, CharPtr_DefaultValue) +/*! + * @brief Checks that @c DEFAULT_VALUE discards a C string longer than the bound. + * + * For a raw pointer the discarded value is represented by a null pointer, so nothing needs to be released. 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 leaves the destination pointer + * null. + */ +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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); EXPECT_EQ(output, nullptr); } -TEST(XCdrTypeConsistency, CharPtr_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); ASSERT_NE(output, nullptr); EXPECT_STREQ(output, "hello"); free(output); @@ -250,61 +626,158 @@ TEST(XCdrTypeConsistency, CharPtr_Trim) // wchar_t*& // ===================================================================================== -TEST(XCdrTypeConsistency, WcharPtr_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); ASSERT_NE(output, nullptr); EXPECT_EQ(std::wcscmp(output, L"hello"), 0); free(output); } -TEST(XCdrTypeConsistency, WcharPtr_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 5), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 5), BadParamException); EXPECT_EQ(output, nullptr); } -TEST(XCdrTypeConsistency, WcharPtr_DefaultValue) +/*! + * @brief Checks that @c DEFAULT_VALUE discards a C wide string longer than the bound. + * + * For a raw pointer the discarded value is represented by a null pointer, so nothing needs to be released. 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 leaves the destination pointer + * null. + */ +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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); EXPECT_EQ(output, nullptr); } -TEST(XCdrTypeConsistency, WcharPtr_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 5)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 5)); ASSERT_NE(output, nullptr); EXPECT_EQ(std::wcscmp(output, L"hello"), 0); free(output); @@ -315,58 +788,173 @@ TEST(XCdrTypeConsistency, WcharPtr_Trim) // fixed_string // ===================================================================================== -TEST(XCdrTypeConsistency, FixedString_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL)); EXPECT_STREQ(output.c_str(), "hi"); } -TEST(XCdrTypeConsistency, FixedString_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL), BadParamException); } -TEST(XCdrTypeConsistency, FixedString_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE)); EXPECT_STREQ(output.c_str(), ""); } -TEST(XCdrTypeConsistency, FixedString_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM)); EXPECT_STREQ(output.c_str(), "abcdefgh"); } @@ -375,58 +963,115 @@ TEST(XCdrTypeConsistency, FixedString_Trim) // std::vector // ===================================================================================== -TEST(XCdrTypeConsistency, StdVectorPrimitive_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdVectorPrimitive_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 3), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 3), BadParamException); } -TEST(XCdrTypeConsistency, StdVectorPrimitive_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 3)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 3)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdVectorPrimitive_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 3)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 3)); const std::vector expected {1, 2, 3}; EXPECT_EQ(output, expected); } @@ -436,58 +1081,115 @@ TEST(XCdrTypeConsistency, StdVectorPrimitive_Trim) // std::vector // ===================================================================================== -TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); } -TEST(XCdrTypeConsistency, StdVectorNonPrimitive_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); const std::vector expected {"alpha", "beta"}; EXPECT_EQ(output, expected); } @@ -497,58 +1199,114 @@ TEST(XCdrTypeConsistency, StdVectorNonPrimitive_Trim) // std::vector // ===================================================================================== -TEST(XCdrTypeConsistency, StdVectorBool_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdVectorBool_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 3), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 3), BadParamException); } -TEST(XCdrTypeConsistency, StdVectorBool_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 3)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 3)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdVectorBool_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 3)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 3)); const std::vector expected {true, false, true}; EXPECT_EQ(output, expected); } @@ -558,58 +1316,115 @@ TEST(XCdrTypeConsistency, StdVectorBool_Trim) // std::map // ===================================================================================== -TEST(XCdrTypeConsistency, StdMapPrimitive_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdMapPrimitive_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); } -TEST(XCdrTypeConsistency, StdMapPrimitive_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdMapPrimitive_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); const std::map expected {{1, 10}, {2, 20}}; EXPECT_EQ(output, expected); } @@ -619,58 +1434,316 @@ TEST(XCdrTypeConsistency, StdMapPrimitive_Trim) // std::map // ===================================================================================== -TEST(XCdrTypeConsistency, StdMapNonPrimitive_Fit) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 10)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 10)); EXPECT_EQ(output, input); } -TEST(XCdrTypeConsistency, StdMapNonPrimitive_Fail) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::FAIL, 2), BadParamException); + EXPECT_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::FAIL, 2), BadParamException); } -TEST(XCdrTypeConsistency, StdMapNonPrimitive_DefaultValue) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::DEFAULT_VALUE, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 2)); EXPECT_TRUE(output.empty()); } -TEST(XCdrTypeConsistency, StdMapNonPrimitive_Trim) +/*! + * @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); + serialize_into(buffer, sizeof(buffer), input, encoding, endianness); FastBuffer fast_buffer(buffer, sizeof(buffer)); - Cdr cdr_des(fast_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, CdrTypeConsistencyFlag::TRIM, 2)); + ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::TRIM, 2)); const std::map expected {{1, "one"}, {2, "two"}}; EXPECT_EQ(output, expected); } + + +// ===================================================================================== +// 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); +} + + +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) + )); From c5a964c460c7526f043d8dbb56c10c28b37d2b9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 27 Oct 2026 09:39:10 +0100 Subject: [PATCH 3/8] Refs #23437. Fix fake mode framing and ABI compatibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Discarded elements are decoded in fake mode, which skips storing every primitive. That included the values that decide how many bytes an element occupies, so discarding a string, a nested sequence, a mutable structure or a structure with an optional member left the stream misaligned. Add a private deserialize_framing() helper that always stores the value, also in fake mode. Use it for every library-owned length or header read: string and sequence lengths, map lengths, DHEADERs, XCDRv1 parameter headers, XCDRv2 EMHEADERs and the optional presence flag. Fake mode is now set through a fake_mode_scope guard, which restores the previous value also when an exception other than eprosima::fastcdr::exception::Exception escapes. Validate the DHEADER bounds in the try-construct XCDRv2 sequence and map overloads, and restore the stream state when they throw. Restore the one-argument read_string() and read_wstring() overloads that binaries built against 2.4.0 reference from inlined header code. They forward to the new overloads with no length limit. Make CdrTryConstructFlag a scoped enum, so its enumerators do not leak into the eprosima::fastcdr namespace. Add tests that serialize a trailer after the collection and check it is read back unchanged after discarding elements of each kind. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 227 ++++++++------ include/fastcdr/CdrEncoding.hpp | 6 +- src/cpp/Cdr.cpp | 60 ++-- test/xcdr/type_consistency.cpp | 510 ++++++++++++++++++++++++++++++++ 4 files changed, 679 insertions(+), 124 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index 10b0e66d..800b0ac1 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -1984,7 +1984,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) { @@ -2042,7 +2042,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -2054,7 +2054,7 @@ class Cdr auto last_offset = offset_; last_offset += dheader; - deserialize(sequence_length); + deserialize_framing(sequence_length); if (0 == sequence_length) { @@ -2095,7 +2095,7 @@ class Cdr } else { - deserialize(sequence_length); + deserialize_framing(sequence_length); if (sequence_length == 0) { @@ -2139,7 +2139,7 @@ class Cdr uint32_t sequence_length = 0; state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); if (sequence_length == 0) { @@ -2214,7 +2214,7 @@ class Cdr uint32_t sequence_length = 0; state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); vector_t.clear(); @@ -2231,7 +2231,6 @@ class Cdr } uint32_t length_to_read {sequence_length}; - bool i_set_fake {false}; if (sequence_length > max_length) { @@ -2259,11 +2258,7 @@ class Cdr // discarded object instead of the destination, which may be shorter or empty. if (sequence_length > length_to_read) { - if (!fake_mode) - { - fake_mode = true; - i_set_fake = true; - } + fake_mode_scope discarding {*this, true}; for (uint32_t count {length_to_read}; count < sequence_length; ++count) { @@ -2274,19 +2269,10 @@ class Cdr } catch (exception::Exception& ex) { - if (i_set_fake) - { - fake_mode = false; - } set_state(state_before_error); ex.raise(); } - if (i_set_fake) - { - fake_mode = false; - } - return *this; } @@ -2298,15 +2284,23 @@ class Cdr uint32_t max_length) { uint32_t sequence_length {0}; + state state_before_error(*this); if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + 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(sequence_length); + deserialize_framing(sequence_length); vector_t.clear(); @@ -2349,6 +2343,7 @@ class Cdr { if (offset_ - offset != dheader) { + set_state(state_before_error); throw exception::BadParamException("Member size differs from the size specified by DHEADER"); } } @@ -2357,6 +2352,7 @@ class Cdr 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); } @@ -2364,9 +2360,7 @@ class Cdr } else { - state state_before_error(*this); - - deserialize(sequence_length); + deserialize_framing(sequence_length); vector_t.clear(); @@ -2383,7 +2377,6 @@ class Cdr } uint32_t length_to_read {sequence_length}; - bool i_set_fake {false}; if (sequence_length > max_length) { @@ -2411,11 +2404,7 @@ class Cdr // discarded object instead of the destination, which may be shorter or empty. if (sequence_length > length_to_read) { - if (!fake_mode) - { - fake_mode = true; - i_set_fake = true; - } + fake_mode_scope discarding {*this, true}; for (uint32_t count {length_to_read}; count < sequence_length; ++count) { @@ -2426,18 +2415,9 @@ class Cdr } catch (exception::Exception& ex) { - if (i_set_fake) - { - fake_mode = false; - } set_state(state_before_error); ex.raise(); } - - if (i_set_fake) - { - fake_mode = false; - } } return *this; @@ -2470,7 +2450,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -2483,7 +2463,7 @@ class Cdr last_offset += dheader; uint32_t map_length {0}; - deserialize(map_length); + deserialize_framing(map_length); try { @@ -2514,7 +2494,7 @@ class Cdr { uint32_t sequence_length = 0; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2555,7 +2535,7 @@ class Cdr state state_(*this); std::map<_K, _T> map; - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2586,15 +2566,24 @@ class Cdr CdrTryConstructFlag consistency_flag, uint32_t max_length) { + state state_before_error(*this); + if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + 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(map_length); + deserialize_framing(map_length); map_t.clear(); @@ -2636,6 +2625,7 @@ class Cdr { if (offset_ - offset != dheader) { + set_state(state_before_error); throw exception::BadParamException("Member size greater than size specified by DHEADER"); } } @@ -2644,6 +2634,7 @@ class Cdr 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); } @@ -2652,9 +2643,8 @@ class Cdr else { uint32_t map_length = 0; - state state_(*this); - deserialize(map_length); + deserialize_framing(map_length); map_t.clear(); @@ -2664,7 +2654,6 @@ class Cdr } uint32_t length_to_read {map_length}; - bool i_set_fake {false}; if (map_length > max_length) { @@ -2693,34 +2682,26 @@ class Cdr map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); } - if (!fake_mode) + // 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 = true; - i_set_fake = true; - } + 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); + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } } } catch (exception::Exception& ex) { - if (i_set_fake) - { - fake_mode = false; - } - set_state(state_); + set_state(state_before_error); ex.raise(); } - - if (i_set_fake) - { - fake_mode = false; - } } return *this; @@ -2758,7 +2739,7 @@ class Cdr uint32_t map_length = 0; state state_(*this); - deserialize(map_length); + deserialize_framing(map_length); map_t.clear(); @@ -2768,7 +2749,6 @@ class Cdr } uint32_t length_to_read {map_length}; - bool i_set_fake {false}; if (map_length > max_length) { @@ -2797,35 +2777,27 @@ class Cdr map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); } - if (!fake_mode) + // 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 = true; - i_set_fake = true; - } + 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); + for (uint32_t i {length_to_read}; i < map_length; ++i) + { + _K key; + _T value; + deserialize(key); + deserialize(value); + } } } catch (exception::Exception& ex) { - if (i_set_fake) - { - fake_mode = false; - } set_state(state_); ex.raise(); } - if (i_set_fake) - { - fake_mode = false; - } - return *this; } @@ -3146,7 +3118,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if ((end_ - offset_) < dheader) { @@ -3260,7 +3232,7 @@ class Cdr if (CdrVersion::XCDRv2 == cdr_version_) { uint32_t dheader {0}; - deserialize(dheader); + deserialize_framing(dheader); if (((end_ - offset_) < dheader) || (dheader < 4)) { @@ -3272,7 +3244,7 @@ class Cdr auto last_offset = offset_; last_offset += dheader; - deserialize(sequence_length); + deserialize_framing(sequence_length); if (0 == sequence_length) { sequence_t = NULL; @@ -3313,7 +3285,7 @@ class Cdr } else { - deserialize(sequence_length); + deserialize_framing(sequence_length); if ((end_ - offset_) < sequence_length) { @@ -3358,7 +3330,7 @@ class Cdr uint32_t sequence_length = 0; state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -3694,7 +3666,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) @@ -3750,7 +3722,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) @@ -3906,6 +3878,65 @@ 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_; + }; + + /*! + * @brief Decodes a value that determines how the rest of the stream is read, such as a length, a DHEADER, a + * member header or a presence flag. + * + * Unlike the regular @c deserialize overloads, the value is always stored, also in @c fake_mode . Discarded + * elements are decoded in fake mode, and they still need these values to consume exactly the bytes they occupy. + * @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); + } + + 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); diff --git a/include/fastcdr/CdrEncoding.hpp b/include/fastcdr/CdrEncoding.hpp index e48c3d36..ed00885e 100644 --- a/include/fastcdr/CdrEncoding.hpp +++ b/include/fastcdr/CdrEncoding.hpp @@ -49,15 +49,15 @@ typedef enum : uint8_t } 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. -typedef enum +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 trims the serialized data so it can be assigned to the type used for deserialization. + //! @brief Cdr will trim the serialized data so it can be assigned to the type used for deserialization. TRIM = 2 -} CdrTryConstructFlag; +}; } // namespace fastcdr } // namespace eprosima diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index e9de7f9b..5093f3dd 100644 --- a/src/cpp/Cdr.cpp +++ b/src/cpp/Cdr.cpp @@ -1698,7 +1698,7 @@ Cdr& Cdr::deserialize( uint32_t length = 0; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1732,7 +1732,7 @@ Cdr& Cdr::deserialize( uint32_t length = 0; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1767,7 +1767,7 @@ Cdr& Cdr::deserialize( uint32_t length {0}; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1835,7 +1835,7 @@ Cdr& Cdr::deserialize( uint32_t length = 0; Cdr::state state_before_error(*this); - deserialize(length); + deserialize_framing(length); if (length == 0) { @@ -1891,6 +1891,20 @@ Cdr& Cdr::deserialize( throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } +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) @@ -1899,7 +1913,7 @@ const char* Cdr::read_string( uint32_t read_length {0}; state state_before_error(*this); - *this >> read_length; + deserialize_framing(read_length); if (read_length == 0) { @@ -1965,7 +1979,7 @@ const std::wstring Cdr::read_wstring( uint32_t read_length {0}; state state_(*this); - *this >> read_length; + deserialize_framing(read_length); uint32_t bytes_length = read_length * 2; if (bytes_length == 0) @@ -2633,7 +2647,7 @@ Cdr& Cdr::deserialize_bool_sequence( uint32_t sequence_length {0}; state state_before_error(*this); - *this >> sequence_length; + deserialize_framing(sequence_length); vector_t.clear(); @@ -2706,11 +2720,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 { @@ -2739,7 +2753,7 @@ Cdr& Cdr::deserialize_string_sequence( { state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2768,11 +2782,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 { @@ -2801,7 +2815,7 @@ Cdr& Cdr::deserialize_wstring_sequence( { state state_before_error(*this); - deserialize(sequence_length); + deserialize_framing(sequence_length); try { @@ -2923,7 +2937,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); @@ -2932,7 +2946,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(); @@ -2940,22 +2954,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"); @@ -3455,7 +3469,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; @@ -3486,14 +3500,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); @@ -3636,7 +3650,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/type_consistency.cpp b/test/xcdr/type_consistency.cpp index 44c4db77..b6742af6 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -154,6 +154,156 @@ void deserialize( } // 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 + // ===================================================================================== // std::string // ===================================================================================== @@ -1194,6 +1344,76 @@ TEST_P(XCdrTypeConsistencyTest, StdVectorNonPrimitive_Trim) 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 @@ -1547,6 +1767,76 @@ TEST_P(XCdrTypeConsistencyTest, StdMapNonPrimitive_Trim) 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 @@ -1737,6 +2027,226 @@ TEST_P(XCdrTypeConsistencyTest, StdVectorBoolStruct_TrimConsumesWholeSequence) 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); +} + INSTANTIATE_TEST_SUITE_P( XCdrTest, From a8e27201f1ac31afabfa16db1f9f145c8135b950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 27 Oct 2026 10:00:28 +0100 Subject: [PATCH 4/8] Refs #23437. Harden try-construct error handling and DHEADER checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reject XCDRv2 sequences and maps whose DHEADER does not match their elements. Before, a DHEADER that ran out before all the kept elements were read left the rest default-constructed. Kept elements that overran the DHEADER while trimming were accepted. FAIL now restores the stream to where it was before the call, as every other exception path does. The documentation no longer claims the stream is always fully consumed. The try-construct map overloads deserialize into a temporary map and only replace the destination when the whole deserialization succeeds, as the regular map overloads do. The TRIM documentation now matches the behaviour: the first max_length entries in wire order are kept. DEFAULT_VALUE and TRIM to zero characters on char* and wchar_t* now return an allocated empty string, as the std::string and std::wstring overloads do. FAIL leaves the pointer unchanged. Fix the plain wchar_t* deserialization not moving past the characters in fake mode. Add Doxygen for the non-primitive sequence and map overloads, use a map specific FAIL message, remove the dead policy switch in the fixed_string overload and a stray blank line. Add tests for FAIL leaving the stream and destination unchanged, for maps keeping their content on error, and for XCDRv2 DHEADER mismatches. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 265 ++++++++++++++++++------------ src/cpp/Cdr.cpp | 32 ++-- test/xcdr/type_consistency.cpp | 287 +++++++++++++++++++++++++++++++-- 3 files changed, 456 insertions(+), 128 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index 800b0ac1..9ba4b4d8 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -1766,10 +1766,16 @@ class Cdr * @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 resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . - * - @ref CdrTryConstructFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @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. @@ -1800,10 +1806,16 @@ class Cdr * @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 resets @p string_t to @c nullptr , and throws @ref exception::BadParamException . - * - @ref CdrTryConstructFlag::DEFAULT_VALUE resets @p string_t to @c nullptr . + * - @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. @@ -1839,8 +1851,11 @@ class Cdr * @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 . * - * The stream is always fully consumed first. If the string read is longer than @p max_length - * characters, not counting the terminating null character when the encoder serialized one: + * 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 . @@ -1883,8 +1898,11 @@ class Cdr * @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 . * - * The stream is always fully consumed first. If the number of wide characters read is larger - * than @p max_length (no terminating null character is serialized, so every character counts): + * 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 . @@ -1928,8 +1946,11 @@ class Cdr * @brief Decodes a fixed string applying a type consistency policy when the deserialized * string does not fit in @c MAX_CHARS . * - * The stream is always fully consumed first. When the number of characters read, excluding - * the terminating null character, is larger than @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 @@ -1951,20 +1972,6 @@ class Cdr { uint32_t length {MAX_CHARS}; const char* str = read_string(length, consistency_flag); - if (length > MAX_CHARS) - { - switch (consistency_flag) - { - case CdrTryConstructFlag::FAIL: - throw exception::BadParamException( - "Deserialized string length exceeds the fixed_string maximum size"); - case CdrTryConstructFlag::DEFAULT_VALUE: - value = fixed_string{}; - return *this; - case CdrTryConstructFlag::TRIM: - break; - } - } value.assign(str, length); return *this; } @@ -2183,18 +2190,16 @@ class Cdr } /*! - * @brief This function template deserializes a sequence applying a type consistency policy + * @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 . * - * The stream is always fully consumed first. After deserialization, if the resulting - * sequence is longer than @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 clears @p vector_t . - * - @ref CdrTryConstructFlag::TRIM resizes @p vector_t to @p max_length . + * - @ref CdrTryConstructFlag::DEFAULT_VALUE leaves @p vector_t empty. + * - @ref CdrTryConstructFlag::TRIM keeps the first @p max_length elements. * - * The overload covers all element types, including @c bool , primitives, enumerations and - * user-defined types, dispatching through the regular @c deserialize overload to read the - * sequence before applying the policy. + * 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 . @@ -2237,6 +2242,7 @@ class Cdr 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: @@ -2276,6 +2282,27 @@ class Cdr 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( @@ -2316,6 +2343,7 @@ class Cdr 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: @@ -2323,31 +2351,38 @@ class Cdr break; case CdrTryConstructFlag::TRIM: length_to_read = max_length; - vector_t.resize(length_to_read); break; } } - else - { - vector_t.resize(length_to_read); - } + + vector_t.resize(length_to_read); uint32_t count {0}; - while (offset_ - offset < dheader && count < length_to_read) - { - deserialize(vector_t.data()[count]); - ++count; - } - if (sequence_length == length_to_read) + try { - if (offset_ - offset != dheader) + while (offset_ - offset < dheader && count < length_to_read) { - set_state(state_before_error); - throw exception::BadParamException("Member size differs from the size specified by DHEADER"); + deserialize(vector_t.data()[count]); + ++count; } } - else if (offset_ - offset < dheader) + 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)) @@ -2383,6 +2418,7 @@ class Cdr 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: @@ -2559,6 +2595,29 @@ 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( @@ -2567,6 +2626,7 @@ class Cdr uint32_t max_length) { state state_before_error(*this); + std::map<_K, _T> map; if (CdrVersion::XCDRv2 == cdr_version_) { @@ -2585,13 +2645,6 @@ class Cdr uint32_t map_length {0}; deserialize_framing(map_length); - map_t.clear(); - - if (0 == map_length) - { - return *this; - } - uint32_t length_to_read {map_length}; if (map_length > max_length) @@ -2599,8 +2652,9 @@ class Cdr 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"); + "Serialized map contains more entries than the destination map can hold"); case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; @@ -2611,25 +2665,35 @@ class Cdr } uint32_t count {0}; - while (offset_ - offset < dheader && count < length_to_read) - { - _K key; - _T val; - deserialize(key); - deserialize(val); - map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(val))); - ++count; - } - if (map_length == length_to_read) + try { - if (offset_ - offset != dheader) + while (offset_ - offset < dheader && count < length_to_read) { - set_state(state_before_error); - throw exception::BadParamException("Member size greater than size specified by DHEADER"); + _K key; + _T value; + deserialize(key); + deserialize(value); + map.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + ++count; } } - else if (offset_ - offset < dheader) + 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)) @@ -2642,17 +2706,9 @@ class Cdr } else { - uint32_t map_length = 0; - + uint32_t map_length {0}; deserialize_framing(map_length); - map_t.clear(); - - if (map_length == 0) - { - return *this; - } - uint32_t length_to_read {map_length}; if (map_length > max_length) @@ -2660,8 +2716,9 @@ class Cdr 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"); + "Serialized map contains more entries than the destination map can hold"); case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; @@ -2673,13 +2730,13 @@ class Cdr try { - for (uint32_t i = 0; i < length_to_read; ++i) + for (uint32_t i {0}; i < length_to_read; ++i) { _K key; _T value; deserialize(key); deserialize(value); - map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(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 @@ -2704,30 +2761,33 @@ class Cdr } } + map_t = std::move(map); + return *this; } /*! - * @brief This function template deserializes a map applying a type consistency policy when - * the serialized length exceeds the supplied @p max_length . + * @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 stream is always fully consumed first. After deserialization, if the resulting map - * has more than @p max_length entries: + * 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 clears @p map_t . - * - @ref CdrTryConstructFlag::TRIM erases the highest-keyed entries until @p map_t - * holds exactly @p max_length entries. + * - @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 overload covers both primitive and non-primitive value types, dispatching through the - * regular @c deserialize overload to read the map before applying the policy. + * 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 length exceeds @p max_length . + * @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 length exceeds @p max_length . + * @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> @@ -2736,18 +2796,12 @@ class Cdr CdrTryConstructFlag consistency_flag, uint32_t max_length) { - uint32_t map_length = 0; - state state_(*this); + state state_before_error(*this); + std::map<_K, _T> map; + uint32_t map_length {0}; deserialize_framing(map_length); - map_t.clear(); - - if (map_length == 0) - { - return *this; - } - uint32_t length_to_read {map_length}; if (map_length > max_length) @@ -2755,8 +2809,9 @@ class Cdr 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"); + "Serialized map contains more entries than the destination map can hold"); case CdrTryConstructFlag::DEFAULT_VALUE: length_to_read = 0; break; @@ -2774,7 +2829,7 @@ class Cdr _T value; deserialize(key); deserialize(value); - map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(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 @@ -2794,10 +2849,12 @@ class Cdr } catch (exception::Exception& ex) { - set_state(state_); + set_state(state_before_error); ex.raise(); } + map_t = std::move(map); + return *this; } diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index 5093f3dd..81810efd 100644 --- a/src/cpp/Cdr.cpp +++ b/src/cpp/Cdr.cpp @@ -1549,7 +1549,6 @@ Cdr& Cdr::deserialize( } else { - offset_ += sizeof(double_t); } @@ -1751,6 +1750,10 @@ Cdr& Cdr::deserialize( deserialize_array(string_t, length); } + else + { + offset_ += length * 2; + } return *this; } @@ -1793,11 +1796,10 @@ Cdr& Cdr::deserialize( switch (consistency_flag) { case CdrTryConstructFlag::FAIL: - string_t = nullptr; + set_state(state_before_error); throw BadParamException( "Deserialized string length exceeds the maximum length allowed by the destination type"); case CdrTryConstructFlag::DEFAULT_VALUE: - string_t = nullptr; length_to_read = 0; break; case CdrTryConstructFlag::TRIM: @@ -1809,17 +1811,17 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint8_t); - if (0 < length_to_read && !fake_mode) + 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. + // 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); @@ -1851,11 +1853,10 @@ Cdr& Cdr::deserialize( switch (consistency_flag) { case CdrTryConstructFlag::FAIL: - string_t = nullptr; + set_state(state_before_error); throw BadParamException( "Deserialized wide string length exceeds the maximum length allowed by the destination type"); case CdrTryConstructFlag::DEFAULT_VALUE: - string_t = nullptr; length_to_read = 0; break; case CdrTryConstructFlag::TRIM: @@ -1869,13 +1870,12 @@ Cdr& Cdr::deserialize( if (!fake_mode) { - if (0 < length_to_read) - { - // Allocate memory. - string_t = reinterpret_cast(calloc(length_to_read + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero + // 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); - } + deserialize_array(string_t, length_to_read); offset_ += (length - length_to_read) * 2; } @@ -1939,6 +1939,7 @@ const char* Cdr::read_string( 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: @@ -1995,6 +1996,7 @@ const std::wstring Cdr::read_wstring( 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: @@ -2662,6 +2664,7 @@ Cdr& Cdr::deserialize_bool_sequence( 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: @@ -2696,6 +2699,7 @@ 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"); } } diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp index b6742af6..4ee19fb8 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include "utility.hpp" using namespace eprosima::fastcdr; @@ -714,13 +715,13 @@ TEST_P(XCdrTypeConsistencyTest, CharPtr_Fail) /*! * @brief Checks that @c DEFAULT_VALUE discards a C string longer than the bound. * - * For a raw pointer the discarded value is represented by a null pointer, so nothing needs to be released. The - * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * 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 leaves the destination pointer - * 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) { @@ -737,7 +738,9 @@ TEST_P(XCdrTypeConsistencyTest, CharPtr_DefaultValue) char* output {nullptr}; ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); - EXPECT_EQ(output, nullptr); + ASSERT_NE(output, nullptr); + EXPECT_STREQ(output, ""); + free(output); } /*! @@ -876,13 +879,14 @@ TEST_P(XCdrTypeConsistencyTest, WcharPtr_Fail) /*! * @brief Checks that @c DEFAULT_VALUE discards a C wide string longer than the bound. * - * For a raw pointer the discarded value is represented by a null pointer, so nothing needs to be released. The - * case is repeated for XCDRv1 and XCDRv2, in big and little endian. + * 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 leaves the destination pointer - * 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) { @@ -899,7 +903,9 @@ TEST_P(XCdrTypeConsistencyTest, WcharPtr_DefaultValue) wchar_t* output {nullptr}; ASSERT_NO_THROW(cdr_des.deserialize(output, CdrTryConstructFlag::DEFAULT_VALUE, 5)); - EXPECT_EQ(output, nullptr); + ASSERT_NE(output, nullptr); + EXPECT_EQ(std::wcscmp(output, L""), 0); + free(output); } /*! @@ -2247,6 +2253,139 @@ TEST_P(XCdrTypeConsistencyTest, StdVectorOptionalStruct_TrimConsumesWholeSequenc 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); +} + INSTANTIATE_TEST_SUITE_P( XCdrTest, @@ -2257,3 +2396,131 @@ INSTANTIATE_TEST_SUITE_P( 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 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); +} From 9f283aef149a062a2b8cde3c7155d7203a84f897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 27 Oct 2026 10:32:05 +0100 Subject: [PATCH 5/8] Refs #23437. Make deserialize_framing public for union discriminators MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Elements discarded by a try-construct policy are consumed in fake mode, where the regular deserialize overloads do not store the decoded values. Generated unions read their discriminator with operator>>, so a discarded union kept the default discriminator, decoded the wrong member and left the stream misaligned without raising any error. This affected XCDRv1, where discarded non-primitive elements are consumed one by one. Move deserialize_framing to the public API, documenting that code decoding a type whose layout depends on a value it reads, like a union discriminator, must decode that value with it. Fast DDS-Gen generated code is updated to use it for union discriminators. Add tests with a union-like type, (de)serialized as Fast DDS-Gen generates it, checking that trimming or discarding a sequence of unions leaves the stream just past the sequence. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 46 +++++---- test/xcdr/type_consistency.cpp | 183 +++++++++++++++++++++++++++++++++ 2 files changed, 210 insertions(+), 19 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index 9ba4b4d8..2d3a3bd7 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -391,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. * @@ -3970,25 +3997,6 @@ class Cdr bool previous_; }; - /*! - * @brief Decodes a value that determines how the rest of the stream is read, such as a length, a DHEADER, a - * member header or a presence flag. - * - * Unlike the regular @c deserialize overloads, the value is always stored, also in @c fake_mode . Discarded - * elements are decoded in fake mode, and they still need these values to consume exactly the bytes they occupy. - * @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); - } - Cdr_DllAPI const char* read_string( uint32_t& length); Cdr_DllAPI const std::wstring read_wstring( diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp index 4ee19fb8..eb7eb2fd 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -305,6 +305,114 @@ void deserialize( } // 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 // ===================================================================================== @@ -2386,6 +2494,81 @@ TEST_P(XCdrTypeConsistencyTest, StdMapPrimitive_ErrorKeepsDestination) 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, From 6646fea3db3ca86018cddd98a7af5df514f88790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 3 Nov 2026 11:03:10 +0100 Subject: [PATCH 6/8] Refs #23437. Validate sequence length against DHEADER before allocating MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The try-construct overload for XCDRv2 sequences of non-primitive types resized the destination before checking that the announced length fits in the DHEADER. A malformed eight-byte input with a DHEADER of 4 and a length of 1000000 allocated a million elements, then threw BadParamException from the per-element DHEADER check. The regular overload rejects that input without allocating. Check that the length does not exceed the bytes left in the DHEADER, as the regular overload does, since every element takes at least one byte. The check runs before the policy is applied, so DEFAULT_VALUE and TRIM reject the malformed sequence too, and it restores the stream before throwing NotEnoughMemoryException. Move the resize inside the try block, as in the regular overload. Add a test with that input, checking for every policy that the call throws NotEnoughMemoryException, allocates nothing and leaves the stream at its start. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 11 +++++++++-- test/xcdr/type_consistency.cpp | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index 2d3a3bd7..95224063 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -2363,6 +2363,13 @@ class Cdr return *this; } + 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) @@ -2382,12 +2389,12 @@ class Cdr } } - vector_t.resize(length_to_read); - uint32_t count {0}; try { + vector_t.resize(length_to_read); + while (offset_ - offset < dheader && count < length_to_read) { deserialize(vector_t.data()[count]); diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp index eb7eb2fd..469f9fc2 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -2639,6 +2640,39 @@ TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_DheaderTooSmall) 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 a truncated sequence whose kept elements overrun the DHEADER is rejected. * From b3e6ccfc4e41f67216c965df58d0408aea5ae2d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 3 Nov 2026 11:18:38 +0100 Subject: [PATCH 7/8] Refs #23437. Check DHEADER for empty non-primitive sequences MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The try-construct overload for XCDRv2 sequences of non-primitive types returned as soon as it read a length of 0, without checking that the bytes read matched the DHEADER. With a DHEADER larger than 4, the unread bytes stayed in the stream and later reads started at the wrong offset. The regular overload rejects that input. Remove the early return so empty sequences go through the final DHEADER check. That check throws BadParamException and restores the stream when the bytes read differ from the DHEADER. A valid empty sequence, with a DHEADER of 4, still returns an empty vector. Add a test with a DHEADER of 8 and a length of 0, checking for every policy that the call throws BadParamException, leaves the destination empty and leaves the stream at its start. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 5 ----- test/xcdr/type_consistency.cpp | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index 95224063..f29fca3e 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -2358,11 +2358,6 @@ class Cdr vector_t.clear(); - if (0 == sequence_length) - { - return *this; - } - if ((dheader - static_cast(offset_ - offset)) < sequence_length) { set_state(state_before_error); diff --git a/test/xcdr/type_consistency.cpp b/test/xcdr/type_consistency.cpp index 469f9fc2..d3e9244c 100644 --- a/test/xcdr/type_consistency.cpp +++ b/test/xcdr/type_consistency.cpp @@ -2673,6 +2673,38 @@ TEST(XCdrTypeConsistencyDheaderTest, StdVectorNonPrimitive_LengthExceedsDheader) } } +/*! + * @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. * From dc2bc14175df31dea4c2a98722ee96b8277ca3ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Gonz=C3=A1lez=20Moreno?= Date: Tue, 3 Nov 2026 11:24:38 +0100 Subject: [PATCH 8/8] Refs #23437. Move fake_mode_ into existing padding to preserve ABI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Place the fake deserialization flag right after encapsulation_serialized_ so it fits in the padding before context_, keeping sizeof(Cdr) unchanged with respect to master. Rename it to fake_mode_ to match the naming of the other members. Signed-off-by: Ricardo González Moreno --- include/fastcdr/Cdr.h | 14 ++++++------- src/cpp/Cdr.cpp | 46 +++++++++++++++++++++---------------------- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/include/fastcdr/Cdr.h b/include/fastcdr/Cdr.h index f29fca3e..ded8b543 100644 --- a/include/fastcdr/Cdr.h +++ b/include/fastcdr/Cdr.h @@ -3965,7 +3965,7 @@ class Cdr size_t min_size_inc); /*! - * @brief Sets @c fake_mode for the lifetime of the object, restoring its previous value on destruction + * @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 @@ -3976,14 +3976,14 @@ class Cdr Cdr& cdr, bool enabled) : cdr_(cdr) - , previous_(cdr.fake_mode) + , previous_(cdr.fake_mode_) { - cdr_.fake_mode = enabled; + cdr_.fake_mode_ = enabled; } ~fake_mode_scope() { - cdr_.fake_mode = previous_; + cdr_.fake_mode_ = previous_; } fake_mode_scope( @@ -4497,12 +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_; - //! Whether fake deserialization mode is enabled. - bool fake_mode {false}; - uint32_t get_long_lc( SerializedMemberSizeForNextInt serialized_member_size); diff --git a/src/cpp/Cdr.cpp b/src/cpp/Cdr.cpp index 81810efd..4f40d2b8 100644 --- a/src/cpp/Cdr.cpp +++ b/src/cpp/Cdr.cpp @@ -1338,7 +1338,7 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(char_t); - if (!fake_mode) + if (!fake_mode_) { offset_++ >> char_t; } @@ -1364,7 +1364,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(short_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1402,7 +1402,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(long_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1442,7 +1442,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1486,7 +1486,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = sizeof(float_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1526,7 +1526,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1570,7 +1570,7 @@ Cdr& Cdr::deserialize( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -1664,7 +1664,7 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint8_t); - if (!fake_mode) + if (!fake_mode_) { offset_++ >> value; @@ -1710,7 +1710,7 @@ Cdr& Cdr::deserialize( last_data_size_ = sizeof(uint8_t); // Allocate memory. - if (!fake_mode) + if (!fake_mode_) { string_t = reinterpret_cast(calloc(length + ((&offset_)[length - 1] == '\0' ? 0 : 1), @@ -1743,7 +1743,7 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint16_t); - if (!fake_mode) + if (!fake_mode_) { // Allocate memory. string_t = reinterpret_cast(calloc(length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero @@ -1811,7 +1811,7 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint8_t); - if (!fake_mode) + 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 @@ -1868,7 +1868,7 @@ Cdr& Cdr::deserialize( // Save last datasize. last_data_size_ = sizeof(uint16_t); - if (!fake_mode) + 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 @@ -1956,7 +1956,7 @@ const char* Cdr::read_string( // 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; + length = fake_mode_ ? 0 : length_to_read; if (length > 0) { @@ -2013,9 +2013,9 @@ const std::wstring Cdr::read_wstring( // 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; + length = fake_mode_ ? 0 : length_to_read; - if (!fake_mode) + if (!fake_mode_) { if (length_to_read > 0) { @@ -2052,7 +2052,7 @@ Cdr& Cdr::deserialize_array( // Save last datasize. last_data_size_ = sizeof(*bool_t); - if (!fake_mode) + if (!fake_mode_) { for (size_t count = 0; count < num_elements; ++count) { @@ -2091,7 +2091,7 @@ Cdr& Cdr::deserialize_array( // Save last datasize. last_data_size_ = sizeof(*char_t); - if (!fake_mode) + if (!fake_mode_) { offset_.rmemcopy(char_t, total_size); } @@ -2121,7 +2121,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*short_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -2170,7 +2170,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*long_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -2239,7 +2239,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -2294,7 +2294,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = sizeof(*float_t); - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -2345,7 +2345,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { if (swap_bytes_) { @@ -2401,7 +2401,7 @@ Cdr& Cdr::deserialize_array( make_alignment(align); last_data_size_ = align64_; - if (!fake_mode) + if (!fake_mode_) { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 if (swap_bytes_)