async_mqtt 4.1.0
Loading...
Searching...
No Matches
json_like_out.hpp
1// Copyright Takatoshi Kondo 2022
2//
3// Distributed under the Boost Software License, Version 1.0.
4// (See accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7#if !defined(ASYNC_MQTT_UTIL_JSON_LIKE_OUT_HPP)
8#define ASYNC_MQTT_UTIL_JSON_LIKE_OUT_HPP
9
10#include <ostream>
11#include <iomanip>
12
13#include <async_mqtt/buffer.hpp>
14
15namespace async_mqtt {
16
17struct json_like_out_t {
18 json_like_out_t(buffer const& buf): buf{buf} {}
19
20 buffer const& buf;
21};
22
23inline std::ostream& operator<<(std::ostream& o, json_like_out_t const& v) {
24 for (char c : v.buf) {
25 switch (c) {
26 case '\\':
27 o << "\\\\";
28 break;
29 case '"':
30 o << "\\\"";
31 break;
32 case '/':
33 o << "\\/";
34 break;
35 case '\b':
36 o << "\\b";
37 break;
38 case '\f':
39 o << "\\f";
40 break;
41 case '\n':
42 o << "\\n";
43 break;
44 case '\r':
45 o << "\\r";
46 break;
47 case '\t':
48 o << "\\t";
49 break;
50 default: {
51 unsigned int code = static_cast<unsigned int>(c);
52 if (code < 0x20 || code >= 0x7f) {
53 std::ios::fmtflags flags(o.flags());
54 o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (code & 0xff);
55 o.flags(flags);
56 }
57 else {
58 o << c;
59 }
60 } break;
61 }
62 }
63 return o;
64}
65
66inline json_like_out_t json_like_out(buffer const& buf) {
67 return json_like_out_t{buf};
68}
69
70} // namespace async_mqtt
71
72#endif // ASYNC_MQTT_UTIL_JSON_LIKE_OUT_HPP