Moved escapeJsonString to stringTools

This commit is contained in:
Daniel Wolf 2017-09-10 22:17:14 +02:00
parent d705a0c0ee
commit 24e8da4474
3 changed files with 34 additions and 31 deletions

View File

@ -1,39 +1,9 @@
#include "JsonExporter.h"
#include "exporterTools.h"
#include <utf8.h>
#include "stringTools.h"
using std::string;
string escapeJsonString(const string& s) {
// JavaScript uses UTF-16 internally. As a result, character escaping in JSON strings is UTF-16-based.
// Convert string to UTF-16
std::u16string utf16String;
utf8::utf8to16(s.begin(), s.end(), std::back_inserter(utf16String));
string result;
for (char16_t c : utf16String) {
switch (c) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\b': result += "\\b"; break;
case '\f': result += "\\f"; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default:
{
bool needsEscaping = c < '\x20' || c >= 0x80;
if (needsEscaping) {
result += fmt::format("\\u{0:04x}", c);
} else {
result += static_cast<char>(c);
}
}
}
}
return result;
}
void JsonExporter::exportAnimation(const ExporterInput& input, std::ostream& outputStream) {
// Export as JSON.
// I'm not using a library because the code is short enough without one and it lets me control the formatting.

View File

@ -3,6 +3,7 @@
#include <utf8.h>
#include <utf8proc.h>
#include <regex>
#include <format.h>
using std::string;
using std::wstring;
@ -157,3 +158,33 @@ string normalizeUnicode(const string s, NormalizationOptions options) {
free(result);
return resultString;
}
string escapeJsonString(const string& s) {
// JavaScript uses UTF-16 internally. As a result, character escaping in JSON strings is UTF-16-based.
// Convert string to UTF-16
std::u16string utf16String;
utf8::utf8to16(s.begin(), s.end(), std::back_inserter(utf16String));
string result;
for (char16_t c : utf16String) {
switch (c) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\b': result += "\\b"; break;
case '\f': result += "\\f"; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default:
{
bool needsEscaping = c < '\x20' || c >= 0x80;
if (needsEscaping) {
result += fmt::format("\\u{0:04x}", c);
} else {
result += static_cast<char>(c);
}
}
}
}
return result;
}

View File

@ -48,3 +48,5 @@ std::string join(T range, const std::string separator) {
}
return result;
}
std::string escapeJsonString(const std::string& s);