1 /*-
2 * Copyright (c) 2007, 2011
3 * Thorsten Glaser <tg@mirbsd.org>
4 *
5 * Provided that these terms and disclaimer and all copyright notices
6 * are retained or reproduced in an accompanying document, permission
7 * is granted to deal in this work without restriction, including un-
8 * limited rights to use, publicly perform, distribute, sell, modify,
9 * merge, give away, or sublicence.
10 *
11 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
12 * the utmost extent permitted by applicable law, neither express nor
13 * implied; without malicious intent or gross negligence. In no event
14 * may a licensor, author or contributor be held liable for indirect,
15 * direct, other damage, loss, or other issues arising in any way out
16 * of dealing in the work, even if advised of the possibility of such
17 * damage or existence of a defect, except proven that it results out
18 * of said person's immediate fault when using the work as intended.
19 */
20
21 #include <sys/param.h>
22 #include <stdlib.h>
23 #ifdef WIDEC
24 #include <wchar.h>
25 #else
26 #include <string.h>
27 #endif
28
29 __RCSID("$MirOS: src/lib/libc/string/strndup.c,v 1.5 2011/07/01 19:17:26 tg Exp $");
30
31 #ifdef WIDEC
32 #define strndup wcsndup
33 #define strlen wcslen
34 #define char_t wchar_t
35 #define NUL L'\0'
36 #else
37 #define char_t char
38 #define NUL '\0'
39 #endif
40
41 char_t *
strndup(const char_t * s,size_t max)42 strndup(const char_t *s, size_t max)
43 {
44 register size_t n;
45 char_t *cp;
46
47 n = strlen(s);
48 n = MIN(n, max);
49 if ((cp = calloc(n + 1, sizeof(char_t))) != NULL) {
50 memcpy(cp, s, n * sizeof(char_t));
51 cp[n] = NUL;
52 }
53 return (cp);
54 }
55