Skip to content

Commit d64ea0f

Browse files
peffgitster
authored andcommitted
git-compat-util: add xstrdup_or_null helper
It's a common idiom to duplicate a string if it is non-NULL, or pass a literal NULL through. This is already a one-liner in C, but you do have to repeat the name of the string twice. So if there's a function call, you must write: const char *x = some_fun(...); return x ? xstrdup(x) : NULL; instead of (with this patch) just: return xstrdup_or_null(some_fun(...)); Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 1da1e07 commit d64ea0f

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

git-compat-util.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,11 @@ extern char *xgetcwd(void);
629629

630630
#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), (alloc) * sizeof(*(x)))
631631

632+
static inline char *xstrdup_or_null(const char *str)
633+
{
634+
return str ? xstrdup(str) : NULL;
635+
}
636+
632637
static inline size_t xsize_t(off_t len)
633638
{
634639
if (len > (size_t) len)

0 commit comments

Comments
 (0)