omni/str/Wildcard.h

File members: omni/str/Wildcard.h

// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once

#include <stddef.h>
#include <cstdint>

namespace omni
{
namespace str
{

inline bool matchWildcard(const char* str, const char* pattern)
{
    const char* star = nullptr;
    const char* s0 = str;
    const char* s1 = s0;
    const char* p = pattern;
    while (*s0)
    {
        // Advance both pointers when both characters match or '?' found in pattern
        if ((*p == '?') || (*p == *s0))
        {
            s0++;
            p++;
            continue;
        }

        // * found in pattern, save index of *, advance a pattern pointer
        if (*p == '*')
        {
            star = p++;
            s1 = s0;
            continue;
        }

        // Current characters didn't match, consume character in string and rewind to star pointer in the pattern
        if (star)
        {
            p = star + 1;
            s0 = ++s1;
            continue;
        }

        // Characters do not match and current pattern pointer is not star
        return false;
    }

    // Skip remaining stars in pattern
    while (*p == '*')
    {
        p++;
    }

    return !*p; // Was whole pattern matched?
}

inline const char* matchWildcards(const char* str, const char* const* patterns, size_t patternsCount)
{
    for (size_t i = 0; i < patternsCount; ++i)
    {
        if (matchWildcard(str, patterns[i]))
        {
            return patterns[i];
        }
    }

    return nullptr;
}

inline bool isWildcardPattern(const char* pattern)
{
    for (const char* p = pattern; p[0] != 0; p++)
    {
        if (*p == '*' || *p == '?')
            return true;
    }

    return false;
}

} // namespace str
} // namespace omni