1//
2// String.h
3//
4// Library: Foundation
5// Package: Core
6// Module: String
7//
8// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14#include "Poco/JSONString.h"
15#include "Poco/UTF8String.h"
16#include <ostream>
17
18
19namespace {
20
21
22template<typename T, typename S>
23struct WriteFunc
24{
25 typedef T& (T::*Type)(const char* s, S n);
26};
27
28
29
30template<typename T, typename S>
31void writeString(const std::string &value, T& obj, typename WriteFunc<T, S>::Type write, int options)
32{
33 bool wrap = ((options & Poco::JSON_WRAP_STRINGS) != 0);
34 bool escapeAllUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0);
35
36 if (value.size() == 0)
37 {
38 if(wrap) (obj.*write)("\"\"", 2);
39 return;
40 }
41
42 if(wrap) (obj.*write)("\"", 1);
43 if(escapeAllUnicode)
44 {
45 std::string str = Poco::UTF8::escape(value.begin(), value.end(), true);
46 (obj.*write)(str.c_str(), str.size());
47 }
48 else
49 {
50 for(std::string::const_iterator it = value.begin(), end = value.end(); it != end; ++it)
51 {
52 // Forward slash isn't strictly required by JSON spec, but some parsers expect it
53 if((*it >= 0 && *it <= 31) || (*it == '"') || (*it == '\\') || (*it == '/'))
54 {
55 std::string str = Poco::UTF8::escape(it, it + 1, true);
56 (obj.*write)(str.c_str(), str.size());
57 }else (obj.*write)(&(*it), 1);
58 }
59 }
60 if(wrap) (obj.*write)("\"", 1);
61};
62
63
64}
65
66
67namespace Poco {
68
69
70void toJSON(const std::string& value, std::ostream& out, bool wrap)
71{
72 int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
73 writeString<std::ostream,
74 std::streamsize>(value, out, &std::ostream::write, options);
75}
76
77
78std::string toJSON(const std::string& value, bool wrap)
79{
80 int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
81 std::string ret;
82 writeString<std::string,
83 std::string::size_type>(value, ret, &std::string::append, options);
84 return ret;
85}
86
87
88void toJSON(const std::string& value, std::ostream& out, int options)
89{
90 writeString<std::ostream, std::streamsize>(value, out, &std::ostream::write, options);
91}
92
93
94std::string toJSON(const std::string& value, int options)
95{
96 std::string ret;
97 writeString<std::string,
98 std::string::size_type>(value, ret, &std::string::append, options);
99 return ret;
100}
101
102
103} // namespace Poco
104