[PATCH v3 2/4] xfuncs: import xstrndup() from busybox

Marc Kleine-Budde mkl at pengutronix.de
Wed Jun 17 13:47:01 PDT 2015


This function is needed for the fixed length string feature in the state
framework.

Signed-off-by: Marc Kleine-Budde <mkl at pengutronix.de>
---
 include/xfuncs.h |  1 +
 lib/xfuncs.c     | 22 ++++++++++++++++++++++
 2 files changed, 23 insertions(+)

diff --git a/include/xfuncs.h b/include/xfuncs.h
index 8efc99dbc455..940a1d67ed1c 100644
--- a/include/xfuncs.h
+++ b/include/xfuncs.h
@@ -7,6 +7,7 @@ void *xmalloc(size_t size);
 void *xrealloc(void *ptr, size_t size);
 void *xzalloc(size_t size);
 char *xstrdup(const char *s);
+char *xstrndup(const char *s, size_t size);
 void* xmemalign(size_t alignment, size_t bytes);
 void* xmemdup(const void *orig, size_t size);
 
diff --git a/lib/xfuncs.c b/lib/xfuncs.c
index 0e78b670a5d4..f0219c43a5ec 100644
--- a/lib/xfuncs.c
+++ b/lib/xfuncs.c
@@ -63,6 +63,28 @@ char *xstrdup(const char *s)
 }
 EXPORT_SYMBOL(xstrdup);
 
+char *xstrndup(const char *s, size_t n)
+{
+	int m;
+	char *t;
+
+	/* We can just xmalloc(n+1) and strncpy into it, */
+	/* but think about xstrndup("abc", 10000) wastage! */
+	m = n;
+	t = (char*) s;
+	while (m) {
+		if (!*t) break;
+		m--;
+		t++;
+	}
+	n -= m;
+	t = xmalloc(n + 1);
+	t[n] = '\0';
+
+	return memcpy(t, s, n);
+}
+EXPORT_SYMBOL(xstrndup);
+
 void* xmemalign(size_t alignment, size_t bytes)
 {
 	void *p = memalign(alignment, bytes);
-- 
2.1.4




More information about the barebox mailing list