From bbbb8b141114f5ebb2c61eb0ae7d59d099134c8b Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Oct 2013 11:59:32 -0700 Subject: [PATCH] Fix buffer printing in json value to string --- src/ripple/json/impl/json_writer.cpp | 54 ++++++---------------------- 1 file changed, 10 insertions(+), 44 deletions(-) diff --git a/src/ripple/json/impl/json_writer.cpp b/src/ripple/json/impl/json_writer.cpp index bd571432d..b93484bf7 100644 --- a/src/ripple/json/impl/json_writer.cpp +++ b/src/ripple/json/impl/json_writer.cpp @@ -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 ) {