Make sure output of NaN, Infinity and -Infinity is identical on all platforms (#717)

Specifically, printing `.nan`, `.inf`, and `-.inf`, respectively, as per the spec section 10.2.1.4.
This commit is contained in:
Jeppe Blicher Tarp
2019-08-04 03:41:45 +02:00
committed by Jesse Beder
parent 0122697561
commit e0e01d53c2
2 changed files with 73 additions and 8 deletions

View File

@@ -7,10 +7,13 @@
#pragma once
#endif
#include <cmath>
#include <cstddef>
#include <limits>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include "yaml-cpp/binary.h"
#include "yaml-cpp/dll.h"
@@ -153,7 +156,28 @@ inline Emitter& Emitter::WriteStreamable(T value) {
std::stringstream stream;
SetStreamablePrecision<T>(stream);
stream << value;
bool special = false;
if (std::is_floating_point<T>::value) {
if ((std::numeric_limits<T>::has_quiet_NaN ||
std::numeric_limits<T>::has_signaling_NaN) &&
std::isnan(value)) {
special = true;
stream << ".nan";
} else if (std::numeric_limits<T>::has_infinity) {
if (value == std::numeric_limits<T>::infinity()) {
special = true;
stream << ".inf";
} else if (value == -std::numeric_limits<T>::infinity()) {
special = true;
stream << "-.inf";
}
}
}
if (!special) {
stream << value;
}
m_stream << stream.str();
StartedScalar();