ksjsb/core/sig3_shape.py
2026-07-30 20:25:56 +08:00

60 lines
1.4 KiB
Python

"""Shape classifier for the two observed `__NS_sig3` families."""
from __future__ import annotations
from enum import Enum
API_10418_SIG3_HEX_LENGTH = 48
H5_SIG3_HEX_LENGTH = 68
class Sig3Shape(str, Enum):
API_10418 = "api_10418"
H5_ENVELOPE = "h5_envelope"
UNKNOWN = "unknown"
def _is_hex(value: str) -> bool:
try:
int(value, 16)
except ValueError:
return False
return bool(value)
def classify_sig3(value: str | bytes | bytearray | None) -> Sig3Shape:
"""Classify `__NS_sig3` by confirmed wire length."""
if value is None:
return Sig3Shape.UNKNOWN
if isinstance(value, (bytes, bytearray)):
text = bytes(value).hex()
else:
text = str(value).strip()
if not _is_hex(text):
return Sig3Shape.UNKNOWN
if len(text) == API_10418_SIG3_HEX_LENGTH:
return Sig3Shape.API_10418
if len(text) == H5_SIG3_HEX_LENGTH:
return Sig3Shape.H5_ENVELOPE
return Sig3Shape.UNKNOWN
def is_api_10418_sig3(value: str | bytes | bytearray | None) -> bool:
return classify_sig3(value) == Sig3Shape.API_10418
def is_h5_sig3(value: str | bytes | bytearray | None) -> bool:
return classify_sig3(value) == Sig3Shape.H5_ENVELOPE
__all__ = [
"API_10418_SIG3_HEX_LENGTH",
"H5_SIG3_HEX_LENGTH",
"Sig3Shape",
"classify_sig3",
"is_api_10418_sig3",
"is_h5_sig3",
]