Make {Float,Double}ToBuffer uniform across platforms for NaNs

This came up when formatting numbers like a quiet NaN with the sign bit set.
MSVC's CRT formats this as "-nan(ind)" while glibc formats this as "-nan".

PiperOrigin-RevId: 335575642
Change-Id: I294801a002d74f5e391fe343ce6eace72e30a0c0
This commit is contained in:
David Majnemer 2020-10-05 22:58:19 -07:00 committed by TensorFlower Gardener
parent bebcbfe67c
commit 14f8cb17bc

View File

@ -186,6 +186,14 @@ size_t DoubleToBuffer(double value, char* buffer) {
// this assert.
static_assert(DBL_DIG < 20, "DBL_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
// Paranoid check to ensure we don't overflow the buffer.
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
if (std::abs(value) <= kDoublePrecisionCheckMax) {
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", DBL_DIG, value);
@ -365,6 +373,14 @@ size_t FloatToBuffer(float value, char* buffer) {
// this assert.
static_assert(FLT_DIG < 10, "FLT_DIG is too big");
if (std::isnan(value)) {
int snprintf_result = snprintf(buffer, kFastToBufferSize, "%snan",
std::signbit(value) ? "-" : "");
// Paranoid check to ensure we don't overflow the buffer.
DCHECK(snprintf_result > 0 && snprintf_result < kFastToBufferSize);
return snprintf_result;
}
int snprintf_result =
snprintf(buffer, kFastToBufferSize, "%.*g", FLT_DIG, value);