1
0
Fork 0
mirror of https://github.com/git/git.git synced 2024-05-26 05:56:11 +02:00

add strip_suffix function

Many callers of ends_with want to not only find out whether
a string has a suffix, but want to also strip it off. Doing
that separately has two minor problems:

  1. We often run over the string twice (once to find
     the suffix, and then once more to find its length to
     subtract the suffix length).

  2. We have to specify the suffix length again, which means
     either a magic number, or repeating ourselves with
     strlen("suffix").

Just as we have skip_prefix to avoid these cases with
starts_with, we can add a strip_suffix to avoid them with
ends_with.

Note that we add two forms of strip_suffix here: one that
takes a string, with the resulting length as an
out-parameter; and one that takes a pointer/length pair, and
reuses the length as an out-parameter. The latter is more
efficient when the caller already has the length (e.g., when
using strbufs), but it can be easy to confuse the two, as
they take the same number and types of parameters.

For that reason, the "mem" form puts its length parameter
next to the buffer (since they are a pair), and the string
form puts it at the end (since it is an out-parameter). The
compiler can notice when you get the order wrong, which
should help prevent writing one when you meant the other.

Signed-off-by: Jeff King <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Jeff King 2014-06-30 12:57:51 -04:00 committed by Junio C Hamano
parent 880fb8de67
commit 35480f0b23

View File

@ -350,6 +350,33 @@ static inline const char *skip_prefix(const char *str, const char *prefix)
return NULL;
}
/*
* If buf ends with suffix, return 1 and subtract the length of the suffix
* from *len. Otherwise, return 0 and leave *len untouched.
*/
static inline int strip_suffix_mem(const char *buf, size_t *len,
const char *suffix)
{
size_t suflen = strlen(suffix);
if (*len < suflen || memcmp(buf + (*len - suflen), suffix, suflen))
return 0;
*len -= suflen;
return 1;
}
/*
* If str ends with suffix, return 1 and set *len to the size of the string
* without the suffix. Otherwise, return 0 and set *len to the size of the
* string.
*
* Note that we do _not_ NUL-terminate str to the new length.
*/
static inline int strip_suffix(const char *str, const char *suffix, size_t *len)
{
*len = strlen(str);
return strip_suffix_mem(str, len, suffix);
}
#if defined(NO_MMAP) || defined(USE_WIN32_MMAP)
#ifndef PROT_READ