Fix buffer printing in json value to string

This commit is contained in:
Vinnie Falco
2013-10-02 11:59:32 -07:00
parent 0a5505f785
commit bbbb8b1411

View File

@@ -77,55 +77,21 @@ std::string valueToString ( UInt value )
return current;
}
std::string valueToString ( double value )
std::string valueToString( double value )
{
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning.
sprintf_s (buffer, sizeof (buffer), "%#f", value);
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with visual studio 2005 to avoid warning.
sprintf_s(buffer, sizeof(buffer), "%.16g", value);
#else
sprintf (buffer, "%#f", value);
snprintf(buffer, sizeof(buffer), "%.16g", value);
#endif
char* ch = buffer + strlen (buffer) - 1;
if (*ch != '0') return buffer; // nothing to truncate, so save time
while (ch > buffer && *ch == '0')
{
--ch;
}
char* last_nonzero = ch;
while (ch >= buffer)
{
switch (*ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
--ch;
continue;
case '.':
// Truncate zeroes to save bytes in output, but keep one.
* (last_nonzero + 2) = '\0';
return buffer;
default:
return buffer;
}
}
return buffer;
}
}
std::string valueToString ( bool value )
{