Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
_struct.py58 linesDownload Raw Back to psycopg
1"""2Utility functions to deal with binary structs.3"""4 5# Copyright (C) 2020 The Psycopg Team6 7import struct8from typing import Callable, cast, Optional, Tuple9from typing_extensions import TypeAlias10 11from .abc import Buffer12from . import errors as e13from ._compat import Protocol14 15PackInt: TypeAlias = Callable[[int], bytes]16UnpackInt: TypeAlias = Callable[[Buffer], Tuple[int]]17PackFloat: TypeAlias = Callable[[float], bytes]18UnpackFloat: TypeAlias = Callable[[Buffer], Tuple[float]]19 20 21class UnpackLen(Protocol):22    def __call__(self, data: Buffer, start: Optional[int]) -> Tuple[int]:23        ...24 25 26pack_int2 = cast(PackInt, struct.Struct("!h").pack)27pack_uint2 = cast(PackInt, struct.Struct("!H").pack)28pack_int4 = cast(PackInt, struct.Struct("!i").pack)29pack_uint4 = cast(PackInt, struct.Struct("!I").pack)30pack_int8 = cast(PackInt, struct.Struct("!q").pack)31pack_float4 = cast(PackFloat, struct.Struct("!f").pack)32pack_float8 = cast(PackFloat, struct.Struct("!d").pack)33 34unpack_int2 = cast(UnpackInt, struct.Struct("!h").unpack)35unpack_uint2 = cast(UnpackInt, struct.Struct("!H").unpack)36unpack_int4 = cast(UnpackInt, struct.Struct("!i").unpack)37unpack_uint4 = cast(UnpackInt, struct.Struct("!I").unpack)38unpack_int8 = cast(UnpackInt, struct.Struct("!q").unpack)39unpack_float4 = cast(UnpackFloat, struct.Struct("!f").unpack)40unpack_float8 = cast(UnpackFloat, struct.Struct("!d").unpack)41 42_struct_len = struct.Struct("!i")43pack_len = cast(Callable[[int], bytes], _struct_len.pack)44unpack_len = cast(UnpackLen, _struct_len.unpack_from)45 46 47def pack_float4_bug_304(x: float) -> bytes:48    raise e.InterfaceError(49        "cannot dump Float4: Python affected by bug #304. Note that the psycopg-c"50        " and psycopg-binary packages are not affected by this issue."51        " See https://github.com/psycopg/psycopg/issues/304"52    )53 54 55# If issue #304 is detected, raise an error instead of dumping wrong data.56if struct.Struct("!f").pack(1.0) != bytes.fromhex("3f800000"):57    pack_float4 = pack_float4_bug_30458