1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  *
21  * $FreeBSD$
22  */
23 /*
24  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/string.h>
30 #include <sys/kmem.h>
31 #include <machine/stdarg.h>
32 
33 #define	IS_DIGIT(c)	((c) >= '0' && (c) <= '9')
34 
35 #define	IS_ALPHA(c)	\
36 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
37 
38 char *
39 strpbrk(const char *s, const char *b)
40 {
41 	const char *p;
42 
43 	do {
44 		for (p = b; *p != '\0' && *p != *s; ++p)
45 			;
46 		if (*p != '\0')
47 			return ((char *)s);
48 	} while (*s++);
49 
50 	return (NULL);
51 }
52 
53 /*
54  * Convert a string into a valid C identifier by replacing invalid
55  * characters with '_'.  Also makes sure the string is nul-terminated
56  * and takes up at most n bytes.
57  */
58 void
59 strident_canon(char *s, size_t n)
60 {
61 	char c;
62 	char *end = s + n - 1;
63 
64 	if ((c = *s) == 0)
65 		return;
66 
67 	if (!IS_ALPHA(c) && c != '_')
68 		*s = '_';
69 
70 	while (s < end && ((c = *(++s)) != 0)) {
71 		if (!IS_ALPHA(c) && !IS_DIGIT(c) && c != '_')
72 			*s = '_';
73 	}
74 	*s = 0;
75 }
76 
77 /*
78  * Do not change the length of the returned string; it must be freed
79  * with strfree().
80  */
81 char *
82 kmem_asprintf(const char *fmt, ...)
83 {
84 	int size;
85 	va_list adx;
86 	char *buf;
87 
88 	va_start(adx, fmt);
89 	size = vsnprintf(NULL, 0, fmt, adx) + 1;
90 	va_end(adx);
91 
92 	buf = kmem_alloc(size, KM_SLEEP);
93 
94 	va_start(adx, fmt);
95 	(void) vsnprintf(buf, size, fmt, adx);
96 	va_end(adx);
97 
98 	return (buf);
99 }
100 
101 void
102 strfree(char *str)
103 {
104 	ASSERT(str != NULL);
105 	kmem_free(str, strlen(str) + 1);
106 }
107