view th_strglob.c @ 735:31bc1ed07cf5

Renaming BOOL->bool and TRUE/FALSE to true/false, and using stdbool.h if available.
author Matti Hamalainen <ccr@tnsp.org>
date Wed, 07 Dec 2022 12:14:39 +0200
parents 29e44a58bc73
children 600a3c08747f
line wrap: on
line source

/*
 * String glob match implementation
 * Programmed and designed by Matti 'ccr' Hamalainen
 * (C) Copyright 2002-2022 Tecnic Software productions (TNSP)
 *
 * Please read file 'COPYING' for information on license and distribution.
 */

bool TH_STRGLOB_FUNC (const char *haystack, const char *pattern)
{
    bool matched = true, any = false, end = false;
    const char *tmp = NULL;

    // Check given pattern and string
    if (haystack == NULL || pattern == NULL)
        return false;

    // Start comparision
    while (matched && !end)
    switch (*pattern)
    {
    case '?':
        // Any single character matches
        if (*haystack)
        {
            pattern++;
            haystack++;
        }
        else
            matched = false;
        break;

    case '*':
        pattern++;
        if (!*pattern || *pattern == '?')
            end = true;
        any = true;
        tmp = pattern;
        break;

    case 0:
        if (any)
        {
            if (*haystack)
                haystack++;
            else
                end = true;
        }
        else
        if (*haystack)
        {
            if (tmp)
            {
                any = true;
                pattern = tmp;
            }
            else
                matched = false;
        }
        else
            end = true;
        break;

    default:
        {
            bool equals = TH_STRGLOB_COLLATE(*pattern) == TH_STRGLOB_COLLATE(*haystack);
            if (any)
            {
                if (equals)
                {
                    any = false;
                }
                else
                if (*haystack)
                    haystack++;
                else
                    matched = false;
            }
            else
            {
                if (equals)
                {
                    if (*pattern)
                        pattern++;
                    if (*haystack)
                        haystack++;
                }
                else
                if (tmp)
                {
                    any = true;
                    pattern = tmp;
                }
                else
                    matched = false;
            }

            if (!*haystack && !*pattern)
                end = true;
        }
        break;
    }

    return matched;
}


#undef TH_STRGLOB_FUNC
#undef TH_STRGLOB_COLLATE