changeset 77:e48757f916ae

Add port of strndup
author David Demelier <markand@malikania.fr>
date Mon, 14 Nov 2011 18:52:06 +0100
parents 4c5f69f5f409
children ad60e5ebd92c
files port/strndup.c
diffstat 1 files changed, 36 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/port/strndup.c	Mon Nov 14 18:52:06 2011 +0100
@@ -0,0 +1,36 @@
+/*
+ * strndup.c -- duplicate a string
+ *
+ * Copyright (c) 2011, David Demelier <markand@malikania.fr>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+char *
+strndup(const char *src, size_t len)
+{
+	size_t tocopy;
+	char *dst;
+
+	for (tocopy = 0; tocopy < len && src[tocopy] != '\0'; ++tocopy)
+		continue;
+
+	if ((dst = calloc(tocopy + 1, 1)) != NULL)
+		strncpy(dst, src, tocopy);
+
+	return dst;
+}