brotli.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright 2016 The Brotli Authors. All rights reserved.
  2. #
  3. # Distributed under MIT license.
  4. # See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. """Functions to compress and decompress data using the Brotli library."""
  6. import _brotli
  7. # The library version.
  8. version = __version__ = _brotli.__version__
  9. # The compression mode.
  10. MODE_GENERIC = _brotli.MODE_GENERIC
  11. MODE_TEXT = _brotli.MODE_TEXT
  12. MODE_FONT = _brotli.MODE_FONT
  13. # The Compressor object.
  14. Compressor = _brotli.Compressor
  15. # The Decompressor object.
  16. Decompressor = _brotli.Decompressor
  17. # Compress a byte string.
  18. def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0):
  19. """Compress a byte string.
  20. Args:
  21. string (bytes): The input data.
  22. mode (int, optional): The compression mode; value 0 should be used for
  23. generic input (MODE_GENERIC); value 1 might be beneficial for UTF-8 text
  24. input (MODE_TEXT); value 2 tunes encoder for WOFF 2.0 data (MODE_FONT).
  25. Defaults to 0.
  26. quality (int, optional): Controls the compression-speed vs compression-
  27. density tradeoff. The higher the quality, the slower the compression.
  28. Range is 0 to 11. Defaults to 11.
  29. lgwin (int, optional): Base 2 logarithm of the sliding window size. Range
  30. is 10 to 24. Defaults to 22.
  31. lgblock (int, optional): Base 2 logarithm of the maximum input block size.
  32. Range is 16 to 24. If set to 0, the value will be set based on the
  33. quality. Defaults to 0.
  34. Returns:
  35. The compressed byte string.
  36. Raises:
  37. brotli.error: If arguments are invalid, or compressor fails.
  38. """
  39. compressor = Compressor(mode=mode, quality=quality, lgwin=lgwin,
  40. lgblock=lgblock)
  41. return compressor.process(string) + compressor.finish()
  42. # Decompress a compressed byte string.
  43. decompress = _brotli.decompress
  44. # Raised if compression or decompression fails.
  45. error = _brotli.error