From ae989a61dad98debe9899823ca987305f8e8020d Mon Sep 17 00:00:00 2001 From: Jeff King Date: Thu, 23 Jun 2016 13:33:57 -0400 Subject: 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 Signed-off-by: Junio C Hamano --- git-compat-util.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'git-compat-util.h') diff --git a/git-compat-util.h b/git-compat-util.h index 061e33c774..8e808c01d2 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -463,6 +463,23 @@ static inline int skip_prefix(const char *str, const char *prefix, return 0; } +/* + * Like skip_prefix, but promises never to read past "len" bytes of the input + * buffer, and returns the remaining number of bytes in "out" via "outlen". + */ +static inline int skip_prefix_mem(const char *buf, size_t len, + const char *prefix, + const char **out, size_t *outlen) +{ + size_t prefix_len = strlen(prefix); + if (prefix_len <= len && !memcmp(buf, prefix, prefix_len)) { + *out = buf + prefix_len; + *outlen = len - prefix_len; + return 1; + } + return 0; +} + /* * If buf ends with suffix, return 1 and subtract the length of the suffix * from *len. Otherwise, return 0 and leave *len untouched. -- cgit v1.2.3