aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/poco/Foundation/src/JSONString.cpp
blob: 16049765d507f3daacb3641767474226e44eecc8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//
// String.h
//
// Library: Foundation
// Package: Core
// Module:  String
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#include "Poco/JSONString.h"
#include "Poco/UTF8String.h"
#include <ostream>


namespace {


template<typename T, typename S>
struct WriteFunc
{
	typedef T& (T::*Type)(const char* s, S n);
};



template<typename T, typename S>
void writeString(const std::string &value, T& obj, typename WriteFunc<T, S>::Type write, int options)
{
	bool wrap = ((options & Poco::JSON_WRAP_STRINGS) != 0);
	bool escapeAllUnicode = ((options & Poco::JSON_ESCAPE_UNICODE) != 0);

	if (value.size() == 0)
	{
		if(wrap) (obj.*write)("\"\"", 2);
		return;
	}

	if(wrap) (obj.*write)("\"", 1);
	if(escapeAllUnicode)
	{
		std::string str = Poco::UTF8::escape(value.begin(), value.end(), true);
		(obj.*write)(str.c_str(), str.size());
	}
	else
	{
		for(std::string::const_iterator it = value.begin(), end = value.end(); it != end; ++it)
		{
			// Forward slash isn't strictly required by JSON spec, but some parsers expect it
			if((*it >= 0 && *it <= 31) || (*it == '"') || (*it == '\\') || (*it == '/'))
			{
				std::string str = Poco::UTF8::escape(it, it + 1, true);
				(obj.*write)(str.c_str(), str.size());
			}else (obj.*write)(&(*it), 1);
		}
	}
	if(wrap) (obj.*write)("\"", 1);
};


}


namespace Poco {


void toJSON(const std::string& value, std::ostream& out, bool wrap)
{
	int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
	writeString<std::ostream, std::streamsize>(value, out, &std::ostream::write, options);
}


std::string toJSON(const std::string& value, bool wrap)
{
	int options = (wrap ? Poco::JSON_WRAP_STRINGS : 0);
	std::string ret;
	writeString<std::string,
				std::string::size_type>(value, ret, &std::string::append, options);
	return ret;
}


void toJSON(const std::string& value, std::ostream& out, int options)
{
	writeString<std::ostream, std::streamsize>(value, out, &std::ostream::write, options);
}


std::string toJSON(const std::string& value, int options)
{
	std::string ret;
	writeString<std::string, std::string::size_type>(value, ret, &std::string::append, options);
	return ret;
}


} // namespace Poco