static void SanitizeFormat()

in sql_utils/public/functions/date_time_util.cc [1976:2044]


static void SanitizeFormat(absl::string_view format_string,
                           const char* elements_to_escape, std::string* out) {
  const char* cur = format_string.data();
  const char* pending = cur;
  const char* end = cur + format_string.size();

  while (cur != end) {
    // Moves cur to the next percent sign.
    while (cur != end && *cur != '%') ++cur;

    // Span the sequential percent signs.
    const char* percent = cur;
    while (cur != end && *cur == '%') ++cur;

    if (cur != pending) {
      out->append(pending, cur - pending);
      pending = cur;
    }

    // Loop unless we have an unescaped percent.
    if (cur == end || (cur - percent) % 2 == 0) {
      continue;
    }

    // Escape width modifier.
    while (cur != end && absl::ascii_isdigit(*cur)) ++cur;

    // Checks if the format should be escaped
    if (cur != end && strchr(elements_to_escape, *cur)) {
      out->push_back('%');  // Escape
      out->append(pending, ++cur - pending);
      pending = cur;
      continue;
    }

    if (cur != end) {
      if ((*cur != 'E' && *cur != 'O') || ++cur == end) {
        out->push_back(*pending++);
        continue;
      }
      if (*pending == 'E') {
        // Check %E extensions.
        if (strchr(elements_to_escape, *cur) ||
            // If %S (second) should be escaped, then %E#S and %E*S should also
            // be escaped.
            (strchr(elements_to_escape, 'S') &&
             ((*cur == '*' || absl::ascii_isdigit(*cur)) && ++cur != end &&
              *cur == 'S')) ||
            // If %Y (year) should be escaped, then %E4Y should also be escaped.
            (strchr(elements_to_escape, 'Y') && *cur == '4' && ++cur != end &&
             *cur == 'Y')) {
          cur++;
          out->push_back('%');  // Escape
        }
      } else if (*pending == 'O') {
        // Check %O extensions.
        if (strchr(elements_to_escape, *cur)) {
          cur++;
          out->push_back('%');  // Escape
        }
      }
    }

    if (cur != pending) {
      out->append(pending, cur - pending);
      pending = cur;
    }
  }
}