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 
19 namespace {
20 
21 
22 template<typename T, typename S>
23 struct WriteFunc
24 {
25 	typedef T& (T::*Type)(const char* s, S n);
26 };
27 
28 
29 
30 template<typename T, typename S>
writeString(const std::string & value,T & obj,typename WriteFunc<T,S>::Type write,int options)31 void 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 
67 namespace Poco {
68 
69 
toJSON(const std::string & value,std::ostream & out,bool wrap)70 void toJSON(const std::string& value, std::ostream& out, bool wrap)
71 {
72 	int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
73 	writeString<std::ostream, std::streamsize>(value, out, &std::ostream::write, options);
74 }
75 
76 
toJSON(const std::string & value,bool wrap)77 std::string toJSON(const std::string& value, bool wrap)
78 {
79 	int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
80 	std::string ret;
81 	writeString<std::string,
82 				std::string::size_type>(value, ret, &std::string::append, options);
83 	return ret;
84 }
85 
86 
toJSON(const std::string & value,std::ostream & out,int options)87 void toJSON(const std::string& value, std::ostream& out, int options)
88 {
89 	writeString<std::ostream, std::streamsize>(value, out, &std::ostream::write, options);
90 }
91 
92 
toJSON(const std::string & value,int options)93 std::string toJSON(const std::string& value, int options)
94 {
95 	std::string ret;
96 	writeString<std::string, std::string::size_type>(value, ret, &std::string::append, options);
97 	return ret;
98 }
99 
100 
101 } // namespace Poco
102