MCPcopy Create free account
hub / github.com/TombEngine/TombEngine / EscapeString

Function EscapeString

Libs/flatbuffers/util.h:589–657  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

587#endif // !FLATBUFFERS_PREFER_PRINTF
588
589inline bool EscapeString(const char *s, size_t length, std::string *_text,
590 bool allow_non_utf8, bool natural_utf8) {
591 std::string &text = *_text;
592 text += "\"";
593 for (uoffset_t i = 0; i < length; i++) {
594 char c = s[i];
595 switch (c) {
596 case '\n': text += "\\n"; break;
597 case '\t': text += "\\t"; break;
598 case '\r': text += "\\r"; break;
599 case '\b': text += "\\b"; break;
600 case '\f': text += "\\f"; break;
601 case '\"': text += "\\\""; break;
602 case '\\': text += "\\\\"; break;
603 default:
604 if (c >= ' ' && c <= '~') {
605 text += c;
606 } else {
607 // Not printable ASCII data. Let's see if it's valid UTF-8 first:
608 const char *utf8 = s + i;
609 int ucc = FromUTF8(&utf8);
610 if (ucc < 0) {
611 if (allow_non_utf8) {
612 text += "\\x";
613 text += IntToStringHex(static_cast<uint8_t>(c), 2);
614 } else {
615 // There are two cases here:
616 //
617 // 1) We reached here by parsing an IDL file. In that case,
618 // we previously checked for non-UTF-8, so we shouldn't reach
619 // here.
620 //
621 // 2) We reached here by someone calling GenerateText()
622 // on a previously-serialized flatbuffer. The data might have
623 // non-UTF-8 Strings, or might be corrupt.
624 //
625 // In both cases, we have to give up and inform the caller
626 // they have no JSON.
627 return false;
628 }
629 } else {
630 if (natural_utf8) {
631 // utf8 points to past all utf-8 bytes parsed
632 text.append(s + i, static_cast<size_t>(utf8 - s - i));
633 } else if (ucc <= 0xFFFF) {
634 // Parses as Unicode within JSON's \uXXXX range, so use that.
635 text += "\\u";
636 text += IntToStringHex(ucc, 4);
637 } else if (ucc <= 0x10FFFF) {
638 // Encode Unicode SMP values to a surrogate pair using two \u
639 // escapes.
640 uint32_t base = ucc - 0x10000;
641 auto high_surrogate = (base >> 10) + 0xD800;
642 auto low_surrogate = (base & 0x03FF) + 0xDC00;
643 text += "\\u";
644 text += IntToStringHex(high_surrogate, 4);
645 text += "\\u";
646 text += IntToStringHex(low_surrogate, 4);

Callers 2

ToStringMethod · 0.85
StringMethod · 0.85

Calls 3

FromUTF8Function · 0.85
IntToStringHexFunction · 0.85
appendMethod · 0.45

Tested by

no test coverage detected