2 * This file is part of DisOrder
3 * Copyright (C) 2017 Mark Wooding
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/regexp.c
19 * @brief Regular expressions
28 static pcre2_general_context
*genctx
= 0;
29 static pcre2_compile_context
*compctx
= 0;
31 static void *rxalloc(size_t sz
, void attribute((unused
)) *q
)
32 { return xmalloc(sz
); }
33 static void rxfree(void *p
, void attribute((unused
)) *q
)
36 void regexp_setup(void)
39 pcre2_compile_context_free(compctx
);
40 pcre2_general_context_free(genctx
);
42 genctx
= pcre2_general_context_create(rxalloc
, rxfree
, 0);
43 compctx
= pcre2_compile_context_create(genctx
);
46 regexp
*regexp_compile(const char *pat
, unsigned f
,
47 char *errbuf
, size_t errlen
, size_t *erroff_out
)
53 re
= pcre2_compile((PCRE2_SPTR
)pat
, strlen(pat
), f
,
54 &errcode
, &erroff
, compctx
);
57 pcre2_get_error_message(errcode
, (PCRE2_UCHAR
*)errbuf
, errlen
);
62 int regexp_match(const regexp
*re
, const char *s
, size_t n
, unsigned f
,
63 size_t *ov
, size_t on
)
70 m
= pcre2_match_data_create(on
, genctx
);
71 rc
= pcre2_match(re
, (PCRE2_SPTR
)s
, n
, 0, f
, m
, 0);
72 ovp
= pcre2_get_ovector_pointer(m
);
73 for(i
= 0; i
< on
; i
++) ov
[i
] = ovp
[i
];
74 pcre2_match_data_free(m
);
78 void regexp_free(regexp
*re
)
79 { pcre2_code_free(re
); }
83 void regexp_setup(void)
85 pcre_malloc
= xmalloc
;
89 regexp
*regexp_compile(const char *pat
, unsigned f
,
90 char *errbuf
, size_t errlen
, size_t *erroff_out
)
98 re
= pcre_compile(pat
, f
, &e
, &erroff
, 0);
100 *erroff_out
= erroff
;
101 for(p
= errbuf
, i
= errlen
- 1; i
&& *e
; i
--) *p
++ = *e
++;
107 int regexp_match(const regexp
*re
, const char *s
, size_t n
, unsigned f
,
108 size_t *ov
, size_t on
)
114 myov
= xmalloc(on
*sizeof(*myov
));
115 rc
= pcre_exec(re
, 0, s
, n
, 0, f
, myov
, on
);
116 for(i
= 0; i
< on
; i
++) ov
[i
] = myov
[i
];
121 void regexp_free(regexp
*re
)