static std::string CEscapeInternal()

in sql_utils/public/strings.cc [51:95]


static std::string CEscapeInternal(absl::string_view src, bool utf8_safe,
                                   char escape_quote_char) {
  std::string dest;
  bool last_hex_escape = false;  // true if last output char was \xNN.

  for (const char* p = src.begin(); p < src.end(); ++p) {
    unsigned char c = *p;
    bool is_hex_escape = false;
    switch (c) {
      case '\n': dest.append("\\" "n"); break;
      case '\r': dest.append("\\" "r"); break;
      case '\t': dest.append("\\" "t"); break;
      case '\\': dest.append("\\" "\\"); break;

      case '\'':
      case '\"':
      case '`':
        // Escape only quote chars that match escape_quote_char.
        if (escape_quote_char == 0 || c == escape_quote_char) {
          dest.push_back('\\');
        }
        dest.push_back(c);
        break;

      default:
        // Note that if we emit \xNN and the src character after that is a hex
        // digit then that digit must be escaped too to prevent it being
        // interpreted as part of the character code by C.
        if ((!utf8_safe || c < 0x80) &&
            (!absl::ascii_isprint(c) ||
             (last_hex_escape && absl::ascii_isxdigit(c)))) {
          dest.append("\\" "x");
          dest.push_back(hex_char[c / 16]);
          dest.push_back(hex_char[c % 16]);
          is_hex_escape = true;
        } else {
          dest.push_back(c);
          break;
        }
    }
    last_hex_escape = is_hex_escape;
  }

  return dest;
}