Zserio C++17 runtime library 1.3.0
Built for Zserio 2.20.0
Loading...
Searching...
No Matches
JsonEncoder.cpp
Go to the documentation of this file.
1#include <array>
2#include <cmath>
3#include <iomanip>
4
6
7namespace zserio
8{
9
11{
12 stream << "null";
13}
14
15void JsonEncoder::encodeBool(std::ostream& stream, bool value)
16{
17 stream << std::boolalpha << value << std::noboolalpha;
18}
19
20void JsonEncoder::encodeFloatingPoint(std::ostream& stream, double value)
21{
22 if (std::isnan(value))
23 {
24 stream << "NaN";
25 }
26 else if (std::isinf(value))
27 {
28 if (value < 0.0)
29 {
30 stream << "-";
31 }
32 stream << "Infinity";
33 }
34 else
35 {
36 double intPart = 1e16;
37 const double fractPart = std::modf(value, &intPart);
38 // trying to get closer to behavior of Python
39 if (fractPart == 0.0 && intPart > -1e16 && intPart < 1e16)
40 {
41 stream << std::fixed << std::setprecision(1) << value << std::defaultfloat;
42 }
43 else
44 {
45 stream << std::setprecision(15) << value << std::defaultfloat;
46 }
47 }
48}
49
50void JsonEncoder::encodeString(std::ostream& stream, std::string_view value)
51{
52 static const std::array<char, 17> HEX = {"0123456789abcdef"};
53
54 (void)stream.put('"');
55 for (char character : value)
56 {
57 if (character == '\\' || character == '"')
58 {
59 (void)stream.put('\\');
60 (void)stream.put(character);
61 }
62 else if (character == '\b')
63 {
64 (void)stream.put('\\');
65 (void)stream.put('b');
66 }
67 else if (character == '\f')
68 {
69 (void)stream.put('\\');
70 (void)stream.put('f');
71 }
72 else if (character == '\n')
73 {
74 (void)stream.put('\\');
75 (void)stream.put('n');
76 }
77 else if (character == '\r')
78 {
79 (void)stream.put('\\');
80 (void)stream.put('r');
81 }
82 else if (character == '\t')
83 {
84 (void)stream.put('\\');
85 (void)stream.put('t');
86 }
87 else
88 {
89 const unsigned int characterInt =
90 static_cast<unsigned int>(std::char_traits<char>::to_int_type(character));
91 if (characterInt <= 0x1F)
92 {
93 (void)stream.put('\\');
94 (void)stream.put('u');
95 (void)stream.put('0');
96 (void)stream.put('0');
97 (void)stream.put(HEX[(characterInt >> 4U) & 0xFU]);
98 (void)stream.put(HEX[characterInt & 0xFU]);
99 }
100 else
101 {
102 (void)stream.put(character);
103 }
104 }
105 }
106 (void)stream.put('"');
107}
108
109} // namespace zserio
static void encodeFloatingPoint(std::ostream &stream, double value)
static void encodeNull(std::ostream &stream)
static void encodeBool(std::ostream &stream, bool value)
static void encodeString(std::ostream &stream, std::string_view value)