xref: /titanic_41/usr/src/lib/libast/common/comp/re_comp.c (revision 989f28072d20c73ae0955d6a1e3e2fc74831cb39)
1 /***********************************************************************
2 *                                                                      *
3 *               This software is part of the ast package               *
4 *          Copyright (c) 1985-2010 AT&T Intellectual Property          *
5 *                      and is licensed under the                       *
6 *                  Common Public License, Version 1.0                  *
7 *                    by AT&T Intellectual Property                     *
8 *                                                                      *
9 *                A copy of the License is available at                 *
10 *            http://www.opensource.org/licenses/cpl1.0.txt             *
11 *         (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9)         *
12 *                                                                      *
13 *              Information and Software Systems Research               *
14 *                            AT&T Research                             *
15 *                           Florham Park NJ                            *
16 *                                                                      *
17 *                 Glenn Fowler <gsf@research.att.com>                  *
18 *                  David Korn <dgk@research.att.com>                   *
19 *                   Phong Vo <kpv@research.att.com>                    *
20 *                                                                      *
21 ***********************************************************************/
22 #pragma prototyped
23 /*
24  * re_comp implementation
25  */
26 
27 #include <ast.h>
28 #include <re_comp.h>
29 #include <regex.h>
30 
31 #undef	error
32 #undef	valid
33 
34 static struct
35 {
36 	char	error[64];
37 	regex_t	re;
38 	int	valid;
39 } state;
40 
41 char*
42 re_comp(const char* pattern)
43 {
44 	register int	r;
45 
46 	if (!pattern || !*pattern)
47 	{
48 		if (state.valid)
49 			return 0;
50 		r = REG_BADPAT;
51 	}
52 	else
53 	{
54 		if (state.valid)
55 		{
56 			state.valid = 0;
57 			regfree(&state.re);
58 		}
59 		if (!(r = regcomp(&state.re, pattern, REG_LENIENT|REG_NOSUB|REG_NULL)))
60 		{
61 			state.valid = 1;
62 			return 0;
63 		}
64 	}
65 	regerror(r, &state.re, state.error, sizeof(state.error));
66 	return state.error;
67 }
68 
69 int
70 re_exec(const char* subject)
71 {
72 	if (state.valid && subject)
73 		switch (regexec(&state.re, subject, 0, NiL, 0))
74 		{
75 		case 0:
76 			return 1;
77 		case REG_NOMATCH:
78 			return 0;
79 		}
80 	return -1;
81 }
82