/*-
 * Copyright (c) 2016 UPLEX Nils Goroll Systemoptimierung
 * All rights reserved
 *
 * Author: Geoffrey Simmons <geoffrey.simmons@uplex.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include "config.h"

#include <algorithm>

#include "vre2set.h"

#define CATCHALL                                \
        catch (const runtime_error& err) {      \
                return err.what();              \
        }                                       \
        catch (const exception& ex) {           \
                return ex.what();               \
        }                                       \
        catch (...) {                           \
                return "Unknown error";         \
        }

using namespace std;

vre2set::vre2set(RE2::Options * const opt, const RE2::Anchor anchor)
{
	set_ = new RE2::Set(*opt, anchor);
}

vre2set::~vre2set()
{
	if (set_) {
		delete set_;
		set_ = NULL;
	}
}

inline int
vre2set::add(const char* pattern, string* error) const
{
	return set_->Add(pattern, error);
}

inline bool
vre2set::compile() const
{
	return set_->Compile();
}

inline bool
vre2set::match(const char* subject, vector<int>* m, errorkind_e* err) const
{
#if HAVE_SET_MATCH_ERRORINFO
	bool ret;
	RE2::Set::ErrorInfo errinfo;

	ret = set_->Match(subject, m, &errinfo);
	*err = (errorkind_e) errinfo.kind;
	return ret;
#else
	*err = NOT_IMPLEMENTED;
	return set_->Match(subject, m);
#endif
}

inline bool
vre2set::matchonly(const char* subject, const unsigned len, errorkind_e* err)
	const
{
	StringPiece s(subject, static_cast<int>(len));

#if HAVE_SET_MATCH_ERRORINFO && HAVE_SET_MATCH_NULL_VECTOR
	bool ret;
	RE2::Set::ErrorInfo errinfo;

	ret = set_->Match(s, NULL, &errinfo);
	*err = (errorkind_e) errinfo.kind;
	return ret;
#elif HAVE_SET_MATCH_ERRORINFO
	bool ret;
	RE2::Set::ErrorInfo errinfo;
	vector<int> v;

	ret = set_->Match(s, &v, &errinfo);
	*err = (errorkind_e) errinfo.kind;
	return ret;
#elif HAVE_SET_MATCH_NULL_VECTOR
	(void)err;
	return set_->Match(s, NULL);
#else
	vector<int> v;
	(void)err;
	return set_->Match(s, &v);
#endif
}

const char *
vre2set_init(vre2set **setp, anchor_e anchor, unsigned utf8,
    unsigned posix_syntax, unsigned longest_match, long max_mem,
    unsigned literal, unsigned never_nl, unsigned dot_nl,
    unsigned case_sensitive, unsigned perl_classes, unsigned word_boundary,
    unsigned one_line)
{
	try {
		RE2::Options opt;
		RE2::Anchor re2_anchor;

		switch(anchor) {
		case NONE:
			re2_anchor = RE2::UNANCHORED;
			break;
		case START:
			re2_anchor = RE2::ANCHOR_START;
			break;
		case BOTH:
			re2_anchor = RE2::ANCHOR_BOTH;
			break;
		default:
			throw runtime_error("illegal anchor");
		}

		opt.set_log_errors(false);
		opt.set_never_capture(true);
		if (utf8)
			opt.set_encoding(RE2::Options::EncodingUTF8);
		else
			opt.set_encoding(RE2::Options::EncodingLatin1);
		opt.set_posix_syntax(posix_syntax);
		opt.set_longest_match(longest_match);
		opt.set_max_mem(max_mem);
		opt.set_literal(literal);
		opt.set_never_nl(never_nl);
		opt.set_dot_nl(dot_nl);
		opt.set_case_sensitive(case_sensitive);
		opt.set_perl_classes(perl_classes);
		opt.set_word_boundary(word_boundary);
		opt.set_one_line(one_line);

		*setp = new vre2set(&opt, re2_anchor);
		return NULL;
	}
	CATCHALL
}

const char *
vre2set_add(vre2set *set, const char * const pattern, int * const idx)
{
	try {
		string err;
		if ((*idx = set->add(pattern, &err)) < 0)
			throw runtime_error(err);
		return NULL;
	}
	CATCHALL
}

const char *
vre2set_compile(vre2set *set)
{
	try {
		if (!set->compile())
			throw runtime_error("compile failed");
		return NULL;
	}
	CATCHALL
}

const char *
vre2set_match(vre2set *set, const char * const subject, int * const match,
	    void *buf, const size_t buflen, size_t * const nmatches,
	    errorkind_e * const err)
{
	try {
		vector<int> m;

		*nmatches = 0;
		*match = set->match(subject, &m, err);
		if (*match) {
			if (m.size() * sizeof(int) > buflen)
				return "insufficient space to copy match data";
			*nmatches = m.size();
			std::sort(m.begin(), m.end());
			memcpy(buf, m.data(), *nmatches * sizeof(int));
		}
		return NULL;
	}
	CATCHALL
}

const char *
vre2set_matchonly(vre2set *set, const char * const subject, const unsigned len,
	    int * const match, errorkind_e * const err)
{
	try {
		*match = set->matchonly(subject, len, err);
		return NULL;
	}
	CATCHALL
}

const char *
vre2set_fini(vre2set **set)
{
	try {
		delete *set;
		return NULL;
	}
	CATCHALL
}
