]> granicus.if.org Git - git/commitdiff
git-compat-util: add xstrdup_or_null helper
authorJeff King <peff@peff.net>
Tue, 13 Jan 2015 01:57:37 +0000 (20:57 -0500)
committerJunio C Hamano <gitster@pobox.com>
Tue, 13 Jan 2015 18:03:30 +0000 (10:03 -0800)
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 <peff@peff.net>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
git-compat-util.h

index 44890d5b18f1f37308bdf77c80ee66bb65afc913..98cb78edf7b982e6083a5c72030e6dea0381deb5 100644 (file)
@@ -629,6 +629,11 @@ extern char *xgetcwd(void);
 
 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), (alloc) * sizeof(*(x)))
 
+static inline char *xstrdup_or_null(const char *str)
+{
+       return str ? xstrdup(str) : NULL;
+}
+
 static inline size_t xsize_t(off_t len)
 {
        if (len > (size_t) len)