Wildcard.h#

Fully qualified name: omni/str/Wildcard.h

File members: omni/str/Wildcard.h

// SPDX-FileCopyrightText: Copyright (c) 2020-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: LicenseRef-NvidiaProprietary
//
// NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
// property and proprietary rights in and to this material, related
// documentation and any modifications thereto. Any use, reproduction,
// disclosure or distribution of this material and related documentation
// without an express license agreement from NVIDIA CORPORATION or
// its affiliates 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