Skip to content

Commit c8749e3

Browse files
committed
refactor: optimize UrlDecoder::Decode()
1 parent 43cfd7c commit c8749e3

File tree

1 file changed

+19
-23
lines changed

1 file changed

+19
-23
lines changed

ext/include/opentelemetry/ext/http/common/url_parser.h

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -194,36 +194,32 @@ class UrlDecoder
194194
std::string result;
195195
result.reserve(encoded.size());
196196

197+
auto hex_to_int = [](int ch) -> int {
198+
if (ch >= '0' && ch <= '9')
199+
return ch - '0';
200+
if (ch >= 'a' && ch <= 'f')
201+
return ch - 'a' + 10;
202+
if (ch >= 'A' && ch <= 'F')
203+
return ch - 'A' + 10;
204+
return -1;
205+
};
206+
197207
for (size_t pos = 0; pos < encoded.size(); pos++)
198208
{
199-
if (encoded[pos] == '%')
209+
auto c = encoded[pos];
210+
if (c == '%' && pos + 2 < encoded.size())
200211
{
212+
int hi = hex_to_int(encoded[pos + 1]);
213+
int lo = hex_to_int(encoded[pos + 2]);
201214

202-
// Invalid input: less than two characters left after '%'
203-
if (encoded.size() < pos + 3)
204-
{
205-
return encoded;
206-
}
207-
208-
char hex[3] = {0};
209-
hex[0] = encoded[++pos];
210-
hex[1] = encoded[++pos];
211-
212-
char *endptr;
213-
int value = static_cast<int>(std::strtol(hex, &endptr, 16));
214-
215-
// Invalid input: no valid hex characters after '%'
216-
if (endptr != &hex[2])
215+
if (hi != -1 && lo != -1)
217216
{
218-
return encoded;
217+
c = static_cast<char>((hi << 4) | lo);
218+
pos += 2;
219219
}
220-
221-
result.push_back(static_cast<char>(value));
222-
}
223-
else
224-
{
225-
result.push_back(encoded[pos]);
226220
}
221+
222+
result.push_back(c);
227223
}
228224

229225
return result;

0 commit comments

Comments
 (0)