Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Optimize _encode_invalid_chars (#1787)
Co-authored-by: Seth Michael Larson <sethmichaellarson@gmail.com>
- Loading branch information
1 parent
d2a5a59
commit a2697e7
Showing
2 changed files
with
8 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -216,18 +216,15 @@ def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"): | |
|
||
component = six.ensure_text(component) | ||
|
||
# Normalize existing percent-encoded bytes. | ||
# Try to see if the component we're encoding is already percent-encoded | ||
# so we can skip all '%' characters but still encode all others. | ||
percent_encodings = PERCENT_RE.findall(component) | ||
|
||
# Normalize existing percent-encoded bytes. | ||
for enc in percent_encodings: | ||
if not enc.isupper(): | ||
component = component.replace(enc, enc.upper()) | ||
component, percent_encodings = PERCENT_RE.subn( | ||
This comment has been minimized.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
pquentin
Author
Member
|
||
lambda match: match.group(0).upper(), component | ||
) | ||
|
||
uri_bytes = component.encode("utf-8", "surrogatepass") | ||
is_percent_encoded = len(percent_encodings) == uri_bytes.count(b"%") | ||
|
||
is_percent_encoded = percent_encodings == uri_bytes.count(b"%") | ||
encoded_component = bytearray() | ||
|
||
for i in range(0, len(uri_bytes)): | ||
|
@@ -237,7 +234,7 @@ def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"): | |
if (is_percent_encoded and byte == b"%") or ( | ||
byte_ord < 128 and byte.decode() in allowed_chars | ||
): | ||
encoded_component.extend(byte) | ||
encoded_component += byte | ||
continue | ||
encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) | ||
|
||
|
Would it be even faster if PERCENT_RE could also exclude matches that contain no lower case alphas (e.g. '%22' or '%2A')?