Debian Codegraph @

asusrouter/tools/identifiers.py

raw
1 """Identifier tools."""
2
3 from __future__ import annotations
4
5 import re
6 from typing import Any, Final
7
8 from asusrouter.tools.converters import clean_string, safe_int
9
10 MAC_CLEAN_RE: Final[re.Pattern[str]] = re.compile(r"[^0-9a-fA-F]")
11 MAC_LENGTH_BYTES: Final[int] = 6
12 MAC_LENGTH_STR: Final[int] = 12
13
14 ERROR_MAC_BYTE: Final[str] = "MAC address must be exactly 6 bytes"
15 ERROR_MAC_INT: Final[str] = "MAC address must be a 48-bit integer"
16 ERROR_MAC_STR: Final[str] = "Invalid MAC address string"
17 ERROR_MAC_UNSUPPORTED_TYPE: Final[str] = "Unsupported MAC address type"
18
19
20 class MacAddress:
21 """MAC address representation."""
22
23 __slots__ = ("_bytes",)
24
25 def __init__(self, mac: Any) -> None:
26 """Initialize MacAddress.
27
28 If bytes/bytearray of length 6 are passed, they are used directly;
29 otherwise the universal conversion is performed.
30 """
31
32 # Fast-path for raw bytes
33 if isinstance(mac, bytes | bytearray):
34 if len(mac) != MAC_LENGTH_BYTES:
35 raise ValueError(ERROR_MAC_BYTE)
36 self._bytes = bytes(mac)
37 return
38
39 # Use universal conversion
40 self._bytes = type(self)._to_bytes(mac)
41
42 @classmethod
43 def _to_bytes(cls, value: Any) -> bytes:
44 """Convert supported values to 6-byte canonical MAC representation.
45
46 Supported inputs:
47 - MacAddress -> returns underlying bytes
48 - bytes/bytearray (length 6)
49 - int in [0, 2**48)
50 - str with separators or plain hex
51 """
52
53 # Already a MacAddress instance
54 if isinstance(value, cls):
55 return value._bytes
56
57 # Bytes-like
58 if isinstance(value, bytes | bytearray):
59 if len(value) != MAC_LENGTH_BYTES:
60 raise ValueError(ERROR_MAC_BYTE)
61 return bytes(value)
62
63 # Integer-compatible
64 vint = safe_int(value)
65 if isinstance(vint, int):
66 if vint < 0 or vint >= (1 << 48):
67 raise ValueError(ERROR_MAC_INT)
68 return int.to_bytes(vint, 6, "big")
69
70 # String-compatible
71 vstr = clean_string(value)
72 if isinstance(vstr, str):
73 cleaned = MAC_CLEAN_RE.sub("", vstr).lower()
74 if len(cleaned) != MAC_LENGTH_STR or not all(
75 c in "0123456789abcdef" for c in cleaned
76 ):
77 raise ValueError(ERROR_MAC_STR)
78 return bytes.fromhex(cleaned)
79
80 raise ValueError(f"{ERROR_MAC_UNSUPPORTED_TYPE}: {type(value)!r}")
81
82 @classmethod
83 def from_value(cls, value: Any) -> MacAddress:
84 """Create a MacAddress from various representations.
85
86 Returns either the same instance (if passed a MacAddress) or a new
87 MacAddress constructed from the canonical 6-byte representation.
88 """
89
90 if isinstance(value, cls):
91 return value
92
93 # Use the shared parser to obtain bytes, then construct using the
94 # bytes fast-path in __init__.
95 parsed = cls._to_bytes(value)
96 return cls(parsed)
97
98 def as_asus(self) -> str:
99 """Return the MAC address in ASUS format.
100
101 The default Asus format is XX:XX:XX:XX:XX:XX.
102 """
103
104 return str(self).upper()
105
106 def to_bytes(self) -> bytes:
107 """Return the MAC address as bytes."""
108
109 return self._bytes
110
111 def to_int(self) -> int:
112 """Return the MAC address as a 48-bit integer."""
113
114 return int.from_bytes(self._bytes, "big")
115
116 def set_locally_administered(self) -> None:
117 """Transform the MAC address to a locally-administered address.
118
119 For this, the locally-administered bit (bit 1) is set to 1 and the
120 multicast bit (LSB) is cleared (set to 0).
121 """
122
123 _bytes = bytearray(self._bytes)
124 _bytes[0] = (_bytes[0] & ~0x01) | 0x02
125 self._bytes = bytes(_bytes)
126
127 def __str__(self) -> str:
128 """Return the string representation of the MAC address."""
129
130 hx = self._bytes.hex()
131 pairs = [hx[i : i + 2] for i in range(0, 12, 2)]
132 return ":".join(pairs)
133
134 def __repr__(self) -> str:
135 """Return the string representation of the MAC address."""
136
137 return str(self)
138
139 def __eq__(self, other: object) -> bool:
140 """Return whether two MAC addresses are equal."""
141
142 if isinstance(other, MacAddress):
143 return self._bytes == other._bytes
144 try:
145 other_obj = MacAddress.from_value(other)
146 except ValueError:
147 return NotImplemented
148 return self._bytes == other_obj._bytes
149
150 def __hash__(self) -> int:
151 """Return the hash of the MAC address."""
152
153 return hash(self._bytes)