Make xstrndup common
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>
Daniel Barkalow committed
May 2, 2007 at 22:49 UTC
5094102e13640d7559a02fd7c77b44dc9254cbbb
2 files changed
+13
-8
commit.c
-8
@@ -720,14 +720,6 @@ static char *logmsg_reencode(const struct commit *commit,
720
return out;
721
}
722
723
-static char *xstrndup(const char *text, int len)
724
-{
725
- char *result = xmalloc(len + 1);
726
- memcpy(result, text, len);
727
- result[len] = '\0';
728
- return result;
729
-}
730
-
723
static void fill_person(struct interp *table, const char *msg, int len)
724
{
725
int start, end, tz = 0;
git-compat-util.h
+13
@@ -189,6 +189,19 @@ static inline void *xmalloc(size_t size)
189
return ret;
190
}
191
192
+static inline char *xstrndup(const char *str, size_t len)
193
+{
194
+ char *p;
195
+
196
+ p = memchr(str, '\0', len);
197
+ if (p)
198
+ len = p - str;
199
+ p = xmalloc(len + 1);
200
+ memcpy(p, str, len);
201
+ p[len] = '\0';
202
+ return p;
203
+}
204
+
205
static inline void *xrealloc(void *ptr, size_t size)
206
{
207
void *ret = realloc(ptr, size);