Skip to content

Commit 8145192

Browse files
authored
Merge pull request #1845 from joto/json-numbers
Handle non-normal floating point numbers in JSON writer
2 parents eff5b95 + 3d5ef01 commit 8145192

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/json-writer.hpp

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313
#include "format.hpp"
1414

1515
#include <cassert>
16+
#include <cmath>
1617
#include <iterator>
1718
#include <string>
19+
#include <type_traits>
1820

1921
class json_writer_t
2022
{
@@ -23,7 +25,18 @@ class json_writer_t
2325

2426
void boolean(bool value) { m_buffer.append(value ? "true" : "false"); }
2527

26-
template <typename T>
28+
template <typename T,
29+
std::enable_if_t<std::is_floating_point_v<T>, bool> = true>
30+
void number(T value)
31+
{
32+
if (std::isfinite(value)) {
33+
fmt::format_to(std::back_inserter(m_buffer), "{}"_format(value));
34+
} else {
35+
null();
36+
}
37+
}
38+
39+
template <typename T, std::enable_if_t<std::is_integral_v<T>, bool> = true>
2740
void number(T value)
2841
{
2942
fmt::format_to(std::back_inserter(m_buffer), "{}"_format(value));

tests/test-json-writer.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,20 @@ TEST_CASE("json writer writes real number", "[NoDB]")
4646
REQUIRE(writer.json() == "3.141");
4747
}
4848

49+
TEST_CASE("json writer writes invalid real number as null", "[NoDB]")
50+
{
51+
json_writer_t writer;
52+
writer.number(INFINITY);
53+
REQUIRE(writer.json() == "null");
54+
}
55+
56+
TEST_CASE("json writer writes NaN as null", "[NoDB]")
57+
{
58+
json_writer_t writer;
59+
writer.number(NAN);
60+
REQUIRE(writer.json() == "null");
61+
}
62+
4963
TEST_CASE("json writer writes string", "[NoDB]")
5064
{
5165
json_writer_t writer;

0 commit comments

Comments
 (0)