static std::string json_escape()

in src/runtime.cpp [459:503]


static std::string json_escape(std::string const& in)
{
    constexpr char last_non_printable_character = 31;
    std::string out;
    out.reserve(in.length()); // most strings will end up identical
    for (char ch : in) {
        if (ch > last_non_printable_character && ch != '\"' && ch != '\\') {
            out.append(1, ch);
        }
        else {
            out.append(1, '\\');
            switch (ch) {
                case '\\':
                    out.append(1, '\\');
                    break;
                case '"':
                    out.append(1, '"');
                    break;
                case '\b':
                    out.append(1, 'b');
                    break;
                case '\f':
                    out.append(1, 'f');
                    break;
                case '\n':
                    out.append(1, 'n');
                    break;
                case '\r':
                    out.append(1, 'r');
                    break;
                case '\t':
                    out.append(1, 't');
                    break;
                default:
                    // escape and print as unicode codepoint
                    constexpr int printed_unicode_length = 6; // 4 hex + letter 'u' + \0
                    std::array<char, printed_unicode_length> buf;
                    sprintf(buf.data(), "u%04x", ch);
                    out.append(buf.data(), buf.size() - 1); // add only five, discarding the null terminator.
                    break;
            }
        }
    }
    return out;
}