README.rst 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. ================
  2. python-zstandard
  3. ================
  4. This project provides Python bindings for interfacing with the
  5. `Zstandard <http://www.zstd.net>`_ compression library. A C extension
  6. and CFFI interface are provided.
  7. The primary goal of the project is to provide a rich interface to the
  8. underlying C API through a Pythonic interface while not sacrificing
  9. performance. This means exposing most of the features and flexibility
  10. of the C API while not sacrificing usability or safety that Python provides.
  11. The canonical home for this project lives in a Mercurial repository run by
  12. the author. For convenience, that repository is frequently synchronized to
  13. https://github.com/indygreg/python-zstandard.
  14. | |ci-status|
  15. Requirements
  16. ============
  17. This extension is designed to run with Python 2.7, 3.5, 3.6, 3.7, and 3.8
  18. on common platforms (Linux, Windows, and OS X). On PyPy (both PyPy2 and PyPy3) we support version 6.0.0 and above.
  19. x86 and x86_64 are well-tested on Windows. Only x86_64 is well-tested on Linux and macOS.
  20. Installing
  21. ==========
  22. This package is uploaded to PyPI at https://pypi.python.org/pypi/zstandard.
  23. So, to install this package::
  24. $ pip install zstandard
  25. Binary wheels are made available for some platforms. If you need to
  26. install from a source distribution, all you should need is a working C
  27. compiler and the Python development headers/libraries. On many Linux
  28. distributions, you can install a ``python-dev`` or ``python-devel``
  29. package to provide these dependencies.
  30. Packages are also uploaded to Anaconda Cloud at
  31. https://anaconda.org/indygreg/zstandard. See that URL for how to install
  32. this package with ``conda``.
  33. Legacy Format Support
  34. =====================
  35. To enable legacy zstd format support which is needed to handle files compressed
  36. with zstd < 1.0 you need to provide an installation option::
  37. $ pip install zstandard --install-option="--legacy"
  38. and since pip 7.0 it is possible to have the following line in your
  39. requirements.txt::
  40. zstandard --install-option="--legacy"
  41. Performance
  42. ===========
  43. zstandard is a highly tunable compression algorithm. In its default settings
  44. (compression level 3), it will be faster at compression and decompression and
  45. will have better compression ratios than zlib on most data sets. When tuned
  46. for speed, it approaches lz4's speed and ratios. When tuned for compression
  47. ratio, it approaches lzma ratios and compression speed, but decompression
  48. speed is much faster. See the official zstandard documentation for more.
  49. zstandard and this library support multi-threaded compression. There is a
  50. mechanism to compress large inputs using multiple threads.
  51. The performance of this library is usually very similar to what the zstandard
  52. C API can deliver. Overhead in this library is due to general Python overhead
  53. and can't easily be avoided by *any* zstandard Python binding. This library
  54. exposes multiple APIs for performing compression and decompression so callers
  55. can pick an API suitable for their need. Contrast with the compression
  56. modules in Python's standard library (like ``zlib``), which only offer limited
  57. mechanisms for performing operations. The API flexibility means consumers can
  58. choose to use APIs that facilitate zero copying or minimize Python object
  59. creation and garbage collection overhead.
  60. This library is capable of single-threaded throughputs well over 1 GB/s. For
  61. exact numbers, measure yourself. The source code repository has a ``bench.py``
  62. script that can be used to measure things.
  63. API
  64. ===
  65. To interface with Zstandard, simply import the ``zstandard`` module::
  66. import zstandard
  67. It is a popular convention to alias the module as a different name for
  68. brevity::
  69. import zstandard as zstd
  70. This module attempts to import and use either the C extension or CFFI
  71. implementation. On Python platforms known to support C extensions (like
  72. CPython), it raises an ImportError if the C extension cannot be imported.
  73. On Python platforms known to not support C extensions (like PyPy), it only
  74. attempts to import the CFFI implementation and raises ImportError if that
  75. can't be done. On other platforms, it first tries to import the C extension
  76. then falls back to CFFI if that fails and raises ImportError if CFFI fails.
  77. To change the module import behavior, a ``PYTHON_ZSTANDARD_IMPORT_POLICY``
  78. environment variable can be set. The following values are accepted:
  79. default
  80. The behavior described above.
  81. cffi_fallback
  82. Always try to import the C extension then fall back to CFFI if that
  83. fails.
  84. cext
  85. Only attempt to import the C extension.
  86. cffi
  87. Only attempt to import the CFFI implementation.
  88. In addition, the ``zstandard`` module exports a ``backend`` attribute
  89. containing the string name of the backend being used. It will be one
  90. of ``cext`` or ``cffi`` (for *C extension* and *cffi*, respectively).
  91. The types, functions, and attributes exposed by the ``zstandard`` module
  92. are documented in the sections below.
  93. .. note::
  94. The documentation in this section makes references to various zstd
  95. concepts and functionality. The source repository contains a
  96. ``docs/concepts.rst`` file explaining these in more detail.
  97. ZstdCompressor
  98. --------------
  99. The ``ZstdCompressor`` class provides an interface for performing
  100. compression operations. Each instance is essentially a wrapper around a
  101. ``ZSTD_CCtx`` from the C API.
  102. Each instance is associated with parameters that control compression
  103. behavior. These come from the following named arguments (all optional):
  104. level
  105. Integer compression level. Valid values are between 1 and 22.
  106. dict_data
  107. Compression dictionary to use.
  108. Note: When using dictionary data and ``compress()`` is called multiple
  109. times, the ``ZstdCompressionParameters`` derived from an integer
  110. compression ``level`` and the first compressed data's size will be reused
  111. for all subsequent operations. This may not be desirable if source data
  112. size varies significantly.
  113. compression_params
  114. A ``ZstdCompressionParameters`` instance defining compression settings.
  115. write_checksum
  116. Whether a 4 byte checksum should be written with the compressed data.
  117. Defaults to False. If True, the decompressor can verify that decompressed
  118. data matches the original input data.
  119. write_content_size
  120. Whether the size of the uncompressed data will be written into the
  121. header of compressed data. Defaults to True. The data will only be
  122. written if the compressor knows the size of the input data. This is
  123. often not true for streaming compression.
  124. write_dict_id
  125. Whether to write the dictionary ID into the compressed data.
  126. Defaults to True. The dictionary ID is only written if a dictionary
  127. is being used.
  128. threads
  129. Enables and sets the number of threads to use for multi-threaded compression
  130. operations. Defaults to 0, which means to use single-threaded compression.
  131. Negative values will resolve to the number of logical CPUs in the system.
  132. Read below for more info on multi-threaded compression. This argument only
  133. controls thread count for operations that operate on individual pieces of
  134. data. APIs that spawn multiple threads for working on multiple pieces of
  135. data have their own ``threads`` argument.
  136. ``compression_params`` is mutually exclusive with ``level``, ``write_checksum``,
  137. ``write_content_size``, ``write_dict_id``, and ``threads``.
  138. Unless specified otherwise, assume that no two methods of ``ZstdCompressor``
  139. instances can be called from multiple Python threads simultaneously. In other
  140. words, assume instances are not thread safe unless stated otherwise.
  141. Utility Methods
  142. ^^^^^^^^^^^^^^^
  143. ``frame_progression()`` returns a 3-tuple containing the number of bytes
  144. ingested, consumed, and produced by the current compression operation.
  145. ``memory_size()`` obtains the memory utilization of the underlying zstd
  146. compression context, in bytes.::
  147. cctx = zstd.ZstdCompressor()
  148. memory = cctx.memory_size()
  149. Simple API
  150. ^^^^^^^^^^
  151. ``compress(data)`` compresses and returns data as a one-shot operation.::
  152. cctx = zstd.ZstdCompressor()
  153. compressed = cctx.compress(b'data to compress')
  154. The ``data`` argument can be any object that implements the *buffer protocol*.
  155. Stream Reader API
  156. ^^^^^^^^^^^^^^^^^
  157. ``stream_reader(source)`` can be used to obtain an object conforming to the
  158. ``io.RawIOBase`` interface for reading compressed output as a stream::
  159. with open(path, 'rb') as fh:
  160. cctx = zstd.ZstdCompressor()
  161. reader = cctx.stream_reader(fh)
  162. while True:
  163. chunk = reader.read(16384)
  164. if not chunk:
  165. break
  166. # Do something with compressed chunk.
  167. Instances can also be used as context managers::
  168. with open(path, 'rb') as fh:
  169. with cctx.stream_reader(fh) as reader:
  170. while True:
  171. chunk = reader.read(16384)
  172. if not chunk:
  173. break
  174. # Do something with compressed chunk.
  175. When the context manager exits or ``close()`` is called, the stream is closed,
  176. underlying resources are released, and future operations against the compression
  177. stream will fail.
  178. The ``source`` argument to ``stream_reader()`` can be any object with a
  179. ``read(size)`` method or any object implementing the *buffer protocol*.
  180. ``stream_reader()`` accepts a ``size`` argument specifying how large the input
  181. stream is. This is used to adjust compression parameters so they are
  182. tailored to the source size.::
  183. with open(path, 'rb') as fh:
  184. cctx = zstd.ZstdCompressor()
  185. with cctx.stream_reader(fh, size=os.stat(path).st_size) as reader:
  186. ...
  187. If the ``source`` is a stream, you can specify how large ``read()`` requests
  188. to that stream should be via the ``read_size`` argument. It defaults to
  189. ``zstandard.COMPRESSION_RECOMMENDED_INPUT_SIZE``.::
  190. with open(path, 'rb') as fh:
  191. cctx = zstd.ZstdCompressor()
  192. # Will perform fh.read(8192) when obtaining data to feed into the
  193. # compressor.
  194. with cctx.stream_reader(fh, read_size=8192) as reader:
  195. ...
  196. The stream returned by ``stream_reader()`` is neither writable nor seekable
  197. (even if the underlying source is seekable). ``readline()`` and
  198. ``readlines()`` are not implemented because they don't make sense for
  199. compressed data. ``tell()`` returns the number of compressed bytes
  200. emitted so far.
  201. Streaming Input API
  202. ^^^^^^^^^^^^^^^^^^^
  203. ``stream_writer(fh)`` allows you to *stream* data into a compressor.
  204. Returned instances implement the ``io.RawIOBase`` interface. Only methods
  205. that involve writing will do useful things.
  206. The argument to ``stream_writer()`` must have a ``write(data)`` method. As
  207. compressed data is available, ``write()`` will be called with the compressed
  208. data as its argument. Many common Python types implement ``write()``, including
  209. open file handles and ``io.BytesIO``.
  210. The ``write(data)`` method is used to feed data into the compressor.
  211. The ``flush([flush_mode=FLUSH_BLOCK])`` method can be called to evict whatever
  212. data remains within the compressor's internal state into the output object. This
  213. may result in 0 or more ``write()`` calls to the output object. This method
  214. accepts an optional ``flush_mode`` argument to control the flushing behavior.
  215. Its value can be any of the ``FLUSH_*`` constants.
  216. Both ``write()`` and ``flush()`` return the number of bytes written to the
  217. object's ``write()``. In many cases, small inputs do not accumulate enough
  218. data to cause a write and ``write()`` will return ``0``.
  219. Calling ``close()`` will mark the stream as closed and subsequent I/O
  220. operations will raise ``ValueError`` (per the documented behavior of
  221. ``io.RawIOBase``). ``close()`` will also call ``close()`` on the underlying
  222. stream if such a method exists.
  223. Typically usage is as follows::
  224. cctx = zstd.ZstdCompressor(level=10)
  225. compressor = cctx.stream_writer(fh)
  226. compressor.write(b'chunk 0\n')
  227. compressor.write(b'chunk 1\n')
  228. compressor.flush()
  229. # Receiver will be able to decode ``chunk 0\nchunk 1\n`` at this point.
  230. # Receiver is also expecting more data in the zstd *frame*.
  231. compressor.write(b'chunk 2\n')
  232. compressor.flush(zstd.FLUSH_FRAME)
  233. # Receiver will be able to decode ``chunk 0\nchunk 1\nchunk 2``.
  234. # Receiver is expecting no more data, as the zstd frame is closed.
  235. # Any future calls to ``write()`` at this point will construct a new
  236. # zstd frame.
  237. Instances can be used as context managers. Exiting the context manager is
  238. the equivalent of calling ``close()``, which is equivalent to calling
  239. ``flush(zstd.FLUSH_FRAME)``::
  240. cctx = zstd.ZstdCompressor(level=10)
  241. with cctx.stream_writer(fh) as compressor:
  242. compressor.write(b'chunk 0')
  243. compressor.write(b'chunk 1')
  244. ...
  245. .. important::
  246. If ``flush(FLUSH_FRAME)`` is not called, emitted data doesn't constitute
  247. a full zstd *frame* and consumers of this data may complain about malformed
  248. input. It is recommended to use instances as a context manager to ensure
  249. *frames* are properly finished.
  250. If the size of the data being fed to this streaming compressor is known,
  251. you can declare it before compression begins::
  252. cctx = zstd.ZstdCompressor()
  253. with cctx.stream_writer(fh, size=data_len) as compressor:
  254. compressor.write(chunk0)
  255. compressor.write(chunk1)
  256. ...
  257. Declaring the size of the source data allows compression parameters to
  258. be tuned. And if ``write_content_size`` is used, it also results in the
  259. content size being written into the frame header of the output data.
  260. The size of chunks being ``write()`` to the destination can be specified::
  261. cctx = zstd.ZstdCompressor()
  262. with cctx.stream_writer(fh, write_size=32768) as compressor:
  263. ...
  264. To see how much memory is being used by the streaming compressor::
  265. cctx = zstd.ZstdCompressor()
  266. with cctx.stream_writer(fh) as compressor:
  267. ...
  268. byte_size = compressor.memory_size()
  269. Thte total number of bytes written so far are exposed via ``tell()``::
  270. cctx = zstd.ZstdCompressor()
  271. with cctx.stream_writer(fh) as compressor:
  272. ...
  273. total_written = compressor.tell()
  274. ``stream_writer()`` accepts a ``write_return_read`` boolean argument to control
  275. the return value of ``write()``. When ``False`` (the default), ``write()`` returns
  276. the number of bytes that were ``write()``en to the underlying object. When
  277. ``True``, ``write()`` returns the number of bytes read from the input that
  278. were subsequently written to the compressor. ``True`` is the *proper* behavior
  279. for ``write()`` as specified by the ``io.RawIOBase`` interface and will become
  280. the default value in a future release.
  281. Streaming Output API
  282. ^^^^^^^^^^^^^^^^^^^^
  283. ``read_to_iter(reader)`` provides a mechanism to stream data out of a
  284. compressor as an iterator of data chunks.::
  285. cctx = zstd.ZstdCompressor()
  286. for chunk in cctx.read_to_iter(fh):
  287. # Do something with emitted data.
  288. ``read_to_iter()`` accepts an object that has a ``read(size)`` method or
  289. conforms to the buffer protocol.
  290. Uncompressed data is fetched from the source either by calling ``read(size)``
  291. or by fetching a slice of data from the object directly (in the case where
  292. the buffer protocol is being used). The returned iterator consists of chunks
  293. of compressed data.
  294. If reading from the source via ``read()``, ``read()`` will be called until
  295. it raises or returns an empty bytes (``b''``). It is perfectly valid for
  296. the source to deliver fewer bytes than were what requested by ``read(size)``.
  297. Like ``stream_writer()``, ``read_to_iter()`` also accepts a ``size`` argument
  298. declaring the size of the input stream::
  299. cctx = zstd.ZstdCompressor()
  300. for chunk in cctx.read_to_iter(fh, size=some_int):
  301. pass
  302. You can also control the size that data is ``read()`` from the source and
  303. the ideal size of output chunks::
  304. cctx = zstd.ZstdCompressor()
  305. for chunk in cctx.read_to_iter(fh, read_size=16384, write_size=8192):
  306. pass
  307. Unlike ``stream_writer()``, ``read_to_iter()`` does not give direct control
  308. over the sizes of chunks fed into the compressor. Instead, chunk sizes will
  309. be whatever the object being read from delivers. These will often be of a
  310. uniform size.
  311. Stream Copying API
  312. ^^^^^^^^^^^^^^^^^^
  313. ``copy_stream(ifh, ofh)`` can be used to copy data between 2 streams while
  314. compressing it.::
  315. cctx = zstd.ZstdCompressor()
  316. cctx.copy_stream(ifh, ofh)
  317. For example, say you wish to compress a file::
  318. cctx = zstd.ZstdCompressor()
  319. with open(input_path, 'rb') as ifh, open(output_path, 'wb') as ofh:
  320. cctx.copy_stream(ifh, ofh)
  321. It is also possible to declare the size of the source stream::
  322. cctx = zstd.ZstdCompressor()
  323. cctx.copy_stream(ifh, ofh, size=len_of_input)
  324. You can also specify how large the chunks that are ``read()`` and ``write()``
  325. from and to the streams::
  326. cctx = zstd.ZstdCompressor()
  327. cctx.copy_stream(ifh, ofh, read_size=32768, write_size=16384)
  328. The stream copier returns a 2-tuple of bytes read and written::
  329. cctx = zstd.ZstdCompressor()
  330. read_count, write_count = cctx.copy_stream(ifh, ofh)
  331. Compressor API
  332. ^^^^^^^^^^^^^^
  333. ``compressobj()`` returns an object that exposes ``compress(data)`` and
  334. ``flush()`` methods. Each returns compressed data or an empty bytes.
  335. The purpose of ``compressobj()`` is to provide an API-compatible interface
  336. with ``zlib.compressobj``, ``bz2.BZ2Compressor``, etc. This allows callers to
  337. swap in different compressor objects while using the same API.
  338. ``flush()`` accepts an optional argument indicating how to end the stream.
  339. ``zstd.COMPRESSOBJ_FLUSH_FINISH`` (the default) ends the compression stream.
  340. Once this type of flush is performed, ``compress()`` and ``flush()`` can
  341. no longer be called. This type of flush **must** be called to end the
  342. compression context. If not called, returned data may be incomplete.
  343. A ``zstd.COMPRESSOBJ_FLUSH_BLOCK`` argument to ``flush()`` will flush a
  344. zstd block. Flushes of this type can be performed multiple times. The next
  345. call to ``compress()`` will begin a new zstd block.
  346. Here is how this API should be used::
  347. cctx = zstd.ZstdCompressor()
  348. cobj = cctx.compressobj()
  349. data = cobj.compress(b'raw input 0')
  350. data = cobj.compress(b'raw input 1')
  351. data = cobj.flush()
  352. Or to flush blocks::
  353. cctx.zstd.ZstdCompressor()
  354. cobj = cctx.compressobj()
  355. data = cobj.compress(b'chunk in first block')
  356. data = cobj.flush(zstd.COMPRESSOBJ_FLUSH_BLOCK)
  357. data = cobj.compress(b'chunk in second block')
  358. data = cobj.flush()
  359. For best performance results, keep input chunks under 256KB. This avoids
  360. extra allocations for a large output object.
  361. It is possible to declare the input size of the data that will be fed into
  362. the compressor::
  363. cctx = zstd.ZstdCompressor()
  364. cobj = cctx.compressobj(size=6)
  365. data = cobj.compress(b'foobar')
  366. data = cobj.flush()
  367. Chunker API
  368. ^^^^^^^^^^^
  369. ``chunker(size=None, chunk_size=COMPRESSION_RECOMMENDED_OUTPUT_SIZE)`` returns
  370. an object that can be used to iteratively feed chunks of data into a compressor
  371. and produce output chunks of a uniform size.
  372. The object returned by ``chunker()`` exposes the following methods:
  373. ``compress(data)``
  374. Feeds new input data into the compressor.
  375. ``flush()``
  376. Flushes all data currently in the compressor.
  377. ``finish()``
  378. Signals the end of input data. No new data can be compressed after this
  379. method is called.
  380. ``compress()``, ``flush()``, and ``finish()`` all return an iterator of
  381. ``bytes`` instances holding compressed data. The iterator may be empty. Callers
  382. MUST iterate through all elements of the returned iterator before performing
  383. another operation on the object.
  384. All chunks emitted by ``compress()`` will have a length of ``chunk_size``.
  385. ``flush()`` and ``finish()`` may return a final chunk smaller than
  386. ``chunk_size``.
  387. Here is how the API should be used::
  388. cctx = zstd.ZstdCompressor()
  389. chunker = cctx.chunker(chunk_size=32768)
  390. with open(path, 'rb') as fh:
  391. while True:
  392. in_chunk = fh.read(32768)
  393. if not in_chunk:
  394. break
  395. for out_chunk in chunker.compress(in_chunk):
  396. # Do something with output chunk of size 32768.
  397. for out_chunk in chunker.finish():
  398. # Do something with output chunks that finalize the zstd frame.
  399. The ``chunker()`` API is often a better alternative to ``compressobj()``.
  400. ``compressobj()`` will emit output data as it is available. This results in a
  401. *stream* of output chunks of varying sizes. The consistency of the output chunk
  402. size with ``chunker()`` is more appropriate for many usages, such as sending
  403. compressed data to a socket.
  404. ``compressobj()`` may also perform extra memory reallocations in order to
  405. dynamically adjust the sizes of the output chunks. Since ``chunker()`` output
  406. chunks are all the same size (except for flushed or final chunks), there is
  407. less memory allocation overhead.
  408. Batch Compression API
  409. ^^^^^^^^^^^^^^^^^^^^^
  410. (Experimental. Not yet supported in CFFI bindings.)
  411. ``multi_compress_to_buffer(data, [threads=0])`` performs compression of multiple
  412. inputs as a single operation.
  413. Data to be compressed can be passed as a ``BufferWithSegmentsCollection``, a
  414. ``BufferWithSegments``, or a list containing byte like objects. Each element of
  415. the container will be compressed individually using the configured parameters
  416. on the ``ZstdCompressor`` instance.
  417. The ``threads`` argument controls how many threads to use for compression. The
  418. default is ``0`` which means to use a single thread. Negative values use the
  419. number of logical CPUs in the machine.
  420. The function returns a ``BufferWithSegmentsCollection``. This type represents
  421. N discrete memory allocations, eaching holding 1 or more compressed frames.
  422. Output data is written to shared memory buffers. This means that unlike
  423. regular Python objects, a reference to *any* object within the collection
  424. keeps the shared buffer and therefore memory backing it alive. This can have
  425. undesirable effects on process memory usage.
  426. The API and behavior of this function is experimental and will likely change.
  427. Known deficiencies include:
  428. * If asked to use multiple threads, it will always spawn that many threads,
  429. even if the input is too small to use them. It should automatically lower
  430. the thread count when the extra threads would just add overhead.
  431. * The buffer allocation strategy is fixed. There is room to make it dynamic,
  432. perhaps even to allow one output buffer per input, facilitating a variation
  433. of the API to return a list without the adverse effects of shared memory
  434. buffers.
  435. ZstdDecompressor
  436. ----------------
  437. The ``ZstdDecompressor`` class provides an interface for performing
  438. decompression. It is effectively a wrapper around the ``ZSTD_DCtx`` type from
  439. the C API.
  440. Each instance is associated with parameters that control decompression. These
  441. come from the following named arguments (all optional):
  442. dict_data
  443. Compression dictionary to use.
  444. max_window_size
  445. Sets an uppet limit on the window size for decompression operations in
  446. kibibytes. This setting can be used to prevent large memory allocations
  447. for inputs using large compression windows.
  448. format
  449. Set the format of data for the decoder. By default, this is
  450. ``zstd.FORMAT_ZSTD1``. It can be set to ``zstd.FORMAT_ZSTD1_MAGICLESS`` to
  451. allow decoding frames without the 4 byte magic header. Not all decompression
  452. APIs support this mode.
  453. The interface of this class is very similar to ``ZstdCompressor`` (by design).
  454. Unless specified otherwise, assume that no two methods of ``ZstdDecompressor``
  455. instances can be called from multiple Python threads simultaneously. In other
  456. words, assume instances are not thread safe unless stated otherwise.
  457. Utility Methods
  458. ^^^^^^^^^^^^^^^
  459. ``memory_size()`` obtains the size of the underlying zstd decompression context,
  460. in bytes.::
  461. dctx = zstd.ZstdDecompressor()
  462. size = dctx.memory_size()
  463. Simple API
  464. ^^^^^^^^^^
  465. ``decompress(data)`` can be used to decompress an entire compressed zstd
  466. frame in a single operation.::
  467. dctx = zstd.ZstdDecompressor()
  468. decompressed = dctx.decompress(data)
  469. By default, ``decompress(data)`` will only work on data written with the content
  470. size encoded in its header (this is the default behavior of
  471. ``ZstdCompressor().compress()`` but may not be true for streaming compression). If
  472. compressed data without an embedded content size is seen, ``zstd.ZstdError`` will
  473. be raised.
  474. If the compressed data doesn't have its content size embedded within it,
  475. decompression can be attempted by specifying the ``max_output_size``
  476. argument.::
  477. dctx = zstd.ZstdDecompressor()
  478. uncompressed = dctx.decompress(data, max_output_size=1048576)
  479. Ideally, ``max_output_size`` will be identical to the decompressed output
  480. size.
  481. If ``max_output_size`` is too small to hold the decompressed data,
  482. ``zstd.ZstdError`` will be raised.
  483. If ``max_output_size`` is larger than the decompressed data, the allocated
  484. output buffer will be resized to only use the space required.
  485. Please note that an allocation of the requested ``max_output_size`` will be
  486. performed every time the method is called. Setting to a very large value could
  487. result in a lot of work for the memory allocator and may result in
  488. ``MemoryError`` being raised if the allocation fails.
  489. .. important::
  490. If the exact size of decompressed data is unknown (not passed in explicitly
  491. and not stored in the zstandard frame), for performance reasons it is
  492. encouraged to use a streaming API.
  493. Stream Reader API
  494. ^^^^^^^^^^^^^^^^^
  495. ``stream_reader(source)`` can be used to obtain an object conforming to the
  496. ``io.RawIOBase`` interface for reading decompressed output as a stream::
  497. with open(path, 'rb') as fh:
  498. dctx = zstd.ZstdDecompressor()
  499. reader = dctx.stream_reader(fh)
  500. while True:
  501. chunk = reader.read(16384)
  502. if not chunk:
  503. break
  504. # Do something with decompressed chunk.
  505. The stream can also be used as a context manager::
  506. with open(path, 'rb') as fh:
  507. dctx = zstd.ZstdDecompressor()
  508. with dctx.stream_reader(fh) as reader:
  509. ...
  510. When used as a context manager, the stream is closed and the underlying
  511. resources are released when the context manager exits. Future operations against
  512. the stream will fail.
  513. The ``source`` argument to ``stream_reader()`` can be any object with a
  514. ``read(size)`` method or any object implementing the *buffer protocol*.
  515. If the ``source`` is a stream, you can specify how large ``read()`` requests
  516. to that stream should be via the ``read_size`` argument. It defaults to
  517. ``zstandard.DECOMPRESSION_RECOMMENDED_INPUT_SIZE``.::
  518. with open(path, 'rb') as fh:
  519. dctx = zstd.ZstdDecompressor()
  520. # Will perform fh.read(8192) when obtaining data for the decompressor.
  521. with dctx.stream_reader(fh, read_size=8192) as reader:
  522. ...
  523. The stream returned by ``stream_reader()`` is not writable.
  524. The stream returned by ``stream_reader()`` is *partially* seekable.
  525. Absolute and relative positions (``SEEK_SET`` and ``SEEK_CUR``) forward
  526. of the current position are allowed. Offsets behind the current read
  527. position and offsets relative to the end of stream are not allowed and
  528. will raise ``ValueError`` if attempted.
  529. ``tell()`` returns the number of decompressed bytes read so far.
  530. Not all I/O methods are implemented. Notably missing is support for
  531. ``readline()``, ``readlines()``, and linewise iteration support. This is
  532. because streams operate on binary data - not text data. If you want to
  533. convert decompressed output to text, you can chain an ``io.TextIOWrapper``
  534. to the stream::
  535. with open(path, 'rb') as fh:
  536. dctx = zstd.ZstdDecompressor()
  537. stream_reader = dctx.stream_reader(fh)
  538. text_stream = io.TextIOWrapper(stream_reader, encoding='utf-8')
  539. for line in text_stream:
  540. ...
  541. The ``read_across_frames`` argument to ``stream_reader()`` controls the
  542. behavior of read operations when the end of a zstd *frame* is encountered.
  543. When ``False`` (the default), a read will complete when the end of a
  544. zstd *frame* is encountered. When ``True``, a read can potentially
  545. return data spanning multiple zstd *frames*.
  546. Streaming Input API
  547. ^^^^^^^^^^^^^^^^^^^
  548. ``stream_writer(fh)`` allows you to *stream* data into a decompressor.
  549. Returned instances implement the ``io.RawIOBase`` interface. Only methods
  550. that involve writing will do useful things.
  551. The argument to ``stream_writer()`` is typically an object that also implements
  552. ``io.RawIOBase``. But any object with a ``write(data)`` method will work. Many
  553. common Python types conform to this interface, including open file handles
  554. and ``io.BytesIO``.
  555. Behavior is similar to ``ZstdCompressor.stream_writer()``: compressed data
  556. is sent to the decompressor by calling ``write(data)`` and decompressed
  557. output is written to the underlying stream by calling its ``write(data)``
  558. method.::
  559. dctx = zstd.ZstdDecompressor()
  560. decompressor = dctx.stream_writer(fh)
  561. decompressor.write(compressed_data)
  562. ...
  563. Calls to ``write()`` will return the number of bytes written to the output
  564. object. Not all inputs will result in bytes being written, so return values
  565. of ``0`` are possible.
  566. Like the ``stream_writer()`` compressor, instances can be used as context
  567. managers. However, context managers add no extra special behavior and offer
  568. little to no benefit to being used.
  569. Calling ``close()`` will mark the stream as closed and subsequent I/O operations
  570. will raise ``ValueError`` (per the documented behavior of ``io.RawIOBase``).
  571. ``close()`` will also call ``close()`` on the underlying stream if such a
  572. method exists.
  573. The size of chunks being ``write()`` to the destination can be specified::
  574. dctx = zstd.ZstdDecompressor()
  575. with dctx.stream_writer(fh, write_size=16384) as decompressor:
  576. pass
  577. You can see how much memory is being used by the decompressor::
  578. dctx = zstd.ZstdDecompressor()
  579. with dctx.stream_writer(fh) as decompressor:
  580. byte_size = decompressor.memory_size()
  581. ``stream_writer()`` accepts a ``write_return_read`` boolean argument to control
  582. the return value of ``write()``. When ``False`` (the default)``, ``write()``
  583. returns the number of bytes that were ``write()``en to the underlying stream.
  584. When ``True``, ``write()`` returns the number of bytes read from the input.
  585. ``True`` is the *proper* behavior for ``write()`` as specified by the
  586. ``io.RawIOBase`` interface and will become the default in a future release.
  587. Streaming Output API
  588. ^^^^^^^^^^^^^^^^^^^^
  589. ``read_to_iter(fh)`` provides a mechanism to stream decompressed data out of a
  590. compressed source as an iterator of data chunks.::
  591. dctx = zstd.ZstdDecompressor()
  592. for chunk in dctx.read_to_iter(fh):
  593. # Do something with original data.
  594. ``read_to_iter()`` accepts an object with a ``read(size)`` method that will
  595. return compressed bytes or an object conforming to the buffer protocol that
  596. can expose its data as a contiguous range of bytes.
  597. ``read_to_iter()`` returns an iterator whose elements are chunks of the
  598. decompressed data.
  599. The size of requested ``read()`` from the source can be specified::
  600. dctx = zstd.ZstdDecompressor()
  601. for chunk in dctx.read_to_iter(fh, read_size=16384):
  602. pass
  603. It is also possible to skip leading bytes in the input data::
  604. dctx = zstd.ZstdDecompressor()
  605. for chunk in dctx.read_to_iter(fh, skip_bytes=1):
  606. pass
  607. .. tip::
  608. Skipping leading bytes is useful if the source data contains extra
  609. *header* data. Traditionally, you would need to create a slice or
  610. ``memoryview`` of the data you want to decompress. This would create
  611. overhead. It is more efficient to pass the offset into this API.
  612. Similarly to ``ZstdCompressor.read_to_iter()``, the consumer of the iterator
  613. controls when data is decompressed. If the iterator isn't consumed,
  614. decompression is put on hold.
  615. When ``read_to_iter()`` is passed an object conforming to the buffer protocol,
  616. the behavior may seem similar to what occurs when the simple decompression
  617. API is used. However, this API works when the decompressed size is unknown.
  618. Furthermore, if feeding large inputs, the decompressor will work in chunks
  619. instead of performing a single operation.
  620. Stream Copying API
  621. ^^^^^^^^^^^^^^^^^^
  622. ``copy_stream(ifh, ofh)`` can be used to copy data across 2 streams while
  623. performing decompression.::
  624. dctx = zstd.ZstdDecompressor()
  625. dctx.copy_stream(ifh, ofh)
  626. e.g. to decompress a file to another file::
  627. dctx = zstd.ZstdDecompressor()
  628. with open(input_path, 'rb') as ifh, open(output_path, 'wb') as ofh:
  629. dctx.copy_stream(ifh, ofh)
  630. The size of chunks being ``read()`` and ``write()`` from and to the streams
  631. can be specified::
  632. dctx = zstd.ZstdDecompressor()
  633. dctx.copy_stream(ifh, ofh, read_size=8192, write_size=16384)
  634. Decompressor API
  635. ^^^^^^^^^^^^^^^^
  636. ``decompressobj()`` returns an object that exposes a ``decompress(data)``
  637. method. Compressed data chunks are fed into ``decompress(data)`` and
  638. uncompressed output (or an empty bytes) is returned. Output from subsequent
  639. calls needs to be concatenated to reassemble the full decompressed byte
  640. sequence.
  641. The purpose of ``decompressobj()`` is to provide an API-compatible interface
  642. with ``zlib.decompressobj`` and ``bz2.BZ2Decompressor``. This allows callers
  643. to swap in different decompressor objects while using the same API.
  644. Each object is single use: once an input frame is decoded, ``decompress()``
  645. can no longer be called.
  646. Here is how this API should be used::
  647. dctx = zstd.ZstdDecompressor()
  648. dobj = dctx.decompressobj()
  649. data = dobj.decompress(compressed_chunk_0)
  650. data = dobj.decompress(compressed_chunk_1)
  651. By default, calls to ``decompress()`` write output data in chunks of size
  652. ``DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE``. These chunks are concatenated
  653. before being returned to the caller. It is possible to define the size of
  654. these temporary chunks by passing ``write_size`` to ``decompressobj()``::
  655. dctx = zstd.ZstdDecompressor()
  656. dobj = dctx.decompressobj(write_size=1048576)
  657. .. note::
  658. Because calls to ``decompress()`` may need to perform multiple
  659. memory (re)allocations, this streaming decompression API isn't as
  660. efficient as other APIs.
  661. For compatibility with the standard library APIs, instances expose a
  662. ``flush([length=None])`` method. This method no-ops and has no meaningful
  663. side-effects, making it safe to call any time.
  664. Batch Decompression API
  665. ^^^^^^^^^^^^^^^^^^^^^^^
  666. (Experimental. Not yet supported in CFFI bindings.)
  667. ``multi_decompress_to_buffer()`` performs decompression of multiple
  668. frames as a single operation and returns a ``BufferWithSegmentsCollection``
  669. containing decompressed data for all inputs.
  670. Compressed frames can be passed to the function as a ``BufferWithSegments``,
  671. a ``BufferWithSegmentsCollection``, or as a list containing objects that
  672. conform to the buffer protocol. For best performance, pass a
  673. ``BufferWithSegmentsCollection`` or a ``BufferWithSegments``, as
  674. minimal input validation will be done for that type. If calling from
  675. Python (as opposed to C), constructing one of these instances may add
  676. overhead cancelling out the performance overhead of validation for list
  677. inputs.::
  678. dctx = zstd.ZstdDecompressor()
  679. results = dctx.multi_decompress_to_buffer([b'...', b'...'])
  680. The decompressed size of each frame MUST be discoverable. It can either be
  681. embedded within the zstd frame (``write_content_size=True`` argument to
  682. ``ZstdCompressor``) or passed in via the ``decompressed_sizes`` argument.
  683. The ``decompressed_sizes`` argument is an object conforming to the buffer
  684. protocol which holds an array of 64-bit unsigned integers in the machine's
  685. native format defining the decompressed sizes of each frame. If this argument
  686. is passed, it avoids having to scan each frame for its decompressed size.
  687. This frame scanning can add noticeable overhead in some scenarios.::
  688. frames = [...]
  689. sizes = struct.pack('=QQQQ', len0, len1, len2, len3)
  690. dctx = zstd.ZstdDecompressor()
  691. results = dctx.multi_decompress_to_buffer(frames, decompressed_sizes=sizes)
  692. The ``threads`` argument controls the number of threads to use to perform
  693. decompression operations. The default (``0``) or the value ``1`` means to
  694. use a single thread. Negative values use the number of logical CPUs in the
  695. machine.
  696. .. note::
  697. It is possible to pass a ``mmap.mmap()`` instance into this function by
  698. wrapping it with a ``BufferWithSegments`` instance (which will define the
  699. offsets of frames within the memory mapped region).
  700. This function is logically equivalent to performing ``dctx.decompress()``
  701. on each input frame and returning the result.
  702. This function exists to perform decompression on multiple frames as fast
  703. as possible by having as little overhead as possible. Since decompression is
  704. performed as a single operation and since the decompressed output is stored in
  705. a single buffer, extra memory allocations, Python objects, and Python function
  706. calls are avoided. This is ideal for scenarios where callers know up front that
  707. they need to access data for multiple frames, such as when *delta chains* are
  708. being used.
  709. Currently, the implementation always spawns multiple threads when requested,
  710. even if the amount of work to do is small. In the future, it will be smarter
  711. about avoiding threads and their associated overhead when the amount of
  712. work to do is small.
  713. Prefix Dictionary Chain Decompression
  714. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  715. ``decompress_content_dict_chain(frames)`` performs decompression of a list of
  716. zstd frames produced using chained *prefix* dictionary compression. Such
  717. a list of frames is produced by compressing discrete inputs where each
  718. non-initial input is compressed with a *prefix* dictionary consisting of the
  719. content of the previous input.
  720. For example, say you have the following inputs::
  721. inputs = [b'input 1', b'input 2', b'input 3']
  722. The zstd frame chain consists of:
  723. 1. ``b'input 1'`` compressed in standalone/discrete mode
  724. 2. ``b'input 2'`` compressed using ``b'input 1'`` as a *prefix* dictionary
  725. 3. ``b'input 3'`` compressed using ``b'input 2'`` as a *prefix* dictionary
  726. Each zstd frame **must** have the content size written.
  727. The following Python code can be used to produce a *prefix dictionary chain*::
  728. def make_chain(inputs):
  729. frames = []
  730. # First frame is compressed in standalone/discrete mode.
  731. zctx = zstd.ZstdCompressor()
  732. frames.append(zctx.compress(inputs[0]))
  733. # Subsequent frames use the previous fulltext as a prefix dictionary
  734. for i, raw in enumerate(inputs[1:]):
  735. dict_data = zstd.ZstdCompressionDict(
  736. inputs[i], dict_type=zstd.DICT_TYPE_RAWCONTENT)
  737. zctx = zstd.ZstdCompressor(dict_data=dict_data)
  738. frames.append(zctx.compress(raw))
  739. return frames
  740. ``decompress_content_dict_chain()`` returns the uncompressed data of the last
  741. element in the input chain.
  742. .. note::
  743. It is possible to implement *prefix dictionary chain* decompression
  744. on top of other APIs. However, this function will likely be faster -
  745. especially for long input chains - as it avoids the overhead of instantiating
  746. and passing around intermediate objects between C and Python.
  747. Multi-Threaded Compression
  748. --------------------------
  749. ``ZstdCompressor`` accepts a ``threads`` argument that controls the number
  750. of threads to use for compression. The way this works is that input is split
  751. into segments and each segment is fed into a worker pool for compression. Once
  752. a segment is compressed, it is flushed/appended to the output.
  753. .. note::
  754. These threads are created at the C layer and are not Python threads. So they
  755. work outside the GIL. It is therefore possible to CPU saturate multiple cores
  756. from Python.
  757. The segment size for multi-threaded compression is chosen from the window size
  758. of the compressor. This is derived from the ``window_log`` attribute of a
  759. ``ZstdCompressionParameters`` instance. By default, segment sizes are in the 1+MB
  760. range.
  761. If multi-threaded compression is requested and the input is smaller than the
  762. configured segment size, only a single compression thread will be used. If the
  763. input is smaller than the segment size multiplied by the thread pool size or
  764. if data cannot be delivered to the compressor fast enough, not all requested
  765. compressor threads may be active simultaneously.
  766. Compared to non-multi-threaded compression, multi-threaded compression has
  767. higher per-operation overhead. This includes extra memory operations,
  768. thread creation, lock acquisition, etc.
  769. Due to the nature of multi-threaded compression using *N* compression
  770. *states*, the output from multi-threaded compression will likely be larger
  771. than non-multi-threaded compression. The difference is usually small. But
  772. there is a CPU/wall time versus size trade off that may warrant investigation.
  773. Output from multi-threaded compression does not require any special handling
  774. on the decompression side. To the decompressor, data generated with single
  775. threaded compressor looks the same as data generated by a multi-threaded
  776. compressor and does not require any special handling or additional resource
  777. requirements.
  778. Dictionary Creation and Management
  779. ----------------------------------
  780. Compression dictionaries are represented with the ``ZstdCompressionDict`` type.
  781. Instances can be constructed from bytes::
  782. dict_data = zstd.ZstdCompressionDict(data)
  783. It is possible to construct a dictionary from *any* data. If the data doesn't
  784. begin with a magic header, it will be treated as a *prefix* dictionary.
  785. *Prefix* dictionaries allow compression operations to reference raw data
  786. within the dictionary.
  787. It is possible to force the use of *prefix* dictionaries or to require a
  788. dictionary header:
  789. dict_data = zstd.ZstdCompressionDict(data,
  790. dict_type=zstd.DICT_TYPE_RAWCONTENT)
  791. dict_data = zstd.ZstdCompressionDict(data,
  792. dict_type=zstd.DICT_TYPE_FULLDICT)
  793. You can see how many bytes are in the dictionary by calling ``len()``::
  794. dict_data = zstd.train_dictionary(size, samples)
  795. dict_size = len(dict_data) # will not be larger than ``size``
  796. Once you have a dictionary, you can pass it to the objects performing
  797. compression and decompression::
  798. dict_data = zstd.train_dictionary(131072, samples)
  799. cctx = zstd.ZstdCompressor(dict_data=dict_data)
  800. for source_data in input_data:
  801. compressed = cctx.compress(source_data)
  802. # Do something with compressed data.
  803. dctx = zstd.ZstdDecompressor(dict_data=dict_data)
  804. for compressed_data in input_data:
  805. buffer = io.BytesIO()
  806. with dctx.stream_writer(buffer) as decompressor:
  807. decompressor.write(compressed_data)
  808. # Do something with raw data in ``buffer``.
  809. Dictionaries have unique integer IDs. You can retrieve this ID via::
  810. dict_id = zstd.dictionary_id(dict_data)
  811. You can obtain the raw data in the dict (useful for persisting and constructing
  812. a ``ZstdCompressionDict`` later) via ``as_bytes()``::
  813. dict_data = zstd.train_dictionary(size, samples)
  814. raw_data = dict_data.as_bytes()
  815. By default, when a ``ZstdCompressionDict`` is *attached* to a
  816. ``ZstdCompressor``, each ``ZstdCompressor`` performs work to prepare the
  817. dictionary for use. This is fine if only 1 compression operation is being
  818. performed or if the ``ZstdCompressor`` is being reused for multiple operations.
  819. But if multiple ``ZstdCompressor`` instances are being used with the dictionary,
  820. this can add overhead.
  821. It is possible to *precompute* the dictionary so it can readily be consumed
  822. by multiple ``ZstdCompressor`` instances::
  823. d = zstd.ZstdCompressionDict(data)
  824. # Precompute for compression level 3.
  825. d.precompute_compress(level=3)
  826. # Precompute with specific compression parameters.
  827. params = zstd.ZstdCompressionParameters(...)
  828. d.precompute_compress(compression_params=params)
  829. .. note::
  830. When a dictionary is precomputed, the compression parameters used to
  831. precompute the dictionary overwrite some of the compression parameters
  832. specified to ``ZstdCompressor.__init__``.
  833. Training Dictionaries
  834. ^^^^^^^^^^^^^^^^^^^^^
  835. Unless using *prefix* dictionaries, dictionary data is produced by *training*
  836. on existing data::
  837. dict_data = zstd.train_dictionary(size, samples)
  838. This takes a target dictionary size and list of bytes instances and creates and
  839. returns a ``ZstdCompressionDict``.
  840. The dictionary training mechanism is known as *cover*. More details about it are
  841. available in the paper *Effective Construction of Relative Lempel-Ziv
  842. Dictionaries* (authors: Liao, Petri, Moffat, Wirth).
  843. The cover algorithm takes parameters ``k` and ``d``. These are the
  844. *segment size* and *dmer size*, respectively. The returned dictionary
  845. instance created by this function has ``k`` and ``d`` attributes
  846. containing the values for these parameters. If a ``ZstdCompressionDict``
  847. is constructed from raw bytes data (a content-only dictionary), the
  848. ``k`` and ``d`` attributes will be ``0``.
  849. The segment and dmer size parameters to the cover algorithm can either be
  850. specified manually or ``train_dictionary()`` can try multiple values
  851. and pick the best one, where *best* means the smallest compressed data size.
  852. This later mode is called *optimization* mode.
  853. If none of ``k``, ``d``, ``steps``, ``threads``, ``level``, ``notifications``,
  854. or ``dict_id`` (basically anything from the underlying ``ZDICT_cover_params_t``
  855. struct) are defined, *optimization* mode is used with default parameter
  856. values.
  857. If ``steps`` or ``threads`` are defined, then *optimization* mode is engaged
  858. with explicit control over those parameters. Specifying ``threads=0`` or
  859. ``threads=1`` can be used to engage *optimization* mode if other parameters
  860. are not defined.
  861. Otherwise, non-*optimization* mode is used with the parameters specified.
  862. This function takes the following arguments:
  863. dict_size
  864. Target size in bytes of the dictionary to generate.
  865. samples
  866. A list of bytes holding samples the dictionary will be trained from.
  867. k
  868. Parameter to cover algorithm defining the segment size. A reasonable range
  869. is [16, 2048+].
  870. d
  871. Parameter to cover algorithm defining the dmer size. A reasonable range is
  872. [6, 16]. ``d`` must be less than or equal to ``k``.
  873. dict_id
  874. Integer dictionary ID for the produced dictionary. Default is 0, which uses
  875. a random value.
  876. steps
  877. Number of steps through ``k`` values to perform when trying parameter
  878. variations.
  879. threads
  880. Number of threads to use when trying parameter variations. Default is 0,
  881. which means to use a single thread. A negative value can be specified to
  882. use as many threads as there are detected logical CPUs.
  883. level
  884. Integer target compression level when trying parameter variations.
  885. notifications
  886. Controls writing of informational messages to ``stderr``. ``0`` (the
  887. default) means to write nothing. ``1`` writes errors. ``2`` writes
  888. progression info. ``3`` writes more details. And ``4`` writes all info.
  889. Explicit Compression Parameters
  890. -------------------------------
  891. Zstandard offers a high-level *compression level* that maps to lower-level
  892. compression parameters. For many consumers, this numeric level is the only
  893. compression setting you'll need to touch.
  894. But for advanced use cases, it might be desirable to tweak these lower-level
  895. settings.
  896. The ``ZstdCompressionParameters`` type represents these low-level compression
  897. settings.
  898. Instances of this type can be constructed from a myriad of keyword arguments
  899. (defined below) for complete low-level control over each adjustable
  900. compression setting.
  901. From a higher level, one can construct a ``ZstdCompressionParameters`` instance
  902. given a desired compression level and target input and dictionary size
  903. using ``ZstdCompressionParameters.from_level()``. e.g.::
  904. # Derive compression settings for compression level 7.
  905. params = zstd.ZstdCompressionParameters.from_level(7)
  906. # With an input size of 1MB
  907. params = zstd.ZstdCompressionParameters.from_level(7, source_size=1048576)
  908. Using ``from_level()``, it is also possible to override individual compression
  909. parameters or to define additional settings that aren't automatically derived.
  910. e.g.::
  911. params = zstd.ZstdCompressionParameters.from_level(4, window_log=10)
  912. params = zstd.ZstdCompressionParameters.from_level(5, threads=4)
  913. Or you can define low-level compression settings directly::
  914. params = zstd.ZstdCompressionParameters(window_log=12, enable_ldm=True)
  915. Once a ``ZstdCompressionParameters`` instance is obtained, it can be used to
  916. configure a compressor::
  917. cctx = zstd.ZstdCompressor(compression_params=params)
  918. The named arguments and attributes of ``ZstdCompressionParameters`` are as
  919. follows:
  920. * format
  921. * compression_level
  922. * window_log
  923. * hash_log
  924. * chain_log
  925. * search_log
  926. * min_match
  927. * target_length
  928. * strategy
  929. * compression_strategy (deprecated: same as ``strategy``)
  930. * write_content_size
  931. * write_checksum
  932. * write_dict_id
  933. * job_size
  934. * overlap_log
  935. * overlap_size_log (deprecated: same as ``overlap_log``)
  936. * force_max_window
  937. * enable_ldm
  938. * ldm_hash_log
  939. * ldm_min_match
  940. * ldm_bucket_size_log
  941. * ldm_hash_rate_log
  942. * ldm_hash_every_log (deprecated: same as ``ldm_hash_rate_log``)
  943. * threads
  944. Some of these are very low-level settings. It may help to consult the official
  945. zstandard documentation for their behavior. Look for the ``ZSTD_p_*`` constants
  946. in ``zstd.h`` (https://github.com/facebook/zstd/blob/dev/lib/zstd.h).
  947. Frame Inspection
  948. ----------------
  949. Data emitted from zstd compression is encapsulated in a *frame*. This frame
  950. begins with a 4 byte *magic number* header followed by 2 to 14 bytes describing
  951. the frame in more detail. For more info, see
  952. https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md.
  953. ``zstd.get_frame_parameters(data)`` parses a zstd *frame* header from a bytes
  954. instance and return a ``FrameParameters`` object describing the frame.
  955. Depending on which fields are present in the frame and their values, the
  956. length of the frame parameters varies. If insufficient bytes are passed
  957. in to fully parse the frame parameters, ``ZstdError`` is raised. To ensure
  958. frame parameters can be parsed, pass in at least 18 bytes.
  959. ``FrameParameters`` instances have the following attributes:
  960. content_size
  961. Integer size of original, uncompressed content. This will be ``0`` if the
  962. original content size isn't written to the frame (controlled with the
  963. ``write_content_size`` argument to ``ZstdCompressor``) or if the input
  964. content size was ``0``.
  965. window_size
  966. Integer size of maximum back-reference distance in compressed data.
  967. dict_id
  968. Integer of dictionary ID used for compression. ``0`` if no dictionary
  969. ID was used or if the dictionary ID was ``0``.
  970. has_checksum
  971. Bool indicating whether a 4 byte content checksum is stored at the end
  972. of the frame.
  973. ``zstd.frame_header_size(data)`` returns the size of the zstandard frame
  974. header.
  975. ``zstd.frame_content_size(data)`` returns the content size as parsed from
  976. the frame header. ``-1`` means the content size is unknown. ``0`` means
  977. an empty frame. The content size is usually correct. However, it may not
  978. be accurate.
  979. Misc Functionality
  980. ------------------
  981. estimate_decompression_context_size()
  982. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  983. Estimate the memory size requirements for a decompressor instance.
  984. Constants
  985. ---------
  986. The following module constants/attributes are exposed:
  987. ZSTD_VERSION
  988. This module attribute exposes a 3-tuple of the Zstandard version. e.g.
  989. ``(1, 0, 0)``
  990. MAX_COMPRESSION_LEVEL
  991. Integer max compression level accepted by compression functions
  992. COMPRESSION_RECOMMENDED_INPUT_SIZE
  993. Recommended chunk size to feed to compressor functions
  994. COMPRESSION_RECOMMENDED_OUTPUT_SIZE
  995. Recommended chunk size for compression output
  996. DECOMPRESSION_RECOMMENDED_INPUT_SIZE
  997. Recommended chunk size to feed into decompresor functions
  998. DECOMPRESSION_RECOMMENDED_OUTPUT_SIZE
  999. Recommended chunk size for decompression output
  1000. FRAME_HEADER
  1001. bytes containing header of the Zstandard frame
  1002. MAGIC_NUMBER
  1003. Frame header as an integer
  1004. FLUSH_BLOCK
  1005. Flushing behavior that denotes to flush a zstd block. A decompressor will
  1006. be able to decode all data fed into the compressor so far.
  1007. FLUSH_FRAME
  1008. Flushing behavior that denotes to end a zstd frame. Any new data fed
  1009. to the compressor will start a new frame.
  1010. CONTENTSIZE_UNKNOWN
  1011. Value for content size when the content size is unknown.
  1012. CONTENTSIZE_ERROR
  1013. Value for content size when content size couldn't be determined.
  1014. WINDOWLOG_MIN
  1015. Minimum value for compression parameter
  1016. WINDOWLOG_MAX
  1017. Maximum value for compression parameter
  1018. CHAINLOG_MIN
  1019. Minimum value for compression parameter
  1020. CHAINLOG_MAX
  1021. Maximum value for compression parameter
  1022. HASHLOG_MIN
  1023. Minimum value for compression parameter
  1024. HASHLOG_MAX
  1025. Maximum value for compression parameter
  1026. SEARCHLOG_MIN
  1027. Minimum value for compression parameter
  1028. SEARCHLOG_MAX
  1029. Maximum value for compression parameter
  1030. MINMATCH_MIN
  1031. Minimum value for compression parameter
  1032. MINMATCH_MAX
  1033. Maximum value for compression parameter
  1034. SEARCHLENGTH_MIN
  1035. Minimum value for compression parameter
  1036. Deprecated: use ``MINMATCH_MIN``
  1037. SEARCHLENGTH_MAX
  1038. Maximum value for compression parameter
  1039. Deprecated: use ``MINMATCH_MAX``
  1040. TARGETLENGTH_MIN
  1041. Minimum value for compression parameter
  1042. STRATEGY_FAST
  1043. Compression strategy
  1044. STRATEGY_DFAST
  1045. Compression strategy
  1046. STRATEGY_GREEDY
  1047. Compression strategy
  1048. STRATEGY_LAZY
  1049. Compression strategy
  1050. STRATEGY_LAZY2
  1051. Compression strategy
  1052. STRATEGY_BTLAZY2
  1053. Compression strategy
  1054. STRATEGY_BTOPT
  1055. Compression strategy
  1056. STRATEGY_BTULTRA
  1057. Compression strategy
  1058. STRATEGY_BTULTRA2
  1059. Compression strategy
  1060. FORMAT_ZSTD1
  1061. Zstandard frame format
  1062. FORMAT_ZSTD1_MAGICLESS
  1063. Zstandard frame format without magic header
  1064. Performance Considerations
  1065. --------------------------
  1066. The ``ZstdCompressor`` and ``ZstdDecompressor`` types maintain state to a
  1067. persistent compression or decompression *context*. Reusing a ``ZstdCompressor``
  1068. or ``ZstdDecompressor`` instance for multiple operations is faster than
  1069. instantiating a new ``ZstdCompressor`` or ``ZstdDecompressor`` for each
  1070. operation. The differences are magnified as the size of data decreases. For
  1071. example, the difference between *context* reuse and non-reuse for 100,000
  1072. 100 byte inputs will be significant (possiby over 10x faster to reuse contexts)
  1073. whereas 10 100,000,000 byte inputs will be more similar in speed (because the
  1074. time spent doing compression dwarfs time spent creating new *contexts*).
  1075. Buffer Types
  1076. ------------
  1077. The API exposes a handful of custom types for interfacing with memory buffers.
  1078. The primary goal of these types is to facilitate efficient multi-object
  1079. operations.
  1080. The essential idea is to have a single memory allocation provide backing
  1081. storage for multiple logical objects. This has 2 main advantages: fewer
  1082. allocations and optimal memory access patterns. This avoids having to allocate
  1083. a Python object for each logical object and furthermore ensures that access of
  1084. data for objects can be sequential (read: fast) in memory.
  1085. BufferWithSegments
  1086. ^^^^^^^^^^^^^^^^^^
  1087. The ``BufferWithSegments`` type represents a memory buffer containing N
  1088. discrete items of known lengths (segments). It is essentially a fixed size
  1089. memory address and an array of 2-tuples of ``(offset, length)`` 64-bit
  1090. unsigned native endian integers defining the byte offset and length of each
  1091. segment within the buffer.
  1092. Instances behave like containers.
  1093. ``len()`` returns the number of segments within the instance.
  1094. ``o[index]`` or ``__getitem__`` obtains a ``BufferSegment`` representing an
  1095. individual segment within the backing buffer. That returned object references
  1096. (not copies) memory. This means that iterating all objects doesn't copy
  1097. data within the buffer.
  1098. The ``.size`` attribute contains the total size in bytes of the backing
  1099. buffer.
  1100. Instances conform to the buffer protocol. So a reference to the backing bytes
  1101. can be obtained via ``memoryview(o)``. A *copy* of the backing bytes can also
  1102. be obtained via ``.tobytes()``.
  1103. The ``.segments`` attribute exposes the array of ``(offset, length)`` for
  1104. segments within the buffer. It is a ``BufferSegments`` type.
  1105. BufferSegment
  1106. ^^^^^^^^^^^^^
  1107. The ``BufferSegment`` type represents a segment within a ``BufferWithSegments``.
  1108. It is essentially a reference to N bytes within a ``BufferWithSegments``.
  1109. ``len()`` returns the length of the segment in bytes.
  1110. ``.offset`` contains the byte offset of this segment within its parent
  1111. ``BufferWithSegments`` instance.
  1112. The object conforms to the buffer protocol. ``.tobytes()`` can be called to
  1113. obtain a ``bytes`` instance with a copy of the backing bytes.
  1114. BufferSegments
  1115. ^^^^^^^^^^^^^^
  1116. This type represents an array of ``(offset, length)`` integers defining segments
  1117. within a ``BufferWithSegments``.
  1118. The array members are 64-bit unsigned integers using host/native bit order.
  1119. Instances conform to the buffer protocol.
  1120. BufferWithSegmentsCollection
  1121. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1122. The ``BufferWithSegmentsCollection`` type represents a virtual spanning view
  1123. of multiple ``BufferWithSegments`` instances.
  1124. Instances are constructed from 1 or more ``BufferWithSegments`` instances. The
  1125. resulting object behaves like an ordered sequence whose members are the
  1126. segments within each ``BufferWithSegments``.
  1127. ``len()`` returns the number of segments within all ``BufferWithSegments``
  1128. instances.
  1129. ``o[index]`` and ``__getitem__(index)`` return the ``BufferSegment`` at
  1130. that offset as if all ``BufferWithSegments`` instances were a single
  1131. entity.
  1132. If the object is composed of 2 ``BufferWithSegments`` instances with the
  1133. first having 2 segments and the second have 3 segments, then ``b[0]``
  1134. and ``b[1]`` access segments in the first object and ``b[2]``, ``b[3]``,
  1135. and ``b[4]`` access segments from the second.
  1136. Choosing an API
  1137. ===============
  1138. There are multiple APIs for performing compression and decompression. This is
  1139. because different applications have different needs and the library wants to
  1140. facilitate optimal use in as many use cases as possible.
  1141. From a high-level, APIs are divided into *one-shot* and *streaming*: either you
  1142. are operating on all data at once or you operate on it piecemeal.
  1143. The *one-shot* APIs are useful for small data, where the input or output
  1144. size is known. (The size can come from a buffer length, file size, or
  1145. stored in the zstd frame header.) A limitation of the *one-shot* APIs is that
  1146. input and output must fit in memory simultaneously. For say a 4 GB input,
  1147. this is often not feasible.
  1148. The *one-shot* APIs also perform all work as a single operation. So, if you
  1149. feed it large input, it could take a long time for the function to return.
  1150. The streaming APIs do not have the limitations of the simple API. But the
  1151. price you pay for this flexibility is that they are more complex than a
  1152. single function call.
  1153. The streaming APIs put the caller in control of compression and decompression
  1154. behavior by allowing them to directly control either the input or output side
  1155. of the operation.
  1156. With the *streaming input*, *compressor*, and *decompressor* APIs, the caller
  1157. has full control over the input to the compression or decompression stream.
  1158. They can directly choose when new data is operated on.
  1159. With the *streaming ouput* APIs, the caller has full control over the output
  1160. of the compression or decompression stream. It can choose when to receive
  1161. new data.
  1162. When using the *streaming* APIs that operate on file-like or stream objects,
  1163. it is important to consider what happens in that object when I/O is requested.
  1164. There is potential for long pauses as data is read or written from the
  1165. underlying stream (say from interacting with a filesystem or network). This
  1166. could add considerable overhead.
  1167. Thread Safety
  1168. =============
  1169. ``ZstdCompressor`` and ``ZstdDecompressor`` instances have no guarantees
  1170. about thread safety. Do not operate on the same ``ZstdCompressor`` and
  1171. ``ZstdDecompressor`` instance simultaneously from different threads. It is
  1172. fine to have different threads call into a single instance, just not at the
  1173. same time.
  1174. Some operations require multiple function calls to complete. e.g. streaming
  1175. operations. A single ``ZstdCompressor`` or ``ZstdDecompressor`` cannot be used
  1176. for simultaneously active operations. e.g. you must not start a streaming
  1177. operation when another streaming operation is already active.
  1178. The C extension releases the GIL during non-trivial calls into the zstd C
  1179. API. Non-trivial calls are notably compression and decompression. Trivial
  1180. calls are things like parsing frame parameters. Where the GIL is released
  1181. is considered an implementation detail and can change in any release.
  1182. APIs that accept bytes-like objects don't enforce that the underlying object
  1183. is read-only. However, it is assumed that the passed object is read-only for
  1184. the duration of the function call. It is possible to pass a mutable object
  1185. (like a ``bytearray``) to e.g. ``ZstdCompressor.compress()``, have the GIL
  1186. released, and mutate the object from another thread. Such a race condition
  1187. is a bug in the consumer of python-zstandard. Most Python data types are
  1188. immutable, so unless you are doing something fancy, you don't need to
  1189. worry about this.
  1190. Note on Zstandard's *Experimental* API
  1191. ======================================
  1192. Many of the Zstandard APIs used by this module are marked as *experimental*
  1193. within the Zstandard project.
  1194. It is unclear how Zstandard's C API will evolve over time, especially with
  1195. regards to this *experimental* functionality. We will try to maintain
  1196. backwards compatibility at the Python API level. However, we cannot
  1197. guarantee this for things not under our control.
  1198. Since a copy of the Zstandard source code is distributed with this
  1199. module and since we compile against it, the behavior of a specific
  1200. version of this module should be constant for all of time. So if you
  1201. pin the version of this module used in your projects (which is a Python
  1202. best practice), you should be shielded from unwanted future changes.
  1203. Donate
  1204. ======
  1205. A lot of time has been invested into this project by the author.
  1206. If you find this project useful and would like to thank the author for
  1207. their work, consider donating some money. Any amount is appreciated.
  1208. .. image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif
  1209. :target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=gregory%2eszorc%40gmail%2ecom&lc=US&item_name=python%2dzstandard&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted
  1210. :alt: Donate via PayPal
  1211. .. |ci-status| image:: https://dev.azure.com/gregoryszorc/python-zstandard/_apis/build/status/indygreg.python-zstandard?branchName=master
  1212. :target: https://dev.azure.com/gregoryszorc/python-zstandard/_apis/build/status/indygreg.python-zstandard?branchName=master