#include "hwlm_literal.h"
#include "util/bitutils.h"
#include "util/compare.h"
#include "util/ue2string.h"
#include <algorithm>
#include <iomanip>
#include <sstream>
using namespace std;
namespace ue2 {
#ifdef DEBUG
static UNUSED
std::string dumpMask(const vector<u8> &v) {
ostringstream oss;
vector<u8>::const_iterator it, ite;
for (it = v.begin(), ite = v.end(); it != ite; ++it) {
oss << setfill('0') << setw(2) << hex << (unsigned int)*it;
}
return oss.str();
}
#endif
bool maskIsConsistent(const std::string &s, bool nocase, const vector<u8> &msk,
const vector<u8> &cmp) {
string::const_reverse_iterator si = s.rbegin();
vector<u8>::const_reverse_iterator mi = msk.rbegin(), ci = cmp.rbegin();
for (; si != s.rend() && mi != msk.rend(); ++si, ++mi, ++ci) {
u8 c = *si, m = *mi, v = *ci;
if (nocase && ourisalpha(c)) {
m &= ~CASE_BIT;
v &= ~CASE_BIT;
}
assert(ci != cmp.rend());
if ((c & m) != v) {
DEBUG_PRINTF("c = %02hhx; *ci = %02hhx m =%02hhx\n", c, *ci, m);
DEBUG_PRINTF("s = %s; dist = %zd\n", s.c_str(), si - s.rbegin());
return false;
}
}
return true;
}
hwlmLiteral::hwlmLiteral(const std::string &s_in, bool nocase_in,
bool noruns_in, u32 id_in, hwlm_group_t groups_in,
const vector<u8> &msk_in, const vector<u8> &cmp_in)
: s(s_in), id(id_in), nocase(nocase_in), noruns(noruns_in),
groups(groups_in), msk(msk_in), cmp(cmp_in) {
assert(s.size() <= HWLM_LITERAL_MAX_LEN);
assert(msk.size() <= HWLM_MASKLEN);
assert(msk.size() == cmp.size());
if (nocase) {
upperString(s);
}
DEBUG_PRINTF("literal '%s'%s, msk=%s, cmp=%s\n", escapeString(s).c_str(),
nocase ? " (nocase)" : "", dumpMask(msk).c_str(),
dumpMask(cmp).c_str());
assert(msk.size() == cmp.size());
assert(maskIsConsistent(s, nocase, msk, cmp));
if (all_of(begin(msk), end(msk), [](u8 val) { return val == 0; })) {
msk.clear();
cmp.clear();
}
}
}