wxWidgets/include/wx/private/json.h

88 lines
2.5 KiB
C
Raw Normal View History

///////////////////////////////////////////////////////////////////////////////
// Name: wx/private/json.h
// Purpose: Helper functions to handle JSON data
// Author: Tobias Taschner
// Created: 2020-01-17
// Copyright: (c) 2020 wxWidgets development team
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_PRIVATE_JSON_H_
#define _WX_PRIVATE_JSON_H_
namespace wxJSON
{
// Decode a string literal including escape sequences
2020-01-19 15:32:11 -05:00
// Returns false if the input string is not a valid JSON string
bool DecodeString(const wxString& in, wxString* out)
{
2020-01-19 15:32:11 -05:00
const wxWCharBuffer buf = in.wc_str();
const wchar_t* ch = buf.data();
// String has to chart with a quote
if (*(ch++) != '"')
return false;
out->reserve(buf.length());
const wchar_t* end = buf.data() + buf.length() - 1;
2020-01-19 15:32:11 -05:00
for (; ch < end; ++ch)
{
if (*ch == '\\')
{
switch (*(++ch))
{
case 'b':
2020-01-19 15:32:11 -05:00
out->append('\b');
break;
case 'n':
2020-01-19 15:32:11 -05:00
out->append('\n');
break;
case 'r':
2020-01-19 15:32:11 -05:00
out->append('\r');
break;
case 't':
2020-01-19 15:32:11 -05:00
out->append('\t');
break;
2020-01-19 15:32:11 -05:00
case 'f':
out->append('\f');
break;
2020-01-19 15:32:11 -05:00
case '/':
out->append('/');
break;
case '"':
2020-01-19 15:32:11 -05:00
out->append('"');
break;
case '\\':
2020-01-19 15:32:11 -05:00
out->append('\\');
break;
case 'u':
2020-01-19 15:32:11 -05:00
#if SIZEOF_WCHAR_T == 2
// In this case, we handle surrogates without doing anything special was wchar_t strings use UTF-17 encoding.
if (wxIsxdigit(ch[1]) && wxIsxdigit(ch[2]) &&
wxIsxdigit(ch[3]) && wxIsxdigit(ch[4]))
{
2020-01-19 15:32:11 -05:00
wchar_t uchar = wxHexToDec(wxString(&ch[3], 2)) |
wxHexToDec(wxString(&ch[1], 2)) >> 8;
2020-01-19 15:32:11 -05:00
out->append(uchar);
ch += 4;
}
2020-01-19 15:32:11 -05:00
#else
#error Implement correct surrogate handling.
#endif
break;
default:
2020-01-19 15:32:11 -05:00
return false;
break;
}
}
else
2020-01-19 15:32:11 -05:00
out->append(*ch);
}
2020-01-19 15:32:11 -05:00
// String has to end with a quote
return (*ch) == '"';
}
} // namespace JSON
#endif // _WX_PRIVATE_JSON_H_