1 #include "iwre.h"
2 #include "cregex.h"
3
4 #include <stdlib.h>
5 #include <string.h>
6 #include <errno.h>
7
8 struct iwre {
9 const char *pattern;
10 cregex_program_t *program;
11 };
12
iwre_pattern_get(struct iwre * re)13 const char* iwre_pattern_get(struct iwre *re) {
14 return re->pattern;
15 }
16
iwre_match(struct iwre * re,const char * text,const char * mpairs[],size_t mpairs_len)17 int iwre_match(struct iwre *re, const char *text, const char *mpairs[], size_t mpairs_len) {
18 if (mpairs_len % 2 != 0) {
19 errno = EINVAL;
20 return -1;
21 }
22 memset(mpairs, 0, sizeof(mpairs[0]) * mpairs_len);
23 int ret = cregex_program_run(re->program, text, mpairs, mpairs_len);
24 if (ret < 1) {
25 return 0;
26 }
27 ret = 0;
28 for (int i = 0; i < mpairs_len && mpairs[i]; ++i) {
29 ++ret;
30 }
31 return ret / 2;
32 }
33
iwre_destroy(struct iwre * re)34 void iwre_destroy(struct iwre *re) {
35 if (re) {
36 cregex_compile_free(re->program);
37 free(re);
38 }
39 }
40
iwre_create(const char * pattern)41 struct iwre* iwre_create(const char *pattern) {
42 struct iwre *re = calloc(1, sizeof(*re));
43 if (!re) {
44 return 0;
45 }
46 cregex_node_t *node = cregex_parse(pattern);
47 if (!node) {
48 goto error;
49 }
50 re->pattern = pattern;
51 re->program = cregex_compile_node(node);
52 if (!re->program) {
53 goto error;
54 }
55 cregex_parse_free(node);
56 return re;
57
58 error:
59 if (node) {
60 cregex_parse_free(node);
61 }
62 iwre_destroy(re);
63 return 0;
64 }
65