diff mbox series

[U-Boot,v5,02/27] lib: Implement strndup()

Message ID 20190415093239.27509-3-thierry.reding@gmail.com
State Accepted
Delegated to: Tom Warren
Headers show
Series ARM: tegra: Miscalleneous improvements | expand

Commit Message

Thierry Reding April 15, 2019, 9:32 a.m. UTC
From: Thierry Reding <treding@nvidia.com>

Signed-off-by: Thierry Reding <treding@nvidia.com>
---
 include/linux/string.h |  1 +
 lib/string.c           | 23 +++++++++++++++++++++++
 2 files changed, 24 insertions(+)
diff mbox series

Patch

diff --git a/include/linux/string.h b/include/linux/string.h
index 36066207392e..5d63be4ce5b0 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -94,6 +94,7 @@  size_t strcspn(const char *s, const char *reject);
 #ifndef __HAVE_ARCH_STRDUP
 extern char * strdup(const char *);
 #endif
+extern char * strndup(const char *, size_t);
 #ifndef __HAVE_ARCH_STRSWAB
 extern char * strswab(const char *);
 #endif
diff --git a/lib/string.c b/lib/string.c
index af17c16f616d..9b779ddc3bbe 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -326,6 +326,29 @@  char * strdup(const char *s)
 }
 #endif
 
+char * strndup(const char *s, size_t n)
+{
+	size_t len;
+	char *new;
+
+	if (s == NULL)
+		return NULL;
+
+	len = strlen(s);
+
+	if (n < len)
+		len = n;
+
+	new = malloc(len + 1);
+	if (new == NULL)
+		return NULL;
+
+	strncpy(new, s, len);
+	new[len] = '\0';
+
+	return new;
+}
+
 #ifndef __HAVE_ARCH_STRSPN
 /**
  * strspn - Calculate the length of the initial substring of @s which only