Skip to content

Commit 22786cc

Browse files
Apeksha9389nandgator
authored andcommitted
Require complete bytes in Base16 encodings
1 parent b330d82 commit 22786cc

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

‎src/validators/encoding.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
def base16(value: str, /):
1212
"""Return whether or not given value is a valid base16 encoding.
1313
14+
Each encoded byte requires two hexadecimal characters.
15+
1416
Examples:
1517
>>> base16('a3f4b2')
1618
True
@@ -25,7 +27,7 @@ def base16(value: str, /):
2527
(Literal[True]): If `value` is a valid base16 encoding.
2628
(ValidationError): If `value` is an invalid base16 encoding.
2729
"""
28-
return re.fullmatch(r"^[0-9A-Fa-f]+$", value) if value else False
30+
return re.fullmatch(r"(?:[0-9A-Fa-f]{2})+", value) if value else False
2931

3032

3133
@validator

‎tests/test_encoding.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ def test_returns_failed_validation_on_invalid_base16(value: str):
3838
assert isinstance(base16(value), ValidationError)
3939

4040

41+
@pytest.mark.parametrize("value", ["0", "a", "ABC", "012345678", "abcdef01234567890"])
42+
def test_base16_rejects_incomplete_bytes(value: str):
43+
"""Reject a dangling half-byte even when every character is hexadecimal."""
44+
assert isinstance(base16(value), ValidationError)
45+
46+
4147
# ==> base32 <== #
4248

4349

0 commit comments

Comments
 (0)