-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnfc_utils.py
More file actions
30 lines (25 loc) · 836 Bytes
/
Copy pathnfc_utils.py
File metadata and controls
30 lines (25 loc) · 836 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import re
UID_SEPARATORS = re.compile(r"[\s:._-]+")
def canonicalize_nfc_uid(value):
"""Return one stable representation for text or raw-byte NFC UIDs."""
if value is None:
return ""
if isinstance(value, (bytes, bytearray)):
raw = bytes(value)
if not raw:
return ""
try:
text = raw.decode("ascii")
except UnicodeDecodeError:
return raw.hex().upper()
if any(ord(character) < 32 and not character.isspace() for character in text):
return raw.hex().upper()
else:
text = str(value)
text = text.strip().upper()
compact = UID_SEPARATORS.sub("", text)
if compact.startswith("0X"):
compact = compact[2:]
if compact and re.fullmatch(r"[0-9A-F]+", compact):
return compact
return text