]> asedeno.scripts.mit.edu Git - git.git/commitdiff
Make xstrndup common
authorDaniel Barkalow <barkalow@iabervon.org>
Thu, 3 May 2007 02:49:41 +0000 (22:49 -0400)
committerJunio C Hamano <junkio@cox.net>
Fri, 4 May 2007 05:28:55 +0000 (22:28 -0700)
This also improves the implementation to match how strndup is
specified (by GNU): if the length given is longer than the string,
only the string's length is allocated and copied, but the string need
not be null-terminated if it is at least as long as the given length.

Signed-off-by: Daniel Barkalow <barkalow@iabervon.org>
Signed-off-by: Junio C Hamano <junkio@cox.net>
commit.c
git-compat-util.h

index 754d1b8a0b8282fd3d1d6bd8f6ccb21b407504a5..eb911f44d7b0d78d884e901430cc34a300f7af21 100644 (file)
--- a/commit.c
+++ b/commit.c
@@ -720,14 +720,6 @@ static char *logmsg_reencode(const struct commit *commit,
        return out;
 }
 
-static char *xstrndup(const char *text, int len)
-{
-       char *result = xmalloc(len + 1);
-       memcpy(result, text, len);
-       result[len] = '\0';
-       return result;
-}
-
 static void fill_person(struct interp *table, const char *msg, int len)
 {
        int start, end, tz = 0;
index e3cf3703bbb896067f4c2d5b5e1f3ce898d8b6fc..bd93b6257885d56fda7268ae88ea82f721a6707f 100644 (file)
@@ -189,6 +189,19 @@ static inline void *xmalloc(size_t size)
        return ret;
 }
 
+static inline char *xstrndup(const char *str, size_t len)
+{
+       char *p;
+
+       p = memchr(str, '\0', len);
+       if (p)
+               len = p - str;
+       p = xmalloc(len + 1);
+       memcpy(p, str, len);
+       p[len] = '\0';
+       return p;
+}
+
 static inline void *xrealloc(void *ptr, size_t size)
 {
        void *ret = realloc(ptr, size);