Skip to content

Commit 14570dc

Browse files
bk2204gitster
authored andcommitted
wrapper: add function to compare strings with different NUL termination
When parsing capabilities for the pack protocol, there are times we'll want to compare the value of a capability to a NUL-terminated string. Since the data we're reading will be space-terminated, not NUL-terminated, we need a function that compares the two strings, but also checks that they're the same length. Otherwise, if we used strncmp to compare these strings, we might accidentally accept a parameter that was a prefix of the expected value. Add a function, xstrncmpz, that takes a NUL-terminated string and a non-NUL-terminated string, plus a length, and compares them, ensuring that they are the same length. Signed-off-by: brian m. carlson <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 92315e5 commit 14570dc

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

git-compat-util.h

+6
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,12 @@ char *xgetcwd(void);
868868
FILE *fopen_for_writing(const char *path);
869869
FILE *fopen_or_warn(const char *path, const char *mode);
870870

871+
/*
872+
* Like strncmp, but only return zero if s is NUL-terminated and exactly len
873+
* characters long. If it is not, consider it greater than t.
874+
*/
875+
int xstrncmpz(const char *s, const char *t, size_t len);
876+
871877
/*
872878
* FREE_AND_NULL(ptr) is like free(ptr) followed by ptr = NULL. Note
873879
* that ptr is used twice, so don't pass e.g. ptr++.

wrapper.c

+8
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,14 @@ char *xstrndup(const char *str, size_t len)
105105
return xmemdupz(str, p ? p - str : len);
106106
}
107107

108+
int xstrncmpz(const char *s, const char *t, size_t len)
109+
{
110+
int res = strncmp(s, t, len);
111+
if (res)
112+
return res;
113+
return s[len] == '\0' ? 0 : 1;
114+
}
115+
108116
void *xrealloc(void *ptr, size_t size)
109117
{
110118
void *ret;

0 commit comments

Comments
 (0)