Skip to content

Commit ae989a6

Browse files
peffgitster
authored andcommitted
add skip_prefix_mem helper
The skip_prefix function has been very useful for simplifying pointer arithmetic and avoiding repeated magic numbers, but we have no equivalent for length-limited buffers. So we're stuck with: if (3 <= len && skip_prefix(buf, "foo", &buf)) len -= 3; That's not that complicated, but it needs to use magic numbers for the length of the prefix (or else write out strlen("foo"), repeating the string). By using a helper, we can get the string length behind the scenes (and often at compile time for string literals). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent adb3356 commit ae989a6

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

git-compat-util.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,23 @@ static inline int skip_prefix(const char *str, const char *prefix,
463463
return 0;
464464
}
465465

466+
/*
467+
* Like skip_prefix, but promises never to read past "len" bytes of the input
468+
* buffer, and returns the remaining number of bytes in "out" via "outlen".
469+
*/
470+
static inline int skip_prefix_mem(const char *buf, size_t len,
471+
const char *prefix,
472+
const char **out, size_t *outlen)
473+
{
474+
size_t prefix_len = strlen(prefix);
475+
if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) {
476+
*out = buf + prefix_len;
477+
*outlen = len - prefix_len;
478+
return 1;
479+
}
480+
return 0;
481+
}
482+
466483
/*
467484
* If buf ends with suffix, return 1 and subtract the length of the suffix
468485
* from *len. Otherwise, return 0 and leave *len untouched.

0 commit comments

Comments
 (0)