]> git.ipfire.org Git - thirdparty/lldpd.git/commitdiff
compat: add `strndup()` compatibility function
authorVincent Bernat <bernat@luffy.cx>
Sun, 23 Jun 2013 07:25:02 +0000 (09:25 +0200)
committerVincent Bernat <bernat@luffy.cx>
Sun, 23 Jun 2013 07:42:14 +0000 (09:42 +0200)
This function does not exist on OS X 10.6 for example. This was a long
time GNU extension.

configure.ac
src/compat/compat.h
src/compat/strndup.c [new file with mode: 0644]

index ce765756564b88f3e4d63ea80c7d1b2a203d0c12..ac71aac23a93191e8b344089ed99719330b70469 100644 (file)
@@ -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
index 8a72bf57f39375103939d564b35bcb99a721126d..643a78281bb708fd8260041d8aa2fafb566c1113 100644 (file)
@@ -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 (file)
index 0000000..f0f1f3e
--- /dev/null
@@ -0,0 +1,22 @@
+/* -*- mode: c; c-file-style: "openbsd" -*- */
+
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * 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;
+}