Skip to content

Refactor validate_mac_address method #294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 27 additions & 49 deletions pydantic_extra_types/mac_address.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,58 +63,36 @@ def _validate(cls, __input_value: str, _: Any) -> str:
@staticmethod
def validate_mac_address(value: bytes) -> str:
"""Validate a MAC Address from the provided byte value."""
if len(value) < 14:
string = value.decode()
if len(string) < 14:
raise PydanticCustomError(
'mac_address_len',
'Length for a {mac_address} MAC address must be {required_length}',
{'mac_address': value.decode(), 'required_length': 14},
{'mac_address': string, 'required_length': 14},
)

if value[2] in [ord(':'), ord('-')]:
if (len(value) + 1) % 3 != 0:
raise PydanticCustomError(
'mac_address_format', 'Must have the format xx:xx:xx:xx:xx:xx or xx-xx-xx-xx-xx-xx'
)
n = (len(value) + 1) // 3
if n not in (6, 8, 20):
raise PydanticCustomError(
'mac_address_format',
'Length for a {mac_address} MAC address must be {required_length}',
{'mac_address': value.decode(), 'required_length': (6, 8, 20)},
)
mac_address = bytearray(n)
x = 0
for i in range(n):
try:
byte_value = int(value[x : x + 2], 16)
mac_address[i] = byte_value
x += 3
except ValueError as e:
raise PydanticCustomError('mac_address_format', 'Unrecognized format') from e

elif value[4] == ord('.'):
if (len(value) + 1) % 5 != 0:
raise PydanticCustomError('mac_address_format', 'Must have the format xx.xx.xx.xx.xx.xx')
n = 2 * (len(value) + 1) // 5
if n not in (6, 8, 20):
raise PydanticCustomError(
'mac_address_format',
'Length for a {mac_address} MAC address must be {required_length}',
{'mac_address': value.decode(), 'required_length': (6, 8, 20)},
)
mac_address = bytearray(n)
x = 0
for i in range(0, n, 2):
try:
byte_value = int(value[x : x + 2], 16)
mac_address[i] = byte_value
byte_value = int(value[x + 2 : x + 4], 16)
mac_address[i + 1] = byte_value
x += 5
except ValueError as e:
raise PydanticCustomError('mac_address_format', 'Unrecognized format') from e

for sep, partbytes in ((':', 2), ('-', 2), ('.', 4)):
if sep in string:
parts = string.split(sep)
if any(len(part) != partbytes for part in parts):
raise PydanticCustomError(
'mac_address_format',
f'Must have the format xx{sep}xx{sep}xx{sep}xx{sep}xx{sep}xx',
)
if len(parts) * partbytes // 2 not in (6, 8, 20):
raise PydanticCustomError(
'mac_address_format',
'Length for a {mac_address} MAC address must be {required_length}',
{'mac_address': string, 'required_length': (6, 8, 20)},
)
mac_address = []
for part in parts:
for idx in range(0, partbytes, 2):
try:
byte_value = int(part[idx : idx + 2], 16)
except ValueError as exc:
raise PydanticCustomError('mac_address_format', 'Unrecognized format') from exc
else:
mac_address.append(byte_value)
return ':'.join(f'{b:02x}' for b in mac_address)
else:
raise PydanticCustomError('mac_address_format', 'Unrecognized format')

return ':'.join(f'{b:02x}' for b in mac_address)