-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpattern.hpp
More file actions
114 lines (96 loc) · 3.15 KB
/
pattern.hpp
File metadata and controls
114 lines (96 loc) · 3.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include <vector>
#include <string>
#include <cstdint>
#include <algorithm>
#include <memory>
class Pattern {
public:
struct BytePattern {
uint8_t value;
bool isWildcard;
};
Pattern() = default;
explicit Pattern(const std::string& patternStr) {
ParsePattern(patternStr);
}
void ParsePattern(const std::string& patternStr) {
bytes.clear();
mask.clear();
patternBytes.clear();
std::string currentByte;
bool inWildcard = false;
for (char c : patternStr) {
if (c == '?') {
if (!currentByte.empty()) {
AddByte(currentByte, false);
currentByte.clear();
}
inWildcard = true;
}
else if (c == ' ' || c == '\t') {
if (!currentByte.empty()) {
AddByte(currentByte, inWildcard);
currentByte.clear();
inWildcard = false;
}
}
else if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f')) {
currentByte += c;
if (inWildcard && currentByte.length() == 2) {
AddByte(currentByte, true);
currentByte.clear();
inWildcard = false;
}
}
}
if (!currentByte.empty()) {
AddByte(currentByte, inWildcard);
}
for (const auto& bp : bytes) {
patternBytes.push_back(bp.value);
mask.push_back(bp.isWildcard ? 0 : 0xFF);
}
}
const std::vector<BytePattern>& GetBytes() const { return bytes; }
const std::vector<uint8_t>& GetPatternBytes() const { return patternBytes; }
// mask (0xFF for wildcards)
const std::vector<uint8_t>& GetMask() const { return mask; }
size_t Size() const { return bytes.size(); }
bool IsValid() const { return !bytes.empty(); }
std::string ToString() const {
std::string result;
for (size_t i = 0; i < bytes.size(); ++i) {
if (i > 0) result += " ";
if (bytes[i].isWildcard) {
result += "??";
}
else {
char buf[3];
snprintf(buf, sizeof(buf), "%02X", bytes[i].value);
result += buf;
}
}
return result;
}
private:
void AddByte(const std::string& byteStr, bool isWildcard) {
BytePattern bp;
bp.isWildcard = isWildcard;
if (!isWildcard && byteStr.length() == 2) {
bp.value = static_cast<uint8_t>(std::stoi(byteStr, nullptr, 16));
}
else if (isWildcard && byteStr.length() == 2) {
bp.value = static_cast<uint8_t>(std::stoi(byteStr, nullptr, 16));
}
else {
bp.value = 0;
}
bytes.push_back(bp);
}
std::vector<BytePattern> bytes;
std::vector<uint8_t> patternBytes;
std::vector<uint8_t> mask;
};