From 7354ec8f2bd0e5b730170abd9eface9681720fd8 Mon Sep 17 00:00:00 2001 From: Vincent Bernat Date: Sun, 23 Jun 2013 09:25:02 +0200 Subject: [PATCH] compat: add `strndup()` compatibility function This function does not exist on OS X 10.6 for example. This was a long time GNU extension. --- configure.ac | 2 +- src/compat/compat.h | 4 ++++ src/compat/strndup.c | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/compat/strndup.c diff --git a/configure.ac b/configure.ac index ce765756..ac71aac2 100644 --- a/configure.ac +++ b/configure.ac @@ -96,7 +96,7 @@ AC_CONFIG_LIBOBJ_DIR([src/compat]) AC_FUNC_MALLOC AC_FUNC_REALLOC AC_SEARCH_LIBS([setproctitle], [util bsd]) -AC_REPLACE_FUNCS([strlcpy strnlen fgetln setproctitle]) +AC_REPLACE_FUNCS([strlcpy strnlen strndup fgetln setproctitle]) AC_CHECK_FUNCS([setresuid setresgid]) case " $LIBS " in diff --git a/src/compat/compat.h b/src/compat/compat.h index 8a72bf57..643a7828 100644 --- a/src/compat/compat.h +++ b/src/compat/compat.h @@ -49,6 +49,10 @@ size_t strlcpy(char *, const char *, size_t); size_t strnlen(const char *, size_t); #endif +#if !HAVE_STRNDUP +char *strndup(const char *, size_t); +#endif + #if !HAVE_FGETLN char *fgetln(FILE *, size_t *); #endif diff --git a/src/compat/strndup.c b/src/compat/strndup.c new file mode 100644 index 00000000..f0f1f3e8 --- /dev/null +++ b/src/compat/strndup.c @@ -0,0 +1,22 @@ +/* -*- mode: c; c-file-style: "openbsd" -*- */ + +#include +#include + +/* + * Similar to `strdup()` but copies at most n bytes. + */ +char* +strndup(const char *string, size_t maxlen) +{ + char *result; + /* We may use `strnlen()` but it may be unavailable. */ + const char *end = memchr(string, '\0', maxlen); + size_t len = end?(size_t)(end - string):maxlen; + + result = malloc(len + 1); + if (!result) return 0; + + memcpy(result, string, len); + return result; +} -- 2.39.5