|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations |
|
|
|
|
|
import binascii |
|
|
import struct |
|
|
|
|
|
from pyiceberg.avro.codecs.codec import Codec |
|
|
|
|
|
STRUCT_CRC32 = struct.Struct(">I") |
|
|
|
|
|
try: |
|
|
import snappy |
|
|
|
|
|
class SnappyCodec(Codec): |
|
|
@staticmethod |
|
|
def _check_crc32(bytes_: bytes, checksum: bytes) -> None: |
|
|
"""Incrementally compute CRC-32 from bytes and compare to a checksum. |
|
|
|
|
|
Args: |
|
|
bytes_ (bytes): The bytes to check against `checksum` |
|
|
checksum (bytes): Byte representation of a checksum |
|
|
|
|
|
Raises: |
|
|
ValueError: If the computed CRC-32 does not match the checksum |
|
|
""" |
|
|
if binascii.crc32(bytes_) & 0xFFFFFFFF != STRUCT_CRC32.unpack(checksum)[0]: |
|
|
raise ValueError("Checksum failure") |
|
|
|
|
|
@staticmethod |
|
|
def compress(data: bytes) -> tuple[bytes, int]: |
|
|
compressed_data = snappy.compress(data) |
|
|
|
|
|
compressed_data += STRUCT_CRC32.pack(binascii.crc32(data) & 0xFFFFFFFF) |
|
|
return compressed_data, len(compressed_data) |
|
|
|
|
|
@staticmethod |
|
|
def decompress(data: bytes) -> bytes: |
|
|
|
|
|
data = data[0:-4] |
|
|
uncompressed = snappy.decompress(data) |
|
|
checksum = data[-4:] |
|
|
SnappyCodec._check_crc32(uncompressed, checksum) |
|
|
return uncompressed |
|
|
|
|
|
except ImportError: |
|
|
|
|
|
class SnappyCodec(Codec): |
|
|
@staticmethod |
|
|
def compress(data: bytes) -> tuple[bytes, int]: |
|
|
raise ImportError("Snappy support not installed, please install using `pip install pyiceberg[snappy]`") |
|
|
|
|
|
@staticmethod |
|
|
def decompress(data: bytes) -> bytes: |
|
|
raise ImportError("Snappy support not installed, please install using `pip install pyiceberg[snappy]`") |
|
|
|