Skip to content

Commit 88de279

Browse files
committed
Factor out regcomp() usage into a wrapper.
Moves regular expression compilation out into a wrapper function that handles errors, so that we can add additional regular expression usage without exploding the code.
1 parent fe62a9b commit 88de279

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed

src/vcard.c

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,37 @@
4040
#include "mem.h"
4141
#include "vcard.h"
4242

43+
/**
44+
* Compile regex, checking and handling errors.
45+
*
46+
* \parm[in] preg The compiled regex.
47+
* \parm[in] regex The pattern to match.
48+
* \parm[in] cflags The compilation flags according to regex(3).
49+
*
50+
* \retval 0 If there were no errors.
51+
* \retval 1 If an error was encounted.
52+
**/
53+
static int
54+
xregcomp(regex_t *preg, const char *regex, int cflags) {
55+
int rerr = 0; /* Regex error code */
56+
size_t rlen = 0; /* Regex error string length */
57+
char *rstr = NULL; /* Regex error string */
58+
59+
rerr = regcomp(preg, regex, REG_EXTENDED | cflags);
60+
if (rerr != 0) {
61+
rlen = regerror(rerr, preg, NULL, 0);
62+
rstr = xmalloc((rlen+1)*sizeof(char));
63+
regerror(rerr, preg, rstr, rlen);
64+
warnx(_("Unable to compile regex '%s': %s\n"), regex, rstr);
65+
if (rstr) {
66+
free(rstr);
67+
rstr = NULL;
68+
}
69+
return 1;
70+
}
71+
return 0;
72+
}
73+
4374
/**
4475
* Search a query's result. This will run regexs over the result
4576
* to filter the data.
@@ -63,8 +94,6 @@ search(const char *card)
6394
int plen = 0; /* Length of snprintf()'s */
6495

6596
int rerr = 0; /* Regex error code */
66-
size_t rlen = 0; /* Regex error string length */
67-
char *rstr = NULL; /* Regex error string */
6897

6998
size_t qlen = 0; /* Length of the query string */
7099
char *q = NULL; /* Regex pattern for query */
@@ -96,15 +125,7 @@ search(const char *card)
96125
return(EXIT_FAILURE);
97126
}
98127

99-
if ((rerr = regcomp(&rq, q, REG_EXTENDED|REG_NEWLINE|REG_ICASE)) != 0) {
100-
rlen = regerror(rerr, &rq, NULL, 0);
101-
rstr = xmalloc((rlen+1)*sizeof(char));
102-
regerror(rerr, &rq, rstr, rlen);
103-
warnx(_("Unable to compile regex '%s': %s\n"), q, rstr);
104-
if (rstr) {
105-
free(rstr);
106-
rstr = NULL;
107-
}
128+
if (xregcomp(&rq, q, REG_NEWLINE|REG_ICASE) != 0) {
108129
return(EXIT_FAILURE);
109130
}
110131

@@ -119,15 +140,7 @@ search(const char *card)
119140
return(EXIT_FAILURE);
120141
}
121142

122-
if ((rerr = regcomp(&rs, s, REG_EXTENDED|REG_NEWLINE)) != 0) {
123-
rlen = regerror(rerr, &rs, NULL, 0);
124-
rstr = xmalloc((rlen+1)*sizeof(char));
125-
regerror(rerr, &rs, rstr, rlen);
126-
warnx(_("Unable to compile regex '%s': %s\n"), s, rstr);
127-
if (rstr) {
128-
free(rstr);
129-
rstr = NULL;
130-
}
143+
if (xregcomp(&rs, s, REG_NEWLINE) != 0) {
131144
return(EXIT_FAILURE);
132145
}
133146

0 commit comments

Comments
 (0)