xref: /freebsd/sys/cddl/compat/opensolaris/kern/opensolaris_string.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
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 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/param.h>
27 #include <sys/string.h>
28 #include <sys/kmem.h>
29 #include <machine/stdarg.h>
30 
31 #define	IS_DIGIT(c)	((c) >= '0' && (c) <= '9')
32 
33 #define	IS_ALPHA(c)	\
34 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
35 
36 char *
37 strpbrk(const char *s, const char *b)
38 {
39 	const char *p;
40 
41 	do {
42 		for (p = b; *p != '\0' && *p != *s; ++p)
43 			;
44 		if (*p != '\0')
45 			return ((char *)s);
46 	} while (*s++);
47 
48 	return (NULL);
49 }
50 
51 /*
52  * Convert a string into a valid C identifier by replacing invalid
53  * characters with '_'.  Also makes sure the string is nul-terminated
54  * and takes up at most n bytes.
55  */
56 void
57 strident_canon(char *s, size_t n)
58 {
59 	char c;
60 	char *end = s + n - 1;
61 
62 	if ((c = *s) == 0)
63 		return;
64 
65 	if (!IS_ALPHA(c) && c != '_')
66 		*s = '_';
67 
68 	while (s < end && ((c = *(++s)) != 0)) {
69 		if (!IS_ALPHA(c) && !IS_DIGIT(c) && c != '_')
70 			*s = '_';
71 	}
72 	*s = 0;
73 }
74 
75 /*
76  * Do not change the length of the returned string; it must be freed
77  * with strfree().
78  */
79 char *
80 kmem_asprintf(const char *fmt, ...)
81 {
82 	int size;
83 	va_list adx;
84 	char *buf;
85 
86 	va_start(adx, fmt);
87 	size = vsnprintf(NULL, 0, fmt, adx) + 1;
88 	va_end(adx);
89 
90 	buf = kmem_alloc(size, KM_SLEEP);
91 
92 	va_start(adx, fmt);
93 	(void) vsnprintf(buf, size, fmt, adx);
94 	va_end(adx);
95 
96 	return (buf);
97 }
98 
99 void
100 strfree(char *str)
101 {
102 	ASSERT(str != NULL);
103 	kmem_free(str, strlen(str) + 1);
104 }
105