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