Prevent overflow on size type conversion

This commit is contained in:
Martchus 2017-11-04 15:15:12 +01:00
parent a4fac7c515
commit f212fc8de7
2 changed files with 12 additions and 2 deletions

View File

@ -24,7 +24,7 @@ inline void push<ChronoUtilities::DateTime>(
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<ChronoUtilities::TimeSpan>(
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

View File

@ -15,6 +15,7 @@
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <limits>
#include <string>
#include <tuple>
@ -26,6 +27,15 @@ template <typename Type> 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<RAPIDJSON_NAMESPACE::SizeType>::max() ? std::numeric_limits<RAPIDJSON_NAMESPACE::SizeType>::max()
: static_cast<RAPIDJSON_NAMESPACE::SizeType>(size);
}
/*!
* \brief Serializes the specified JSON \a document.
*/