zstd.py 857 B

12345678910111213141516171819202122232425262728293031
  1. from __future__ import annotations
  2. __all__ = ["ZstdCompression"]
  3. import zstandard
  4. from . import Compression
  5. class ZstdCompression(Compression):
  6. """Compression implementation using Zstandard."""
  7. def __init__(self, level: int = 3) -> None:
  8. """Creates a new ZstdCompression.
  9. Args:
  10. level: Compression level to use.
  11. """
  12. self._level = level
  13. def name(self) -> str:
  14. return "zstd"
  15. def compress(self, data: bytes | bytearray | memoryview) -> bytes:
  16. return zstandard.ZstdCompressor(level=self._level).compress(data)
  17. def decompress(self, data: bytes | bytearray | memoryview) -> bytes:
  18. # Support clients sending frames without length by using
  19. # stream API.
  20. with zstandard.ZstdDecompressor().stream_reader(data) as reader:
  21. return reader.read()