Zserio C++ runtime library  1.0.2
Built for Zserio 2.14.1
JsonEncoder.cpp
Go to the documentation of this file.
1 #include <array>
2 #include <cmath>
3 #include <iomanip>
4 
5 #include "zserio/JsonEncoder.h"
6 
7 namespace zserio
8 {
9 
10 void JsonEncoder::encodeNull(std::ostream& stream)
11 {
12  stream << "null";
13 }
14 
15 void JsonEncoder::encodeBool(std::ostream& stream, bool value)
16 {
17  stream << std::boolalpha << value << std::noboolalpha;
18 }
19 
20 void 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 
50 void JsonEncoder::encodeString(std::ostream& stream, StringView value)
51 {
52  static const std::array<char, 17> HEX = {"0123456789abcdef"};
53 
54  stream.put('"');
55  for (char character : value)
56  {
57  switch (character)
58  {
59  case '\\':
60  case '"':
61  stream.put('\\');
62  stream.put(character);
63  break;
64  case '\b':
65  stream.put('\\');
66  stream.put('b');
67  break;
68  case '\f':
69  stream.put('\\');
70  stream.put('f');
71  break;
72  case '\n':
73  stream.put('\\');
74  stream.put('n');
75  break;
76  case '\r':
77  stream.put('\\');
78  stream.put('r');
79  break;
80  case '\t':
81  stream.put('\\');
82  stream.put('t');
83  break;
84  default:
85  if (static_cast<uint8_t>(character) <= 0x1F)
86  {
87  stream.put('\\');
88  stream.put('u');
89  stream.put('0');
90  stream.put('0');
91  stream.put(HEX[static_cast<uint8_t>(static_cast<uint8_t>(character) >> 4U) & 0xFU]);
92  stream.put(HEX[static_cast<uint8_t>(character) & 0xFU]);
93  }
94  else
95  {
96  stream.put(character);
97  }
98  break;
99  }
100  }
101  stream.put('"');
102 }
103 
104 } // namespace zserio
static void encodeFloatingPoint(std::ostream &stream, double value)
Definition: JsonEncoder.cpp:20
static void encodeNull(std::ostream &stream)
Definition: JsonEncoder.cpp:10
static void encodeBool(std::ostream &stream, bool value)
Definition: JsonEncoder.cpp:15
static void encodeString(std::ostream &stream, StringView value)
Definition: JsonEncoder.cpp:50