libweb/wildcard_cmp.c
Xavier Del Campo Romero 0222b75e85
Rename project from slweb to libweb
It was found out there was another project of the same name around
(https://git.sr.ht/~strahinja/slweb/), also related to website
generation.

In order to avoid confusion, a new name has been chosen for this
project. Surprisingly, libweb was not in use by any distributions
(according to https://repology.org and AUR index), and it should
reflect well the intention behind this project i.e., being a library
to build web-related stuff.
2023-10-11 00:07:13 +02:00

74 lines
1.5 KiB
C

#include "libweb/wildcard_cmp.h"
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <strings.h>
int wildcard_cmp(const char *s, const char *p, const bool casecmp)
{
const char *last = NULL;
int (*const cmp)(const char *, const char *) =
casecmp ? strcmp : strcasecmp;
int (*const ncmp)(const char *, const char *, size_t) =
casecmp ? strncmp : strncasecmp;
while (*p && *s)
{
const char *const wc = strchr(p, '*');
if (!wc)
{
const int r = cmp(s, p);
if (r && last)
{
p = last;
s += strlen(p);
continue;
}
else
return r;
}
const size_t auxn = wc - p, rem = strlen(s),
n = auxn > rem ? rem : auxn;
if (n)
{
const int r = ncmp(s, p, n);
if (r)
{
if (last)
p = last;
else
return r;
}
else
p += n;
s += n;
}
else
{
const char next = *(wc + 1), wca[2] = {next}, sa[sizeof wca] = {*s};
if (!cmp(wca, sa))
{
last = p;
p = wc + 1;
}
else if (next == '*')
p++;
else
s++;
}
}
while (*p)
if (*p++ != '*')
return -1;
return 0;
}