Loading...
Searching...
No Matches
globPattern.h
1//
2// Copyright 2026 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_USD_SDF_GLOB_PATTERN_H
8#define PXR_USD_SDF_GLOB_PATTERN_H
9
10#include "pxr/pxr.h"
11#include "pxr/usd/sdf/api.h"
12
13#include <cstddef>
14#include <cstdint>
15#include <memory>
16#include <string_view>
17
18PXR_NAMESPACE_OPEN_SCOPE
19
20// A compiled glob pattern matcher optimized for matching short UTF-8 strings
21// (e.g. path component names). Supports *, ?, [abc], [a-z], [!a-z], and
22// backslash escapes. The pattern is compiled into a flat bytecoded
23// representation for fast matching.
24//
25// UTF-8 contract: both the pattern passed to Compile() and the string passed to
26// Match() must be valid UTF-8. This is NOT checked -- malformed input produces
27// undefined behavior (out-of-bounds reads, false positives/negatives, etc.).
28// Callers are responsible for validating input upstream.
29//
30// Size limits: the compiled pattern is held in a buffer of at most 64KB, so
31// pattern strings producing more than ~64KB of bytecode will not compile
32// correctly. In practice patterns are far shorter than that.
33class Sdf_GlobPattern {
34public:
35 Sdf_GlobPattern() = default;
36
37 SDF_API
38 Sdf_GlobPattern(Sdf_GlobPattern const &);
39 SDF_API
40 Sdf_GlobPattern &operator=(Sdf_GlobPattern const &);
41
42 Sdf_GlobPattern(Sdf_GlobPattern &&) noexcept = default;
43 Sdf_GlobPattern &operator=(Sdf_GlobPattern &&) noexcept = default;
44
45 // Compile a glob pattern. The pattern must be valid UTF-8 (not checked).
46 // Returns an invalid pattern on parse error.
47 SDF_API
48 static Sdf_GlobPattern Compile(const char *pattern, size_t patLen);
49 static Sdf_GlobPattern Compile(std::string_view pattern) {
50 return Compile(pattern.data(), pattern.size());
51 }
52
53 // Match a UTF-8 string against the compiled pattern. The string must be
54 // valid UTF-8 (not checked).
55 SDF_API
56 bool Match(const char *str, size_t len) const;
57 bool Match(std::string_view str) const {
58 return Match(str.data(), str.size());
59 }
60
61 // True if the pattern compiled successfully.
62 explicit operator bool() const {
63 return _flags & _Compiled;
64 }
65
66private:
67 // Sentinel flag bit set by Compile() on success. Default-constructed
68 // (flags == 0) patterns are therefore invalid until populated.
69 static constexpr uint16_t _Compiled = 1u << 15;
70
71 std::unique_ptr<uint8_t[]> _buf;
72 uint16_t _bufSize = 0;
73 uint16_t _minBytes = 0;
74 uint16_t _flags = 0;
75 uint16_t _suffixCodePointCount = 0;
76};
77
78PXR_NAMESPACE_CLOSE_SCOPE
79
80#endif // PXR_USD_SDF_GLOB_PATTERN_H
STL namespace.