Alex Nicksay | f7b5b3d | 2016-09-28 17:26:00 -0400 | [diff] [blame] | 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 | |
| 6 | """Functions to compress and decompress data using the Brotli library.""" |
| 7 | |
| 8 | import _brotli |
| 9 | |
| 10 | |
| 11 | # The library version. |
| 12 | __version__ = _brotli.__version__ |
| 13 | |
| 14 | # The compression mode. |
| 15 | MODE_GENERIC = _brotli.MODE_GENERIC |
| 16 | MODE_TEXT = _brotli.MODE_TEXT |
| 17 | MODE_FONT = _brotli.MODE_FONT |
| 18 | |
Alex Nicksay | afb1272 | 2016-10-25 04:19:29 -0400 | [diff] [blame] | 19 | # The Compressor object. |
| 20 | Compressor = _brotli.Compressor |
| 21 | |
Janek | 58f5c37 | 2017-06-28 16:32:28 +0200 | [diff] [blame] | 22 | # The Decompressor object. |
| 23 | Decompressor = _brotli.Decompressor |
| 24 | |
Alex Nicksay | f7b5b3d | 2016-09-28 17:26:00 -0400 | [diff] [blame] | 25 | # Compress a byte string. |
Eugene Kliuchnikov | d63e8f7 | 2017-08-04 10:02:56 +0200 | [diff] [blame] | 26 | def compress(string, mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0): |
Alex Nicksay | 595a524 | 2016-09-29 15:14:16 -0400 | [diff] [blame] | 27 | """Compress a byte string. |
| 28 | |
| 29 | Args: |
| 30 | string (bytes): The input data. |
| 31 | mode (int, optional): The compression mode can be MODE_GENERIC (default), |
| 32 | MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0). |
| 33 | quality (int, optional): Controls the compression-speed vs compression- |
| 34 | density tradeoff. The higher the quality, the slower the compression. |
| 35 | Range is 0 to 11. Defaults to 11. |
| 36 | lgwin (int, optional): Base 2 logarithm of the sliding window size. Range |
| 37 | is 10 to 24. Defaults to 22. |
| 38 | lgblock (int, optional): Base 2 logarithm of the maximum input block size. |
| 39 | Range is 16 to 24. If set to 0, the value will be set based on the |
| 40 | quality. Defaults to 0. |
Alex Nicksay | 595a524 | 2016-09-29 15:14:16 -0400 | [diff] [blame] | 41 | |
| 42 | Returns: |
| 43 | The compressed byte string. |
| 44 | |
| 45 | Raises: |
| 46 | brotli.error: If arguments are invalid, or compressor fails. |
| 47 | """ |
Alex Nicksay | afb1272 | 2016-10-25 04:19:29 -0400 | [diff] [blame] | 48 | compressor = Compressor(mode=mode, quality=quality, lgwin=lgwin, |
Eugene Kliuchnikov | d63e8f7 | 2017-08-04 10:02:56 +0200 | [diff] [blame] | 49 | lgblock=lgblock) |
Alex Nicksay | 5632315 | 2016-10-24 07:28:56 -0400 | [diff] [blame] | 50 | return compressor.process(string) + compressor.finish() |
Alex Nicksay | f7b5b3d | 2016-09-28 17:26:00 -0400 | [diff] [blame] | 51 | |
| 52 | # Decompress a compressed byte string. |
| 53 | decompress = _brotli.decompress |
| 54 | |
| 55 | # Raised if compression or decompression fails. |
| 56 | error = _brotli.error |