#ifndef __INCLUDED_CONFGET_PCRE2_H
#define __INCLUDED_CONFGET_PCRE2_H

/*-
 * SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
 * SPDX-License-Identifier: BSD-2-Clause
 */

#define PCRE2_CODE_UNIT_WIDTH	8

#include <pcre2.h>

#define var_pcre	pcre2_code

static void _do_pcre2_compile(PCRE2_SPTR const pattern, const pcre2_code ** const pvar,
		const char * const name, const bool is_utf8)
{
	int err;
	PCRE2_SIZE ofs;
	static PCRE2_UCHAR err_str[256];

	pcre2_code * const res = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED,
	    is_utf8 ? PCRE2_UTF : 0, &err, &ofs, NULL);
	if (res == NULL) {
		pcre2_get_error_message(err, err_str, sizeof(err_str));
		errx(1, "Invalid match %s: %s", name, err_str);
	}
	*pvar = res;
}

static bool _do_pcre2_match(const pcre2_code * const var, const char * const value,
		const char * const pattern)
{
	static pcre2_match_data *data;
	static PCRE2_UCHAR err_str[256];

	if (data == NULL)
		data = pcre2_match_data_create(1, NULL);

	int r = pcre2_match(var, (PCRE2_SPTR)value, strlen(value), 0, 0, data, 0);
	if (r == 0) {
		/* Allocate a larger ovector. */
		pcre2_match_data_free(data);
		data = pcre2_match_data_create_from_pattern(var, NULL);
		r = pcre2_match(var, (PCRE2_SPTR)value, strlen(value), 0, 0, data, 0);
		/* Let us hope r != 0 now. */
	}

	if (r > 0)
		return true;
	if (r == PCRE2_ERROR_NOMATCH)
		return false;

	pcre2_get_error_message(r, err_str, sizeof(err_str));
	errx(1, "Could not match '%s' against the '%s' pattern: %s", value, pattern, err_str);
}

#define do_pcre_compile(pattern, pvar, pvar_extra, name, is_utf8)	\
	_do_pcre2_compile((PCRE2_SPTR)(pattern), (pvar), (name), (is_utf8))

#define do_pcre_match(var, var_extra, value, pattern)	\
	_do_pcre2_match((var), (value), (pattern))

#define CONFGET_REGEX_IMPL_PCRE2_(major, minor) #major "." #minor
#define CONFGET_REGEX_IMPL_PCRE2(major, minor) CONFGET_REGEX_IMPL_PCRE2_(major, minor)

#endif
