From f212fc8de784519da02e14cd8a3810eab0082b3b Mon Sep 17 00:00:00 2001 From: Martchus Date: Sat, 4 Nov 2017 15:15:12 +0100 Subject: [PATCH] Prevent overflow on size type conversion --- lib/json/reflector-chronoutilities.h | 4 ++-- lib/json/reflector.h | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/json/reflector-chronoutilities.h b/lib/json/reflector-chronoutilities.h index 08f0867..ee24ace 100644 --- a/lib/json/reflector-chronoutilities.h +++ b/lib/json/reflector-chronoutilities.h @@ -24,7 +24,7 @@ inline void push( const ChronoUtilities::DateTime &reflectable, RAPIDJSON_NAMESPACE::Value &value, RAPIDJSON_NAMESPACE::Document::AllocatorType &allocator) { const std::string str(reflectable.toIsoString()); - value.SetString(str.data(), str.size(), allocator); + value.SetString(str.data(), rapidJsonSize(str.size()), allocator); } template <> @@ -32,7 +32,7 @@ inline void push( const ChronoUtilities::TimeSpan &reflectable, RAPIDJSON_NAMESPACE::Value &value, RAPIDJSON_NAMESPACE::Document::AllocatorType &allocator) { const std::string str(reflectable.toString()); - value.SetString(str.data(), str.size(), allocator); + value.SetString(str.data(), rapidJsonSize(str.size()), allocator); } // define functions to "pull" values from a RapidJSON array or object diff --git a/lib/json/reflector.h b/lib/json/reflector.h index b31b424..25219f7 100644 --- a/lib/json/reflector.h +++ b/lib/json/reflector.h @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -26,6 +27,15 @@ template struct JsonSerializable; namespace JsonReflector { +/*! + * \brief Casts the specified \a size to the size type used by RapidJSON ensuring no overflow happens. + */ +constexpr RAPIDJSON_NAMESPACE::SizeType rapidJsonSize(std::size_t size) +{ + return size > std::numeric_limits::max() ? std::numeric_limits::max() + : static_cast(size); +} + /*! * \brief Serializes the specified JSON \a document. */