Skip to content
Myr

utils.py

This file

Path

http3/utils.py

66 lines · 2.1 KiB · Python

Last changed by

Encoding detection in Response.json (#116)Yeray Diaz Diazbefore adoption5442006

History of this file

Take it

1import codecs2import typing345def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:6    """7    Coerce str/bytes into a strictly byte-wise HTTP header key.8    """9    if isinstance(value, bytes):10        return value.lower()11    return value.encode(encoding or "ascii").lower()121314def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:15    """16    Coerce str/bytes into a strictly byte-wise HTTP header value.17    """18    if isinstance(value, bytes):19        return value20    return value.encode(encoding or "ascii")212223def is_known_encoding(encoding: str) -> bool:24    """25    Return `True` if `encoding` is a known codec.26    """27    try:28        codecs.lookup(encoding)29    except LookupError:30        return False31    return True323334# Null bytes; no need to recreate these on each call to guess_json_utf35_null = "\x00".encode("ascii")  # encoding to ASCII for Python 336_null2 = _null * 237_null3 = _null * 3383940def guess_json_utf(data: bytes) -> typing.Optional[str]:41    # JSON always starts with two ASCII characters, so detection is as42    # easy as counting the nulls and from their location and count43    # determine the encoding. Also detect a BOM, if present.44    sample = data[:4]45    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):46        return "utf-32"  # BOM included47    if sample[:3] == codecs.BOM_UTF8:48        return "utf-8-sig"  # BOM included, MS style (discouraged)49    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):50        return "utf-16"  # BOM included51    nullcount = sample.count(_null)52    if nullcount == 0:53        return "utf-8"54    if nullcount == 2:55        if sample[::2] == _null2:  # 1st and 3rd are null56            return "utf-16-be"57        if sample[1::2] == _null2:  # 2nd and 4th are null58            return "utf-16-le"59        # Did not detect 2 valid UTF-16 ascii-range characters60    if nullcount == 3:61        if sample[:3] == _null3:62            return "utf-32-be"63        if sample[1:] == _null3:64            return "utf-32-le"65        # Did not detect a valid UTF-32 ascii-range character66    return None