static int num_newlines_before_trailers()

in src/git_cache.h [1113:1183]


static int num_newlines_before_trailers(const std::string &message) {
  // Check for an empty message.
  if (message.empty())
    return 0;

  // Check if the subject ends.
  const char *first = message.c_str();
  const char *last = first + message.size();
  assert(*last == 0);
  if (*--last != '\n')
    return 2;

  // Pattern match for a suffix of trailers.
  bool newline = true;
  bool space = false;
  bool colon = false;
  bool in_trailer = false;
  while (first != last) {
    int ch = *--last;
    if (ch == '\n') {
      if (newline)
        return 0;
      if (!in_trailer)
        return 1;
      newline = true;
      in_trailer = false;
      continue;
    }
    newline = false;

    if (ch == ' ') {
      // Line matches "* *\n";
      space = true;
      colon = false;
      in_trailer = false;
      continue;
    }
    if (ch == ':') {
      // Line matches "*: *\n";
      if (colon) {
        colon = false;
        continue;
      }
      if (space)
        colon = true;
      space = false;
      in_trailer = false;
      continue;
    }

    space = false;
    if (!in_trailer && !colon)
      continue;
    colon = false;

    // Line matches "*: *\n".
    in_trailer = true;
    if (ch >= 'a' && ch <= 'z')
      continue;
    if (ch >= 'Z' && ch <= 'Z')
      continue;
    if (ch >= '0' && ch <= '9')
      continue;
    if (ch == '_' || ch == '-' || ch == '+')
      continue;
    in_trailer = false;
  }

  // The subject is never a trailer.
  return 1;
}