import zstandard

from django_redis.exceptions import CompressorError
from django_redis.compressors.base import BaseCompressor


class ZstandardCompressor(BaseCompressor):
    """
    Redis cache compressor for Zstandard compression.
    """

    min_length = 15
    level = 3

    def compress(self, value: bytes) -> bytes:
        if len(value) > self.min_length:
            return zstandard.compress(value, self.level)
        return value

    def decompress(self, value: bytes) -> bytes:
        try:
            return zstandard.decompress(value)
        except Exception as e:
            raise CompressorError(e) from None
