[pacman-dev] [PATCH 1/3] Add strndup fallback function to libalpm util

Dan McGee dan at archlinux.org
Thu Jan 20 16:03:07 EST 2011


The same fallback we are currently using in the pacman frontend.

Signed-off-by: Dan McGee <dan at archlinux.org>
---
 lib/libalpm/util.c |   22 ++++++++++++++++++++++
 lib/libalpm/util.h |    5 +++++
 2 files changed, 27 insertions(+), 0 deletions(-)

diff --git a/lib/libalpm/util.c b/lib/libalpm/util.c
index 2eee5e4..81d950e 100644
--- a/lib/libalpm/util.c
+++ b/lib/libalpm/util.c
@@ -937,4 +937,26 @@ long _alpm_parsedate(const char *line)
 	return(atol(line));
 }
 
+#ifndef HAVE_STRNDUP
+/* A quick and dirty implementation derived from glibc */
+static size_t strnlen(const char *s, size_t max)
+{
+    register const char *p;
+    for(p = s; *p && max--; ++p);
+    return(p - s);
+}
+
+char *strndup(const char *s, size_t n)
+{
+  size_t len = strnlen(s, n);
+  char *new = (char *) malloc(len + 1);
+
+  if (new == NULL)
+    return NULL;
+
+  new[len] = '\0';
+  return (char *) memcpy(new, s, len);
+}
+#endif
+
 /* vim: set ts=2 sw=2 noet: */
diff --git a/lib/libalpm/util.h b/lib/libalpm/util.h
index be5c1d9..015e9bf 100644
--- a/lib/libalpm/util.h
+++ b/lib/libalpm/util.h
@@ -50,6 +50,7 @@
 #define CALLOC(p, l, s, action) do { p = calloc(l, s); if(p == NULL) { ALLOC_FAIL(s); action; } } while(0)
 /* This strdup macro is NULL safe- copying NULL will yield NULL */
 #define STRDUP(r, s, action) do { if(s != NULL) { r = strdup(s); if(r == NULL) { ALLOC_FAIL(strlen(s)); action; } } else { r = NULL; } } while(0)
+#define STRNDUP(r, s, l, action) do { if(s != NULL) { r = strndup(s, l); if(r == NULL) { ALLOC_FAIL(strlen(s)); action; } } else { r = NULL; } } while(0)
 
 #define FREE(p) do { free(p); p = NULL; } while(0)
 
@@ -101,6 +102,10 @@ long _alpm_parsedate(const char *line);
 char *strsep(char **, const char *);
 #endif
 
+#ifndef HAVE_STRNDUP
+char *strndup(const char *s, size_t n);
+#endif
+
 /* check exported library symbols with: nm -C -D <lib> */
 #define SYMEXPORT __attribute__((visibility("default")))
 #define SYMHIDDEN __attribute__((visibility("internal")))
-- 
1.7.3.5



More information about the pacman-dev mailing list