Zserio C++ runtime library  1.0.1
Built for Zserio 2.14.0
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  stream << "-";
30  stream << "Infinity";
31  }
32  else
33  {
34  double intPart = 1e16;
35  const double fractPart = std::modf(value, &intPart);
36  // trying to get closer to behavior of Python
37  if (fractPart == 0.0 && intPart > -1e16 && intPart < 1e16)
38  {
39  stream << std::fixed << std::setprecision(1) << value << std::defaultfloat;
40  }
41  else
42  {
43  stream << std::setprecision(15) << value << std::defaultfloat;
44  }
45  }
46 }
47 
48 void JsonEncoder::encodeString(std::ostream& stream, StringView value)
49 {
50  static const std::array<char, 17> HEX = {"0123456789abcdef"};
51 
52  stream.put('"');
53  for (char character : value)
54  {
55  switch (character)
56  {
57  case '\\':
58  case '"':
59  stream.put('\\');
60  stream.put(character);
61  break;
62  case '\b':
63  stream.put('\\');
64  stream.put('b');
65  break;
66  case '\f':
67  stream.put('\\');
68  stream.put('f');
69  break;
70  case '\n':
71  stream.put('\\');
72  stream.put('n');
73  break;
74  case '\r':
75  stream.put('\\');
76  stream.put('r');
77  break;
78  case '\t':
79  stream.put('\\');
80  stream.put('t');
81  break;
82  default:
83  if (static_cast<uint8_t>(character) <= 0x1F)
84  {
85  stream.put('\\');
86  stream.put('u');
87  stream.put('0');
88  stream.put('0');
89  stream.put(HEX[static_cast<uint8_t>(static_cast<uint8_t>(character) >> 4U) & 0xFU]);
90  stream.put(HEX[static_cast<uint8_t>(character) & 0xFU]);
91  }
92  else
93  {
94  stream.put(character);
95  }
96  break;
97  }
98  }
99  stream.put('"');
100 }
101 
102 } // 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:48