| 180 | static const double kDoublePrecisionCheckMax = DBL_MAX / 1.000000000000001; |
| 181 | |
| 182 | size_t DoubleToBuffer(double value, char* buffer) { |
| 183 | // DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all |
| 184 | // platforms these days. Just in case some system exists where DBL_DIG |
| 185 | // is significantly larger -- and risks overflowing our buffer -- we have |
| 186 | // this assert. |
| 187 | static_assert(DBL_DIG < 20, "DBL_DIG is too big"); |
| 188 | |
| 189 | if (std::abs(value) <= kDoublePrecisionCheckMax) { |
| 190 | int snprintf_result = |
| 191 | snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value); |
| 192 | |
| 193 | // The snprintf should never overflow because the buffer is significantly |
| 194 | // larger than the precision we asked for. |
| 195 | DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); |
| 196 | |
| 197 | if (locale_independent_strtonum<double>(buffer, nullptr) == value) { |
| 198 | // Round-tripping the string to double works; we're done. |
| 199 | return snprintf_result; |
| 200 | } |
| 201 | // else: full precision formatting needed. Fall through. |
| 202 | } |
| 203 | |
| 204 | int snprintf_result = |
| 205 | snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG + 2, value); |
| 206 | |
| 207 | // Should never overflow; see above. |
| 208 | DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize); |
| 209 | |
| 210 | return snprintf_result; |
| 211 | } |
| 212 | |
| 213 | namespace { |
| 214 | char SafeFirstChar(StringPiece str) { |
no test coverage detected