patch-id: use starts_with() and skip_prefix()

Get rid of magic numbers and avoid running over the end of a NUL terminated string by using starts_with() and skip_prefix() instead of memcmp(). Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

René Scharfe committed May 28, 2016 at 18:20 UTC 2bb73ae8037ae6fd82f002257d04f8cda2a721cd
1 file changed +10 -13
builtin/patch-id.c
+10 -13
@@ -81,16 +81,13 @@ static int get_one_patchid(unsigned char *next_sha1, unsigned char *result,
81
82 while (strbuf_getwholeline(line_buf, stdin, '\n') != EOF) {
83 char *line = line_buf->buf;
84 - char *p = line;
84 + const char *p = line;
85 int len;
86
87 - if (!memcmp(line, "diff-tree ", 10))
88 - p += 10;
89 - else if (!memcmp(line, "commit ", 7))
90 - p += 7;
91 - else if (!memcmp(line, "From ", 5))
92 - p += 5;
93 - else if (!memcmp(line, "\\ ", 2) && 12 < strlen(line))
87 + if (!skip_prefix(line, "diff-tree ", &p) &&
88 + !skip_prefix(line, "commit ", &p) &&
89 + !skip_prefix(line, "From ", &p) &&
90 + starts_with(line, "\\ ") && 12 < strlen(line))
91 continue;
92
93 if (!get_sha1_hex(p, next_sha1)) {
@@ -99,14 +96,14 @@ static int get_one_patchid(unsigned char *next_sha1, unsigned char *result,
96 }
97
98 /* Ignore commit comments */
102 - if (!patchlen && memcmp(line, "diff ", 5))
99 + if (!patchlen && !starts_with(line, "diff "))
100 continue;
101
102 /* Parsing diff header? */
103 if (before == -1) {
107 - if (!memcmp(line, "index ", 6))
104 + if (starts_with(line, "index "))
105 continue;
109 - else if (!memcmp(line, "--- ", 4))
106 + else if (starts_with(line, "--- "))
107 before = after = 1;
108 else if (!isalpha(line[0]))
109 break;
@@ -114,14 +111,14 @@ static int get_one_patchid(unsigned char *next_sha1, unsigned char *result,
111
112 /* Looking for a valid hunk header? */
113 if (before == 0 && after == 0) {
117 - if (!memcmp(line, "@@ -", 4)) {
114 + if (starts_with(line, "@@ -")) {
115 /* Parse next hunk, but ignore line numbers. */
116 scan_hunk_header(line, &before, &after);
117 continue;
118 }
119
120 /* Split at the end of the patch. */
124 - if (memcmp(line, "diff ", 5))
121 + if (!starts_with(line, "diff "))
122 break;
123
124 /* Else we're parsing another header. */