xref: /freebsd/sys/cddl/compat/opensolaris/kern/opensolaris_string.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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 
29 #define	IS_DIGIT(c)	((c) >= '0' && (c) <= '9')
30 
31 #define	IS_ALPHA(c)	\
32 	(((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
33 
34 char *
35 strchr(const char *s, int c)
36 {
37 	char ch;
38 
39 	ch = c;
40 	for (;; ++s) {
41 		if (*s == ch)
42 			return ((char *)s);
43 		if (*s == '\0')
44 			return (NULL);
45 	}
46 	/* NOTREACHED */
47 }
48 
49 char *
50 strrchr(const char *s, int c)
51 {
52 	char *save;
53 	char ch;
54 
55 	ch = c;
56 	for (save = NULL;; ++s) {
57 		if (*s == ch)
58 			save = (char *)s;
59 		if (*s == '\0')
60 			return (save);
61 	}
62 	/* NOTREACHED */
63 }
64 
65 char *
66 strpbrk(const char *s, const char *b)
67 {
68 	const char *p;
69 
70 	do {
71 		for (p = b; *p != '\0' && *p != *s; ++p)
72 			;
73 		if (*p != '\0')
74 			return ((char *)s);
75 	} while (*s++);
76 
77 	return (NULL);
78 }
79 
80 /*
81  * Convert a string into a valid C identifier by replacing invalid
82  * characters with '_'.  Also makes sure the string is nul-terminated
83  * and takes up at most n bytes.
84  */
85 void
86 strident_canon(char *s, size_t n)
87 {
88 	char c;
89 	char *end = s + n - 1;
90 
91 	if ((c = *s) == 0)
92 		return;
93 
94 	if (!IS_ALPHA(c) && c != '_')
95 		*s = '_';
96 
97 	while (s < end && ((c = *(++s)) != 0)) {
98 		if (!IS_ALPHA(c) && !IS_DIGIT(c) && c != '_')
99 			*s = '_';
100 	}
101 	*s = 0;
102 }
103