A file-like object providing transparent Zstandard (de)compression. A ZstdFile can act as a wrapper for an existing file object, or refer directly to a named file on disk. ZstdFile provides a *binary* file interface. Data is read and returned as bytes, and may only be written to ob
| 18 | |
| 19 | |
| 20 | class ZstdFile(_streams.BaseStream): |
| 21 | """A file-like object providing transparent Zstandard (de)compression. |
| 22 | |
| 23 | A ZstdFile can act as a wrapper for an existing file object, or refer |
| 24 | directly to a named file on disk. |
| 25 | |
| 26 | ZstdFile provides a *binary* file interface. Data is read and returned as |
| 27 | bytes, and may only be written to objects that support the Buffer Protocol. |
| 28 | """ |
| 29 | |
| 30 | FLUSH_BLOCK = ZstdCompressor.FLUSH_BLOCK |
| 31 | FLUSH_FRAME = ZstdCompressor.FLUSH_FRAME |
| 32 | |
| 33 | def __init__(self, file, /, mode='r', *, |
| 34 | level=None, options=None, zstd_dict=None): |
| 35 | """Open a Zstandard compressed file in binary mode. |
| 36 | |
| 37 | *file* can be either an file-like object, or a file name to open. |
| 38 | |
| 39 | *mode* can be 'r' for reading (default), 'w' for (over)writing, 'x' for |
| 40 | creating exclusively, or 'a' for appending. These can equivalently be |
| 41 | given as 'rb', 'wb', 'xb' and 'ab' respectively. |
| 42 | |
| 43 | *level* is an optional int specifying the compression level to use, |
| 44 | or COMPRESSION_LEVEL_DEFAULT if not given. |
| 45 | |
| 46 | *options* is an optional dict for advanced compression parameters. |
| 47 | See CompressionParameter and DecompressionParameter for the possible |
| 48 | options. |
| 49 | |
| 50 | *zstd_dict* is an optional ZstdDict object, a pre-trained Zstandard |
| 51 | dictionary. See train_dict() to train ZstdDict on sample data. |
| 52 | """ |
| 53 | self._fp = None |
| 54 | self._close_fp = False |
| 55 | self._mode = _MODE_CLOSED |
| 56 | self._buffer = None |
| 57 | |
| 58 | if not isinstance(mode, str): |
| 59 | raise ValueError('mode must be a str') |
| 60 | if options is not None and not isinstance(options, dict): |
| 61 | raise TypeError('options must be a dict or None') |
| 62 | mode = mode.removesuffix('b') # handle rb, wb, xb, ab |
| 63 | if mode == 'r': |
| 64 | if level is not None: |
| 65 | raise TypeError('level is illegal in read mode') |
| 66 | self._mode = _MODE_READ |
| 67 | elif mode in {'w', 'a', 'x'}: |
| 68 | if level is not None and not isinstance(level, int): |
| 69 | raise TypeError('level must be int or None') |
| 70 | self._mode = _MODE_WRITE |
| 71 | self._compressor = ZstdCompressor(level=level, options=options, |
| 72 | zstd_dict=zstd_dict) |
| 73 | self._pos = 0 |
| 74 | else: |
| 75 | raise ValueError(f'Invalid mode: {mode!r}') |
| 76 | |
| 77 | if isinstance(file, (str, bytes, PathLike)): |
no outgoing calls
searching dependent graphs…