1 /* @(#)strndup.c	1.1 10/05/06 Copyright 2003-2010 J. Schilling */
2 #include <schily/mconfig.h>
3 #ifndef lint
4 static	UConst char sccsid[] =
5 	"@(#)strndup.c	1.1 10/05/06 Copyright 2003-2010 J. Schilling";
6 #endif
7 /*
8  *	strndup() to be used if missing in libc
9  *
10  *	Copyright (c) 2003-2010 J. Schilling
11  */
12 /*
13  * The contents of this file are subject to the terms of the
14  * Common Development and Distribution License, Version 1.0 only
15  * (the "License").  You may not use this file except in compliance
16  * with the License.
17  *
18  * See the file CDDL.Schily.txt in this distribution for details.
19  * A copy of the CDDL is also available via the Internet at
20  * http://www.opensource.org/licenses/cddl1.txt
21  *
22  * When distributing Covered Code, include this CDDL HEADER in each
23  * file and include the License file CDDL.Schily.txt from this distribution.
24  */
25 
26 #include <schily/standard.h>
27 #include <schily/stdlib.h>
28 #include <schily/string.h>
29 #include <schily/unistd.h>
30 #include <schily/schily.h>
31 #include <schily/libport.h>
32 
33 #ifndef	HAVE_STRNDUP
34 
35 EXPORT char *
strndup(s,len)36 strndup(s, len)
37 	const char	*s;
38 	size_t		len;
39 {
40 	size_t	i	= strnlen(s, len) + 1;
41 	char	 *res	= malloc(i);
42 
43 	if (res == NULL)
44 		return (NULL);
45 	if (i > 16) {
46 		movebytes(s, res, --i);
47 		res[i] = '\0';
48 	} else {
49 		char	*s2 = res;
50 
51 		while (--i > 0 && (*s2++ = *s++) != '\0')
52 			;
53 		if (i == 0)
54 			*s2 = '\0';
55 	}
56 	return (res);
57 }
58 #endif	/* HAVE_STRDUP */
59