Debian Codegraph @

lz4/frame/_frame.c

raw symbols SCIP
1 /*
2 * Copyright (c) 2015, 2016 Jerry Ryle and Jonathan G. Underwood
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * 3. Neither the name of the copyright holders nor the names of its
16 * contributors may be used to endorse or promote products derived from this
17 * software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 */
32 #if defined(_WIN32) && defined(_MSC_VER)
33 #define inline __inline
34 #elif defined(__SUNPRO_C) || defined(__hpux) || defined(_AIX)
35 #define inline
36 #endif
37
38 #include <Python.h>
39
40 #include <stdlib.h>
41 #include <lz4.h> /* Needed for LZ4_VERSION_NUMBER only. */
42 #include <lz4frame.h>
43
44 static const char * compression_context_capsule_name = "_frame.LZ4F_cctx";
45 static const char * decompression_context_capsule_name = "_frame.LZ4F_dctx";
46
47 struct compression_context
48 {
49 LZ4F_cctx * context;
50 LZ4F_preferences_t preferences;
51 };
52
53 /*****************************
54 * create_compression_context *
55 ******************************/
56 static void
57 destroy_compression_context (PyObject * py_context)
58 {
59 #ifndef PyCapsule_Type
60 struct compression_context *context =
61 PyCapsule_GetPointer (py_context, compression_context_capsule_name);
62 #else
63 /* Compatibility with 2.6 via capsulethunk. */
64 struct compression_context *context = py_context;
65 #endif
66 Py_BEGIN_ALLOW_THREADS
67 LZ4F_freeCompressionContext (context->context);
68 Py_END_ALLOW_THREADS
69
70 PyMem_Free (context);
71 }
72
73 static PyObject *
74 create_compression_context (PyObject * Py_UNUSED (self))
75 {
76 struct compression_context * context;
77 LZ4F_errorCode_t result;
78
79 context =
80 (struct compression_context *)
81 PyMem_Malloc (sizeof (struct compression_context));
82
83 if (!context)
84 {
85 return PyErr_NoMemory ();
86 }
87
88 Py_BEGIN_ALLOW_THREADS
89
90 result =
91 LZ4F_createCompressionContext (&context->context,
92 LZ4F_VERSION);
93 Py_END_ALLOW_THREADS
94
95 if (LZ4F_isError (result))
96 {
97 LZ4F_freeCompressionContext (context->context);
98 PyMem_Free (context);
99 PyErr_Format (PyExc_RuntimeError,
100 "LZ4F_createCompressionContext failed with code: %s",
101 LZ4F_getErrorName (result));
102 return NULL;
103 }
104
105 return PyCapsule_New (context, compression_context_capsule_name,
106 destroy_compression_context);
107 }
108
109 /************
110 * compress *
111 ************/
112 static PyObject *
113 compress (PyObject * Py_UNUSED (self), PyObject * args,
114 PyObject * keywds)
115 {
116 Py_buffer source;
117 Py_ssize_t source_size;
118 int store_size = 1;
119 int return_bytearray = 0;
120 int content_checksum = 0;
121 int block_checksum = 0;
122 int block_linked = 1;
123 LZ4F_preferences_t preferences;
124 size_t destination_size;
125 size_t compressed_size;
126 PyObject *py_destination;
127 char *destination;
128
129 static char *kwlist[] = { "data",
130 "compression_level",
131 "block_size",
132 "content_checksum",
133 "block_checksum",
134 "block_linked",
135 "store_size",
136 "return_bytearray",
137 NULL
138 };
139
140
141 memset (&preferences, 0, sizeof preferences);
142
143 if (!PyArg_ParseTupleAndKeywords (args, keywds, "y*|iippppp", kwlist,
144 &source,
145 &preferences.compressionLevel,
146 &preferences.frameInfo.blockSizeID,
147 &content_checksum,
148 &block_checksum,
149 &block_linked,
150 &store_size,
151 &return_bytearray))
152 {
153 return NULL;
154 }
155
156 if (content_checksum)
157 {
158 preferences.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;
159 }
160 else
161 {
162 preferences.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum;
163 }
164
165 if (block_linked)
166 {
167 preferences.frameInfo.blockMode = LZ4F_blockLinked;
168 }
169 else
170 {
171 preferences.frameInfo.blockMode = LZ4F_blockIndependent;
172 }
173
174 if (LZ4_versionNumber() >= 10800)
175 {
176 if (block_checksum)
177 {
178 preferences.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled;
179 }
180 else
181 {
182 preferences.frameInfo.blockChecksumFlag = LZ4F_noBlockChecksum;
183 }
184 }
185 else if (block_checksum)
186 {
187 PyErr_SetString (PyExc_RuntimeError,
188 "block_checksum specified but not supported by LZ4 library version");
189 return NULL;
190 }
191
192 source_size = source.len;
193
194 preferences.autoFlush = 0;
195 if (store_size)
196 {
197 preferences.frameInfo.contentSize = source_size;
198 }
199 else
200 {
201 preferences.frameInfo.contentSize = 0;
202 }
203
204 Py_BEGIN_ALLOW_THREADS
205 destination_size =
206 LZ4F_compressFrameBound (source_size, &preferences);
207 Py_END_ALLOW_THREADS
208
209 if (destination_size > PY_SSIZE_T_MAX)
210 {
211 PyBuffer_Release(&source);
212 PyErr_Format (PyExc_ValueError,
213 "Input data could require %zu bytes, which is larger than the maximum supported size of %zd bytes",
214 destination_size, PY_SSIZE_T_MAX);
215 return NULL;
216 }
217
218 destination = PyMem_Malloc (destination_size * sizeof * destination);
219 if (destination == NULL)
220 {
221 PyBuffer_Release(&source);
222 return PyErr_NoMemory();
223 }
224
225 Py_BEGIN_ALLOW_THREADS
226 compressed_size =
227 LZ4F_compressFrame (destination, destination_size, source.buf, source_size,
228 &preferences);
229 Py_END_ALLOW_THREADS
230
231 PyBuffer_Release(&source);
232
233 if (LZ4F_isError (compressed_size))
234 {
235 PyMem_Free (destination);
236 PyErr_Format (PyExc_RuntimeError,
237 "LZ4F_compressFrame failed with code: %s",
238 LZ4F_getErrorName (compressed_size));
239 return NULL;
240 }
241
242 if (return_bytearray)
243 {
244 py_destination = PyByteArray_FromStringAndSize (destination, (Py_ssize_t) compressed_size);
245 }
246 else
247 {
248 py_destination = PyBytes_FromStringAndSize (destination, (Py_ssize_t) compressed_size);
249 }
250
251 PyMem_Free (destination);
252
253 if (py_destination == NULL)
254 {
255 return PyErr_NoMemory ();
256 }
257
258 return py_destination;
259 }
260
261 /******************
262 * compress_begin *
263 ******************/
264 static PyObject *
265 compress_begin (PyObject * Py_UNUSED (self), PyObject * args,
266 PyObject * keywds)
267 {
268 PyObject *py_context = NULL;
269 Py_ssize_t source_size = (Py_ssize_t) 0;
270 int return_bytearray = 0;
271 int content_checksum = 0;
272 int block_checksum = 0;
273 int block_linked = 1;
274 LZ4F_preferences_t preferences;
275 PyObject *py_destination;
276 char * destination;
277 /* The destination buffer needs to be large enough for a header, which is 15
278 * bytes. Unfortunately, the lz4 library doesn't provide a #define for this.
279 * We over-allocate to allow for larger headers in the future. */
280 const size_t header_size = 32;
281 struct compression_context *context;
282 size_t result;
283 static char *kwlist[] = { "context",
284 "source_size",
285 "compression_level",
286 "block_size",
287 "content_checksum",
288 "block_checksum",
289 "block_linked",
290 "auto_flush",
291 "return_bytearray",
292 NULL
293 };
294
295 memset (&preferences, 0, sizeof preferences);
296
297 if (!PyArg_ParseTupleAndKeywords (args, keywds, "O|kiippppp", kwlist,
298 &py_context,
299 &source_size,
300 &preferences.compressionLevel,
301 &preferences.frameInfo.blockSizeID,
302 &content_checksum,
303 &block_checksum,
304 &block_linked,
305 &preferences.autoFlush,
306 &return_bytearray
307 ))
308 {
309 return NULL;
310 }
311
312 if (content_checksum)
313 {
314 preferences.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;
315 }
316 else
317 {
318 preferences.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum;
319 }
320
321 if (block_linked)
322 {
323 preferences.frameInfo.blockMode = LZ4F_blockLinked;
324 }
325 else
326 {
327 preferences.frameInfo.blockMode = LZ4F_blockIndependent;
328 }
329
330 if (LZ4_versionNumber() >= 10800)
331 {
332 if (block_checksum)
333 {
334 preferences.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled;
335 }
336 else
337 {
338 preferences.frameInfo.blockChecksumFlag = LZ4F_noBlockChecksum;
339 }
340 }
341 else if (block_checksum)
342 {
343 PyErr_SetString (PyExc_RuntimeError,
344 "block_checksum specified but not supported by LZ4 library version");
345 return NULL;
346 }
347
348 if (block_linked)
349 {
350 preferences.frameInfo.blockMode = LZ4F_blockLinked;
351 }
352 else
353 {
354 preferences.frameInfo.blockMode = LZ4F_blockIndependent;
355 }
356
357
358 preferences.frameInfo.contentSize = source_size;
359
360 context =
361 (struct compression_context *) PyCapsule_GetPointer (py_context, compression_context_capsule_name);
362
363 if (!context || !context->context)
364 {
365 PyErr_SetString (PyExc_ValueError, "No valid compression context supplied");
366 return NULL;
367 }
368
369 context->preferences = preferences;
370
371 destination = PyMem_Malloc (header_size * sizeof * destination);
372 if (destination == NULL)
373 {
374 return PyErr_NoMemory();
375 }
376
377 Py_BEGIN_ALLOW_THREADS
378 result = LZ4F_compressBegin (context->context,
379 destination,
380 header_size,
381 &context->preferences);
382 Py_END_ALLOW_THREADS
383
384 if (LZ4F_isError (result))
385 {
386 PyErr_Format (PyExc_RuntimeError,
387 "LZ4F_compressBegin failed with code: %s",
388 LZ4F_getErrorName (result));
389 return NULL;
390 }
391
392 if (return_bytearray)
393 {
394 py_destination = PyByteArray_FromStringAndSize (destination, (Py_ssize_t) result);
395 }
396 else
397 {
398 py_destination = PyBytes_FromStringAndSize (destination, (Py_ssize_t) result);
399 }
400
401 PyMem_Free (destination);
402
403 if (py_destination == NULL)
404 {
405 return PyErr_NoMemory ();
406 }
407
408 return py_destination;
409 }
410
411 /******************
412 * compress_chunk *
413 ******************/
414 static PyObject *
415 compress_chunk (PyObject * Py_UNUSED (self), PyObject * args,
416 PyObject * keywds)
417 {
418 PyObject *py_context = NULL;
419 Py_buffer source;
420 Py_ssize_t source_size;
421 struct compression_context *context;
422 size_t compressed_bound;
423 PyObject *py_destination;
424 char *destination;
425 LZ4F_compressOptions_t compress_options;
426 size_t result;
427 int return_bytearray = 0;
428 static char *kwlist[] = { "context",
429 "data",
430 "return_bytearray",
431 NULL
432 };
433
434 memset (&compress_options, 0, sizeof compress_options);
435
436 if (!PyArg_ParseTupleAndKeywords (args, keywds, "Oy*|p", kwlist,
437 &py_context,
438 &source,
439 &return_bytearray))
440 {
441 return NULL;
442 }
443
444 source_size = source.len;
445
446 context =
447 (struct compression_context *) PyCapsule_GetPointer (py_context, compression_context_capsule_name);
448 if (!context || !context->context)
449 {
450 PyBuffer_Release(&source);
451 PyErr_Format (PyExc_ValueError, "No compression context supplied");
452 return NULL;
453 }
454
455 /* If autoFlush is enabled, then the destination buffer only needs to be as
456 big as LZ4F_compressFrameBound specifies for this source size. However, if
457 autoFlush is disabled, previous calls may have resulted in buffered data,
458 and so we need instead to use LZ4F_compressBound to find the size required
459 for the destination buffer. This means that with autoFlush disabled we may
460 frequently allocate more memory than needed. */
461 Py_BEGIN_ALLOW_THREADS
462 if (context->preferences.autoFlush == 1)
463 {
464 compressed_bound =
465 LZ4F_compressFrameBound (source_size, &context->preferences);
466 }
467 else
468 {
469 compressed_bound =
470 LZ4F_compressBound (source_size, &context->preferences);
471 }
472 Py_END_ALLOW_THREADS
473
474 if (compressed_bound > PY_SSIZE_T_MAX)
475 {
476 PyBuffer_Release(&source);
477 PyErr_Format (PyExc_ValueError,
478 "input data could require %zu bytes, which is larger than the maximum supported size of %zd bytes",
479 compressed_bound, PY_SSIZE_T_MAX);
480 return NULL;
481 }
482
483 destination = PyMem_Malloc (compressed_bound * sizeof * destination);
484 if (destination == NULL)
485 {
486 PyBuffer_Release(&source);
487 return PyErr_NoMemory();
488 }
489
490 compress_options.stableSrc = 0;
491
492 Py_BEGIN_ALLOW_THREADS
493 result =
494 LZ4F_compressUpdate (context->context, destination,
495 compressed_bound, source.buf, source_size,
496 &compress_options);
497 Py_END_ALLOW_THREADS
498
499 PyBuffer_Release(&source);
500
501 if (LZ4F_isError (result))
502 {
503 PyMem_Free (destination);
504 PyErr_Format (PyExc_RuntimeError,
505 "LZ4F_compressUpdate failed with code: %s",
506 LZ4F_getErrorName (result));
507 return NULL;
508 }
509
510 if (return_bytearray)
511 {
512 py_destination = PyByteArray_FromStringAndSize (destination, (Py_ssize_t) result);
513 }
514 else
515 {
516 py_destination = PyBytes_FromStringAndSize (destination, (Py_ssize_t) result);
517 }
518
519 PyMem_Free (destination);
520
521 if (py_destination == NULL)
522 {
523 return PyErr_NoMemory ();
524 }
525
526 return py_destination;
527 }
528
529 /******************
530 * compress_flush *
531 ******************/
532 static PyObject *
533 compress_flush (PyObject * Py_UNUSED (self), PyObject * args, PyObject * keywds)
534 {
535 PyObject *py_context = NULL;
536 LZ4F_compressOptions_t compress_options;
537 struct compression_context *context;
538 size_t destination_size;
539 int return_bytearray = 0;
540 int end_frame = 1;
541 PyObject *py_destination;
542 char * destination;
543 size_t result;
544 static char *kwlist[] = { "context",
545 "end_frame",
546 "return_bytearray",
547 NULL
548 };
549
550 memset (&compress_options, 0, sizeof compress_options);
551
552 if (!PyArg_ParseTupleAndKeywords (args, keywds, "O|pp", kwlist,
553 &py_context,
554 &end_frame,
555 &return_bytearray))
556 {
557 return NULL;
558 }
559
560 if (!end_frame && LZ4_versionNumber() < 10800)
561 {
562 PyErr_SetString (PyExc_RuntimeError,
563 "Flush without ending a frame is not supported with this version of the LZ4 library");
564 return NULL;
565 }
566
567 context =
568 (struct compression_context *) PyCapsule_GetPointer (py_context, compression_context_capsule_name);
569 if (!context || !context->context)
570 {
571 PyErr_SetString (PyExc_ValueError, "No compression context supplied");
572 return NULL;
573 }
574
575 compress_options.stableSrc = 0;
576
577 /* Calling LZ4F_compressBound with srcSize equal to 0 returns a size
578 sufficient to fit (i) any remaining buffered data (when autoFlush is
579 disabled) and the footer size, which is either 4 or 8 bytes depending on
580 whether checksums are enabled. See: https://github.com/lz4/lz4/issues/280
581 and https://github.com/lz4/lz4/issues/290. Prior to 1.7.5, it was necessary
582 to call LZ4F_compressBound with srcSize equal to 1. Since we now require a
583 minimum version to 1.7.5 we'll call this with srcSize equal to 0. */
584 Py_BEGIN_ALLOW_THREADS
585 destination_size = LZ4F_compressBound (0, &(context->preferences));
586 Py_END_ALLOW_THREADS
587
588 destination = PyMem_Malloc (destination_size * sizeof * destination);
589 if (destination == NULL)
590 {
591 return PyErr_NoMemory();
592 }
593
594 Py_BEGIN_ALLOW_THREADS
595 if (end_frame)
596 {
597 result =
598 LZ4F_compressEnd (context->context, destination,
599 destination_size, &compress_options);
600 }
601 else
602 {
603 result =
604 LZ4F_flush (context->context, destination,
605 destination_size, &compress_options);
606 }
607 Py_END_ALLOW_THREADS
608
609 if (LZ4F_isError (result))
610 {
611 PyMem_Free (destination);
612 PyErr_Format (PyExc_RuntimeError,
613 "LZ4F_compressEnd failed with code: %s",
614 LZ4F_getErrorName (result));
615 return NULL;
616 }
617
618 if (return_bytearray)
619 {
620 py_destination = PyByteArray_FromStringAndSize (destination, (Py_ssize_t) result);
621 }
622 else
623 {
624 py_destination = PyBytes_FromStringAndSize (destination, (Py_ssize_t) result);
625 }
626
627 PyMem_Free (destination);
628
629 if (py_destination == NULL)
630 {
631 return PyErr_NoMemory ();
632 }
633
634 return py_destination;
635 }
636
637 /******************
638 * get_frame_info *
639 ******************/
640 static PyObject *
641 get_frame_info (PyObject * Py_UNUSED (self), PyObject * args,
642 PyObject * keywds)
643 {
644 Py_buffer py_source;
645 char *source;
646 size_t source_size;
647 LZ4F_decompressionContext_t context;
648 LZ4F_frameInfo_t frame_info;
649 size_t result;
650 unsigned int block_size;
651 unsigned int block_size_id;
652 int block_linked;
653 int content_checksum;
654 int block_checksum;
655 int skippable;
656
657 static char *kwlist[] = { "data",
658 NULL
659 };
660
661 if (!PyArg_ParseTupleAndKeywords (args, keywds, "y*", kwlist,
662 &py_source))
663 {
664 return NULL;
665 }
666
667 Py_BEGIN_ALLOW_THREADS
668
669 result = LZ4F_createDecompressionContext (&context, LZ4F_VERSION);
670
671 if (LZ4F_isError (result))
672 {
673 Py_BLOCK_THREADS
674 PyBuffer_Release (&py_source);
675 PyErr_Format (PyExc_RuntimeError,
676 "LZ4F_createDecompressionContext failed with code: %s",
677 LZ4F_getErrorName (result));
678 return NULL;
679 }
680
681 source = (char *) py_source.buf;
682 source_size = (size_t) py_source.len;
683
684 result =
685 LZ4F_getFrameInfo (context, &frame_info, source, &source_size);
686
687 if (LZ4F_isError (result))
688 {
689 LZ4F_freeDecompressionContext (context);
690 Py_BLOCK_THREADS
691 PyBuffer_Release (&py_source);
692 PyErr_Format (PyExc_RuntimeError,
693 "LZ4F_getFrameInfo failed with code: %s",
694 LZ4F_getErrorName (result));
695 return NULL;
696 }
697
698 result = LZ4F_freeDecompressionContext (context);
699
700 Py_END_ALLOW_THREADS
701
702 PyBuffer_Release (&py_source);
703
704 if (LZ4F_isError (result))
705 {
706 PyErr_Format (PyExc_RuntimeError,
707 "LZ4F_freeDecompressionContext failed with code: %s",
708 LZ4F_getErrorName (result));
709 return NULL;
710 }
711
712 #define KB *(1<<10)
713 #define MB *(1<<20)
714 switch (frame_info.blockSizeID)
715 {
716 case LZ4F_default:
717 case LZ4F_max64KB:
718 block_size = 64 KB;
719 block_size_id = LZ4F_max64KB;
720 break;
721 case LZ4F_max256KB:
722 block_size = 256 KB;
723 block_size_id = LZ4F_max256KB;
724 break;
725 case LZ4F_max1MB:
726 block_size = 1 MB;
727 block_size_id = LZ4F_max1MB;
728 break;
729 case LZ4F_max4MB:
730 block_size = 4 MB;
731 block_size_id = LZ4F_max4MB;
732 break;
733 default:
734 PyErr_Format (PyExc_RuntimeError,
735 "Unrecognized blockSizeID in get_frame_info: %d",
736 frame_info.blockSizeID);
737 return NULL;
738 }
739 #undef KB
740 #undef MB
741
742 if (frame_info.blockMode == LZ4F_blockLinked)
743 {
744 block_linked = 1;
745 }
746 else if (frame_info.blockMode == LZ4F_blockIndependent)
747 {
748 block_linked = 0;
749 }
750 else
751 {
752 PyErr_Format (PyExc_RuntimeError,
753 "Unrecognized blockMode in get_frame_info: %d",
754 frame_info.blockMode);
755 return NULL;
756 }
757
758 if (frame_info.contentChecksumFlag == LZ4F_noContentChecksum)
759 {
760 content_checksum = 0;
761 }
762 else if (frame_info.contentChecksumFlag == LZ4F_contentChecksumEnabled)
763 {
764 content_checksum = 1;
765 }
766 else
767 {
768 PyErr_Format (PyExc_RuntimeError,
769 "Unrecognized contentChecksumFlag in get_frame_info: %d",
770 frame_info.contentChecksumFlag);
771 return NULL;
772 }
773
774 if (LZ4_versionNumber() >= 10800)
775 {
776 if (frame_info.blockChecksumFlag == LZ4F_noBlockChecksum)
777 {
778 block_checksum = 0;
779 }
780 else if (frame_info.blockChecksumFlag == LZ4F_blockChecksumEnabled)
781 {
782 block_checksum = 1;
783 }
784 else
785 {
786 PyErr_Format (PyExc_RuntimeError,
787 "Unrecognized blockChecksumFlag in get_frame_info: %d",
788 frame_info.blockChecksumFlag);
789 return NULL;
790 }
791 }
792 else
793 {
794 /* Prior to LZ4 1.8.0 the blockChecksum functionality wasn't exposed in the
795 frame API, and blocks weren't checksummed, so we'll always return 0
796 here. */
797 block_checksum = 0;
798 }
799
800 if (frame_info.frameType == LZ4F_frame)
801 {
802 skippable = 0;
803 }
804 else if (frame_info.frameType == LZ4F_skippableFrame)
805 {
806 skippable = 1;
807 }
808 else
809 {
810 PyErr_Format (PyExc_RuntimeError,
811 "Unrecognized frameType in get_frame_info: %d",
812 frame_info.frameType);
813 return NULL;
814 }
815
816 return Py_BuildValue ("{s:I,s:I,s:O,s:O,s:O,s:O,s:K}",
817 "block_size", block_size,
818 "block_size_id", block_size_id,
819 "block_linked", block_linked ? Py_True : Py_False,
820 "content_checksum", content_checksum ? Py_True : Py_False,
821 "block_checksum", block_checksum ? Py_True : Py_False,
822 "skippable", skippable ? Py_True : Py_False,
823 "content_size", frame_info.contentSize);
824 }
825
826 /********************************
827 * create_decompression_context *
828 ********************************/
829 static void
830 destroy_decompression_context (PyObject * py_context)
831 {
832 #ifndef PyCapsule_Type
833 LZ4F_dctx * context =
834 PyCapsule_GetPointer (py_context, decompression_context_capsule_name);
835 #else
836 /* Compatibility with 2.6 via capsulethunk. */
837 LZ4F_dctx * context = py_context;
838 #endif
839 Py_BEGIN_ALLOW_THREADS
840 LZ4F_freeDecompressionContext (context);
841 Py_END_ALLOW_THREADS
842 }
843
844 static PyObject *
845 create_decompression_context (PyObject * Py_UNUSED (self))
846 {
847 LZ4F_dctx * context;
848 LZ4F_errorCode_t result;
849
850 Py_BEGIN_ALLOW_THREADS
851 result = LZ4F_createDecompressionContext (&context, LZ4F_VERSION);
852 if (LZ4F_isError (result))
853 {
854 Py_BLOCK_THREADS
855 LZ4F_freeDecompressionContext (context);
856 PyErr_Format (PyExc_RuntimeError,
857 "LZ4F_createDecompressionContext failed with code: %s",
858 LZ4F_getErrorName (result));
859 return NULL;
860 }
861 Py_END_ALLOW_THREADS
862
863 return PyCapsule_New (context, decompression_context_capsule_name,
864 destroy_decompression_context);
865 }
866
867 /*******************************
868 * reset_decompression_context *
869 *******************************/
870 static PyObject *
871 reset_decompression_context (PyObject * Py_UNUSED (self), PyObject * args,
872 PyObject * keywds)
873 {
874 LZ4F_dctx * context;
875 PyObject * py_context = NULL;
876 static char *kwlist[] = { "context",
877 NULL
878 };
879
880 if (!PyArg_ParseTupleAndKeywords (args, keywds, "O", kwlist,
881 &py_context
882 ))
883 {
884 return NULL;
885 }
886
887 context = (LZ4F_dctx *)
888 PyCapsule_GetPointer (py_context, decompression_context_capsule_name);
889
890 if (!context)
891 {
892 PyErr_SetString (PyExc_ValueError,
893 "No valid decompression context supplied");
894 return NULL;
895 }
896
897 if (LZ4_versionNumber() >= 10800) /* LZ4 >= v1.8.0 has LZ4F_resetDecompressionContext */
898 {
899 /* No error checking possible here - this is always successful. */
900 Py_BEGIN_ALLOW_THREADS
901 LZ4F_resetDecompressionContext (context);
902 Py_END_ALLOW_THREADS
903 }
904 else
905 {
906 /* No resetDecompressionContext available, so we'll destroy the context
907 and create a new one. */
908 int result;
909
910 Py_BEGIN_ALLOW_THREADS
911 LZ4F_freeDecompressionContext (context);
912
913 result = LZ4F_createDecompressionContext (&context, LZ4F_VERSION);
914 if (LZ4F_isError (result))
915 {
916 LZ4F_freeDecompressionContext (context);
917 Py_BLOCK_THREADS
918 PyErr_Format (PyExc_RuntimeError,
919 "LZ4F_createDecompressionContext failed with code: %s",
920 LZ4F_getErrorName (result));
921 return NULL;
922 }
923 Py_END_ALLOW_THREADS
924
925 result = PyCapsule_SetPointer(py_context, context);
926 if (result)
927 {
928 LZ4F_freeDecompressionContext (context);
929 PyErr_SetString (PyExc_RuntimeError,
930 "PyCapsule_SetPointer failed with code: %s");
931 return NULL;
932 }
933 }
934
935 Py_RETURN_NONE;
936 }
937
938 static inline PyObject *
939 __decompress(LZ4F_dctx * context, char * source, size_t source_size,
940 Py_ssize_t max_length, int full_frame,
941 int return_bytearray, int return_bytes_read)
942 {
943 size_t source_remain;
944 size_t source_read;
945 char * source_cursor;
946 char * source_end;
947 char * destination;
948 size_t destination_write;
949 char * destination_cursor;
950 size_t destination_written;
951 size_t destination_size;
952 PyObject * py_destination;
953 size_t result = 0;
954 LZ4F_frameInfo_t frame_info;
955 LZ4F_decompressOptions_t options;
956 int end_of_frame = 0;
957 int resize_factor = 1;
958
959 memset(&options, 0, sizeof options);
960
961 Py_BEGIN_ALLOW_THREADS
962
963 source_cursor = source;
964 source_end = source + source_size;
965 source_remain = source_size;
966
967 if (full_frame)
968 {
969 source_read = source_size;
970
971 result =
972 LZ4F_getFrameInfo (context, &frame_info,
973 source_cursor, &source_read);
974
975 if (LZ4F_isError (result))
976 {
977 Py_BLOCK_THREADS
978 PyErr_Format (PyExc_RuntimeError,
979 "LZ4F_getFrameInfo failed with code: %s",
980 LZ4F_getErrorName (result));
981 return NULL;
982 }
983
984 /* Advance the source_cursor pointer past the header - the call to
985 getFrameInfo above replaces the passed source_read value with the
986 number of bytes read. Also reduce source_remain accordingly. */
987 source_cursor += source_read;
988 source_remain -= source_read;
989
990 /* If the uncompressed content size is available, we'll use that to size
991 the destination buffer. Otherwise, guess at twice the remaining source
992 source as a starting point, and adjust if needed. */
993 if (frame_info.contentSize > 0)
994 {
995 destination_size = frame_info.contentSize;
996 }
997 else
998 {
999 destination_size = 2 * source_remain;
1000 }
1001 }
1002 else
1003 {
1004 if (max_length >= (Py_ssize_t) 0)
1005 {
1006 destination_size = (size_t) max_length;
1007 }
1008 else
1009 {
1010 /* Choose an initial destination size as twice the source size, and we'll
1011 grow the allocation as needed. */
1012 destination_size = 2 * source_remain;
1013 }
1014 }
1015
1016 Py_BLOCK_THREADS
1017
1018 destination = PyMem_Malloc (destination_size * sizeof * destination);
1019 if (destination == NULL)
1020 {
1021 return PyErr_NoMemory();
1022 }
1023
1024 Py_UNBLOCK_THREADS
1025
1026 /* Only set stableDst = 1 if we are sure no PyMem_Realloc will be called since
1027 when stableDst = 1 the LZ4 library stores a pointer to the last compressed
1028 data, which may be invalid after a PyMem_Realloc. */
1029 if (full_frame && max_length >= (Py_ssize_t) 0)
1030 {
1031 options.stableDst = 1;
1032 }
1033 else
1034 {
1035 options.stableDst = 0;
1036 }
1037
1038 source_read = source_remain;
1039
1040 destination_write = destination_size;
1041 destination_cursor = destination;
1042 destination_written = 0;
1043
1044 while (1)
1045 {
1046 /* Decompress from the source string and write to the destination
1047 until there's no more source string to read, or until we've reached the
1048 frame end.
1049
1050 On calling LZ4F_decompress, source_read is set to the remaining length
1051 of source available to read. On return, source_read is set to the
1052 actual number of bytes read from source, which may be less than
1053 available. NB: LZ4F_decompress does not explicitly fail on empty input.
1054
1055 On calling LZ4F_decompress, destination_write is the number of bytes in
1056 destination available for writing. On exit, destination_write is set to
1057 the actual number of bytes written to destination. */
1058 result = LZ4F_decompress (context,
1059 destination_cursor,
1060 &destination_write,
1061 source_cursor,
1062 &source_read,
1063 &options);
1064
1065 if (LZ4F_isError (result))
1066 {
1067 Py_BLOCK_THREADS
1068 PyErr_Format (PyExc_RuntimeError,
1069 "LZ4F_decompress failed with code: %s",
1070 LZ4F_getErrorName (result));
1071 PyMem_Free (destination);
1072 return NULL;
1073 }
1074
1075 destination_written += destination_write;
1076 source_cursor += source_read;
1077 source_read = source_end - source_cursor;
1078
1079 if (result == 0)
1080 {
1081 /* We've reached the end of the frame. */
1082 end_of_frame = 1;
1083 break;
1084 }
1085 else if (source_cursor == source_end)
1086 {
1087 /* We've reached end of input. */
1088 break;
1089 }
1090 else if (destination_written == destination_size)
1091 {
1092 /* Destination buffer is full. So, stop decompressing if
1093 max_length is set. Otherwise expand the destination
1094 buffer. */
1095 if (max_length >= (Py_ssize_t) 0)
1096 {
1097 break;
1098 }
1099 else
1100 {
1101 /* Expand the destination buffer. We've tried various strategies
1102 here to estimate the compression ratio so far and adjust the
1103 buffer size accordingly. However, that grows the buffer too
1104 slowly. The best choices found were to either double the buffer
1105 size each time, or to grow faster by multiplying the buffer
1106 size by 2^N, where N is the number of resizes. We take the
1107 latter approach, though the former approach may actually be
1108 good enough in practice. */
1109 char * buff;
1110
1111 resize_factor *= 2;
1112 destination_size *= resize_factor;
1113
1114 Py_BLOCK_THREADS
1115 buff = PyMem_Realloc (destination, destination_size);
1116 if (buff == NULL)
1117 {
1118 PyErr_SetString (PyExc_RuntimeError,
1119 "Failed to resize buffer");
1120 return NULL;
1121 }
1122 else
1123 {
1124 destination = buff;
1125 }
1126 Py_UNBLOCK_THREADS
1127 }
1128 }
1129 /* Data still remaining to be decompressed, so increment the destination
1130 cursor location, and reset destination_write ready for the next
1131 iteration. Important to re-initialize destination_cursor here (as
1132 opposed to simply incrementing it) so we're pointing to the realloc'd
1133 memory location. */
1134 destination_cursor = destination + destination_written;
1135 destination_write = destination_size - destination_written;
1136 }
1137
1138 Py_END_ALLOW_THREADS
1139
1140 if (result > 0 && full_frame)
1141 {
1142 PyErr_Format (PyExc_RuntimeError,
1143 "Frame incomplete. LZ4F_decompress returned: %zu", result);
1144 PyMem_Free (destination);
1145 return NULL;
1146 }
1147
1148 if (LZ4F_isError (result))
1149 {
1150 PyErr_Format (PyExc_RuntimeError,
1151 "LZ4F_freeDecompressionContext failed with code: %s",
1152 LZ4F_getErrorName (result));
1153 PyMem_Free (destination);
1154 return NULL;
1155 }
1156
1157 if (return_bytearray)
1158 {
1159 py_destination = PyByteArray_FromStringAndSize (destination, (Py_ssize_t) destination_written);
1160 }
1161 else
1162 {
1163 py_destination = PyBytes_FromStringAndSize (destination, (Py_ssize_t) destination_written);
1164 }
1165
1166 PyMem_Free (destination);
1167
1168 if (py_destination == NULL)
1169 {
1170 return PyErr_NoMemory ();
1171 }
1172
1173 if (full_frame)
1174 {
1175 if (return_bytes_read)
1176 {
1177 return Py_BuildValue ("Ni",
1178 py_destination,
1179 source_cursor - source);
1180 }
1181 else
1182 {
1183 return py_destination;
1184 }
1185 }
1186 else
1187 {
1188 return Py_BuildValue ("NiO",
1189 py_destination,
1190 source_cursor - source,
1191 end_of_frame ? Py_True : Py_False);
1192 }
1193 }
1194
1195 /**************
1196 * decompress *
1197 **************/
1198 static PyObject *
1199 decompress (PyObject * Py_UNUSED (self), PyObject * args,
1200 PyObject * keywds)
1201 {
1202 LZ4F_dctx * context;
1203 LZ4F_errorCode_t result;
1204 Py_buffer py_source;
1205 char * source;
1206 size_t source_size;
1207 PyObject * ret;
1208 int return_bytearray = 0;
1209 int return_bytes_read = 0;
1210 static char *kwlist[] = { "data",
1211 "return_bytearray",
1212 "return_bytes_read",
1213 NULL
1214 };
1215
1216 if (!PyArg_ParseTupleAndKeywords (args, keywds, "y*|pp", kwlist,
1217 &py_source,
1218 &return_bytearray,
1219 &return_bytes_read
1220 ))
1221 {
1222 return NULL;
1223 }
1224
1225 Py_BEGIN_ALLOW_THREADS
1226 result = LZ4F_createDecompressionContext (&context, LZ4F_VERSION);
1227 if (LZ4F_isError (result))
1228 {
1229 LZ4F_freeDecompressionContext (context);
1230 Py_BLOCK_THREADS
1231 PyBuffer_Release(&py_source);
1232 PyErr_Format (PyExc_RuntimeError,
1233 "LZ4F_createDecompressionContext failed with code: %s",
1234 LZ4F_getErrorName (result));
1235 return NULL;
1236 }
1237 Py_END_ALLOW_THREADS
1238
1239 /* MSVC can't do pointer arithmetic on void * pointers, so cast to char * */
1240 source = (char *) py_source.buf;
1241 source_size = py_source.len;
1242
1243 ret = __decompress (context,
1244 source,
1245 source_size,
1246 -1,
1247 1,
1248 return_bytearray,
1249 return_bytes_read);
1250
1251 PyBuffer_Release(&py_source);
1252
1253 Py_BEGIN_ALLOW_THREADS
1254 LZ4F_freeDecompressionContext (context);
1255 Py_END_ALLOW_THREADS
1256
1257 return ret;
1258 }
1259
1260 /********************
1261 * decompress_chunk *
1262 ********************/
1263 static PyObject *
1264 decompress_chunk (PyObject * Py_UNUSED (self), PyObject * args,
1265 PyObject * keywds)
1266 {
1267 PyObject * py_context = NULL;
1268 PyObject * ret;
1269 LZ4F_dctx * context;
1270 Py_buffer py_source;
1271 char * source;
1272 size_t source_size;
1273 Py_ssize_t max_length = (Py_ssize_t) -1;
1274 int return_bytearray = 0;
1275 static char *kwlist[] = { "context",
1276 "data",
1277 "max_length",
1278 "return_bytearray",
1279 NULL
1280 };
1281
1282 if (!PyArg_ParseTupleAndKeywords (args, keywds, "Oy*|np", kwlist,
1283 &py_context,
1284 &py_source,
1285 &max_length,
1286 &return_bytearray
1287 ))
1288 {
1289 return NULL;
1290 }
1291
1292 context = (LZ4F_dctx *)
1293 PyCapsule_GetPointer (py_context, decompression_context_capsule_name);
1294
1295 if (!context)
1296 {
1297 PyBuffer_Release(&py_source);
1298 PyErr_SetString (PyExc_ValueError,
1299 "No valid decompression context supplied");
1300 return NULL;
1301 }
1302
1303 /* MSVC can't do pointer arithmetic on void * pointers, so cast to char * */
1304 source = (char *) py_source.buf;
1305 source_size = py_source.len;
1306
1307 ret = __decompress (context,
1308 source,
1309 source_size,
1310 max_length,
1311 0,
1312 return_bytearray,
1313 0);
1314
1315 PyBuffer_Release(&py_source);
1316
1317 return ret;
1318 }
1319
1320 PyDoc_STRVAR(
1321 create_compression_context__doc,
1322 "create_compression_context()\n" \
1323 "\n" \
1324 "Creates a compression context object.\n" \
1325 "\n" \
1326 "The compression object is required for compression operations.\n" \
1327 "\n" \
1328 "Returns:\n" \
1329 " cCtx: A compression context\n"
1330 );
1331
1332 #define COMPRESS_KWARGS_DOCSTRING \
1333 " block_size (int): Specifies the maximum blocksize to use.\n" \
1334 " Options:\n\n" \
1335 " - `lz4.frame.BLOCKSIZE_DEFAULT`: the lz4 library default\n" \
1336 " - `lz4.frame.BLOCKSIZE_MAX64KB`: 64 kB\n" \
1337 " - `lz4.frame.BLOCKSIZE_MAX256KB`: 256 kB\n" \
1338 " - `lz4.frame.BLOCKSIZE_MAX1MB`: 1 MB\n" \
1339 " - `lz4.frame.BLOCKSIZE_MAX4MB`: 4 MB\n\n" \
1340 " If unspecified, will default to `lz4.frame.BLOCKSIZE_DEFAULT`\n" \
1341 " which is currently equal to `lz4.frame.BLOCKSIZE_MAX64KB`.\n" \
1342 " block_linked (bool): Specifies whether to use block-linked\n" \
1343 " compression. If ``True``, the compression ratio is improved,\n" \
1344 " particularly for small block sizes. Default is ``True``.\n" \
1345 " compression_level (int): Specifies the level of compression used.\n" \
1346 " Values between 0-16 are valid, with 0 (default) being the\n" \
1347 " lowest compression (0-2 are the same value), and 16 the highest.\n" \
1348 " Values below 0 will enable \"fast acceleration\", proportional\n" \
1349 " to the value. Values above 16 will be treated as 16.\n" \
1350 " The following module constants are provided as a convenience:\n\n" \
1351 " - `lz4.frame.COMPRESSIONLEVEL_MIN`: Minimum compression (0, the\n" \
1352 " default)\n" \
1353 " - `lz4.frame.COMPRESSIONLEVEL_MINHC`: Minimum high-compression\n" \
1354 " mode (3)\n" \
1355 " - `lz4.frame.COMPRESSIONLEVEL_MAX`: Maximum compression (16)\n\n" \
1356 " content_checksum (bool): Specifies whether to enable checksumming\n" \
1357 " of the uncompressed content. If True, a checksum is stored at the\n" \
1358 " end of the frame, and checked during decompression. Default is\n" \
1359 " ``False``.\n" \
1360 " block_checksum (bool): Specifies whether to enable checksumming of\n" \
1361 " the uncompressed content of each block. If `True` a checksum of\n" \
1362 " the uncompressed data in each block in the frame is stored at\n\n" \
1363 " the end of each block. If present, these checksums will be used\n\n" \
1364 " to validate the data during decompression. The default is\n" \
1365 " ``False`` meaning block checksums are not calculated and stored.\n" \
1366 " This functionality is only supported if the underlying LZ4\n" \
1367 " library has version >= 1.8.0. Attempting to set this value\n" \
1368 " to ``True`` with a version of LZ4 < 1.8.0 will cause a\n" \
1369 " ``RuntimeError`` to be raised.\n" \
1370 " return_bytearray (bool): If ``True`` a ``bytearray`` object will be\n" \
1371 " returned. If ``False``, a string of bytes is returned. The default\n" \
1372 " is ``False``.\n" \
1373
1374 PyDoc_STRVAR(
1375 compress__doc,
1376 "compress(data, compression_level=0, block_size=0, content_checksum=0,\n" \
1377 "block_linked=True, store_size=True, return_bytearray=False)\n" \
1378 "\n" \
1379 "Compresses ``data`` returning the compressed data as a complete frame.\n" \
1380 "\n" \
1381 "The returned data includes a header and endmark and so is suitable\n" \
1382 "for writing to a file.\n" \
1383 "\n" \
1384 "Args:\n" \
1385 " data (str, bytes or buffer-compatible object): data to compress\n" \
1386 "\n" \
1387 "Keyword Args:\n" \
1388 COMPRESS_KWARGS_DOCSTRING \
1389 " store_size (bool): If ``True`` then the frame will include an 8-byte\n" \
1390 " header field that is the uncompressed size of data included\n" \
1391 " within the frame. Default is ``True``.\n" \
1392 "\n" \
1393 "Returns:\n" \
1394 " bytes or bytearray: Compressed data\n"
1395 );
1396 PyDoc_STRVAR
1397 (
1398 compress_begin__doc,
1399 "compress_begin(context, source_size=0, compression_level=0, block_size=0,\n" \
1400 "content_checksum=0, content_size=1, block_linked=0, frame_type=0,\n" \
1401 "auto_flush=1)\n" \
1402 "\n" \
1403 "Creates a frame header from a compression context.\n\n" \
1404 "Args:\n" \
1405 " context (cCtx): A compression context.\n\n" \
1406 "Keyword Args:\n" \
1407 COMPRESS_KWARGS_DOCSTRING \
1408 " auto_flush (bool): Enable or disable autoFlush. When autoFlush is disabled\n" \
1409 " the LZ4 library may buffer data internally until a block is full.\n" \
1410 " Default is ``False`` (autoFlush disabled).\n\n" \
1411 " source_size (int): This optionally specifies the uncompressed size\n" \
1412 " of the data to be compressed. If specified, the size will be stored\n" \
1413 " in the frame header for use during decompression. Default is ``True``\n" \
1414 " return_bytearray (bool): If ``True`` a bytearray object will be returned.\n" \
1415 " If ``False``, a string of bytes is returned. Default is ``False``.\n\n" \
1416 "Returns:\n" \
1417 " bytes or bytearray: Frame header.\n"
1418 );
1419
1420 #undef COMPRESS_KWARGS_DOCSTRING
1421
1422 PyDoc_STRVAR
1423 (
1424 compress_chunk__doc,
1425 "compress_chunk(context, data)\n" \
1426 "\n" \
1427 "Compresses blocks of data and returns the compressed data.\n" \
1428 "\n" \
1429 "The returned data should be concatenated with the data returned from\n" \
1430 "`lz4.frame.compress_begin` and any subsequent calls to\n" \
1431 "`lz4.frame.compress_chunk`.\n" \
1432 "\n" \
1433 "Args:\n" \
1434 " context (cCtx): compression context\n" \
1435 " data (str, bytes or buffer-compatible object): data to compress\n" \
1436 "\n" \
1437 "Keyword Args:\n" \
1438 " return_bytearray (bool): If ``True`` a bytearray object will be\n" \
1439 " returned. If ``False``, a string of bytes is returned. The\n" \
1440 " default is False.\n" \
1441 "\n" \
1442 "Returns:\n" \
1443 " bytes or bytearray: Compressed data.\n\n" \
1444 "Notes:\n" \
1445 " If auto flush is disabled (``auto_flush=False`` when calling\n" \
1446 " `lz4.frame.compress_begin`) this function may buffer and retain\n" \
1447 " some or all of the compressed data for future calls to\n" \
1448 " `lz4.frame.compress`.\n"
1449 );
1450
1451 PyDoc_STRVAR
1452 (
1453 compress_flush__doc,
1454 "compress_flush(context, end_frame=True, return_bytearray=False)\n" \
1455 "\n" \
1456 "Flushes any buffered data held in the compression context.\n" \
1457 "\n" \
1458 "This flushes any data buffed in the compression context, returning it as\n" \
1459 "compressed data. The returned data should be appended to the output of\n" \
1460 "previous calls to ``lz4.frame.compress_chunk``.\n" \
1461 "\n" \
1462 "The ``end_frame`` argument specifies whether or not the frame should be\n" \
1463 "ended. If this is ``True`` and end of frame marker will be appended to\n" \
1464 "the returned data. In this case, if ``content_checksum`` was ``True``\n" \
1465 "when calling `lz4.frame.compress_begin`, then a checksum of the uncompressed\n" \
1466 "data will also be included in the returned data.\n" \
1467 "\n" \
1468 "If the ``end_frame`` argument is ``True``, the compression context will be\n" \
1469 "reset and can be reused.\n" \
1470 "\n" \
1471 "Args:\n" \
1472 " context (cCtx): Compression context\n" \
1473 "\n" \
1474 "Keyword Args:\n" \
1475 " end_frame (bool): If ``True`` the frame will be ended. Default is\n" \
1476 " ``True``.\n" \
1477 " return_bytearray (bool): If ``True`` a ``bytearray`` object will\n" \
1478 " be returned. If ``False``, a ``bytes`` object is returned.\n" \
1479 " The default is ``False``.\n" \
1480 "\n" \
1481 "Returns:\n" \
1482 " bytes or bytearray: compressed data.\n" \
1483 "\n" \
1484 "Notes:\n" \
1485 " If ``end_frame`` is ``False`` but the underlying LZ4 library does not" \
1486 " support flushing without ending the frame, a ``RuntimeError`` will be\n" \
1487 " raised.\n"
1488 );
1489
1490 PyDoc_STRVAR
1491 (
1492 get_frame_info__doc,
1493 "get_frame_info(frame)\n\n" \
1494 "Given a frame of compressed data, returns information about the frame.\n" \
1495 "\n" \
1496 "Args:\n" \
1497 " frame (str, bytes or buffer-compatible object): LZ4 compressed frame\n" \
1498 "\n" \
1499 "Returns:\n" \
1500 " dict: Dictionary with keys:\n" \
1501 "\n" \
1502 " - ``block_size`` (int): the maximum size (in bytes) of each block\n" \
1503 " - ``block_size_id`` (int): identifier for maximum block size\n" \
1504 " - ``content_checksum`` (bool): specifies whether the frame\n" \
1505 " contains a checksum of the uncompressed content\n" \
1506 " - ``content_size`` (int): uncompressed size in bytes of\n" \
1507 " frame content\n" \
1508 " - ``block_linked`` (bool): specifies whether the frame contains\n" \
1509 " blocks which are independently compressed (``False``) or linked\n" \
1510 " linked (``True``)\n" \
1511 " - ``block_checksum`` (bool): specifies whether each block contains a\n" \
1512 " checksum of its contents\n" \
1513 " - ``skippable`` (bool): whether the block is skippable (``True``) or\n" \
1514 " not (``False``)\n"
1515 );
1516
1517 PyDoc_STRVAR
1518 (
1519 create_decompression_context__doc,
1520 "create_decompression_context()\n" \
1521 "\n" \
1522 "Creates a decompression context object.\n" \
1523 "\n" \
1524 "A decompression context is needed for decompression operations.\n" \
1525 "\n" \
1526 "Returns:\n" \
1527 " dCtx: A decompression context\n"
1528 );
1529
1530 PyDoc_STRVAR
1531 (
1532 reset_decompression_context__doc,
1533 "reset_decompression_context(context)\n" \
1534 "\n" \
1535 "Resets a decompression context object.\n" \
1536 "\n" \
1537 "This is useful for recovering from an error or for stopping an unfinished\n" \
1538 "decompression and starting a new one with the same context\n" \
1539 "\n" \
1540 "Args:\n" \
1541 " context (dCtx): A decompression context\n"
1542 );
1543
1544 PyDoc_STRVAR
1545 (
1546 decompress__doc,
1547 "decompress(data, return_bytearray=False, return_bytes_read=False)\n" \
1548 "\n" \
1549 "Decompresses a frame of data and returns it as a string of bytes.\n" \
1550 "\n" \
1551 "Args:\n" \
1552 " data (str, bytes or buffer-compatible object): data to decompress.\n" \
1553 " This should contain a complete LZ4 frame of compressed data.\n" \
1554 "\n" \
1555 "Keyword Args:\n" \
1556 " return_bytearray (bool): If ``True`` a bytearray object will be\n" \
1557 " returned. If ``False``, a string of bytes is returned. The\n" \
1558 " default is ``False``.\n" \
1559 " return_bytes_read (bool): If ``True`` then the number of bytes read\n" \
1560 " from ``data`` will also be returned. Default is ``False``\n" \
1561 "\n" \
1562 "Returns:\n" \
1563 " bytes/bytearray or tuple: Uncompressed data and optionally the number" \
1564 " of bytes read\n" \
1565 "\n" \
1566 " If the ``return_bytes_read`` argument is ``True`` this function\n" \
1567 " returns a tuple consisting of:\n" \
1568 "\n" \
1569 " - bytes or bytearray: Uncompressed data\n" \
1570 " - int: Number of bytes consumed from ``data``\n"
1571 );
1572
1573 PyDoc_STRVAR
1574 (
1575 decompress_chunk__doc,
1576 "decompress_chunk(context, data, max_length=-1)\n" \
1577 "\n" \
1578 "Decompresses part of a frame of compressed data.\n" \
1579 "\n" \
1580 "The returned uncompressed data should be concatenated with the data\n" \
1581 "returned from previous calls to `lz4.frame.decompress_chunk`\n" \
1582 "\n" \
1583 "Args:\n" \
1584 " context (dCtx): decompression context\n" \
1585 " data (str, bytes or buffer-compatible object): part of a LZ4\n" \
1586 " frame of compressed data\n" \
1587 "\n" \
1588 "Keyword Args:\n" \
1589 " max_length (int): if non-negative this specifies the maximum number\n" \
1590 " of bytes of uncompressed data to return. Default is ``-1``.\n" \
1591 " return_bytearray (bool): If ``True`` a bytearray object will be\n" \
1592 " returned.If ``False``, a string of bytes is returned. The\n" \
1593 " default is ``False``.\n" \
1594 "\n" \
1595 "Returns:\n" \
1596 " tuple: uncompressed data, bytes read, end of frame indicator\n" \
1597 "\n" \
1598 " This function returns a tuple consisting of:\n" \
1599 "\n" \
1600 " - The uncompressed data as a ``bytes`` or ``bytearray`` object\n" \
1601 " - The number of bytes consumed from input ``data`` as an ``int``\n" \
1602 " - The end of frame indicator as a ``bool``.\n" \
1603 "\n"
1604 "The end of frame indicator is ``True`` if the end of the compressed\n" \
1605 "frame has been reached, or ``False`` otherwise\n"
1606 );
1607
1608 static PyMethodDef module_methods[] =
1609 {
1610 {
1611 "create_compression_context", (PyCFunction) create_compression_context,
1612 METH_NOARGS, create_compression_context__doc
1613 },
1614 {
1615 "compress", (PyCFunction) compress,
1616 METH_VARARGS | METH_KEYWORDS, compress__doc
1617 },
1618 {
1619 "compress_begin", (PyCFunction) compress_begin,
1620 METH_VARARGS | METH_KEYWORDS, compress_begin__doc
1621 },
1622 {
1623 "compress_chunk", (PyCFunction) compress_chunk,
1624 METH_VARARGS | METH_KEYWORDS, compress_chunk__doc
1625 },
1626 {
1627 "compress_flush", (PyCFunction) compress_flush,
1628 METH_VARARGS | METH_KEYWORDS, compress_flush__doc
1629 },
1630 {
1631 "get_frame_info", (PyCFunction) get_frame_info,
1632 METH_VARARGS | METH_KEYWORDS, get_frame_info__doc
1633 },
1634 {
1635 "create_decompression_context", (PyCFunction) create_decompression_context,
1636 METH_NOARGS, create_decompression_context__doc
1637 },
1638 {
1639 "reset_decompression_context", (PyCFunction) reset_decompression_context,
1640 METH_VARARGS | METH_KEYWORDS, reset_decompression_context__doc
1641 },
1642 {
1643 "decompress", (PyCFunction) decompress,
1644 METH_VARARGS | METH_KEYWORDS, decompress__doc
1645 },
1646 {
1647 "decompress_chunk", (PyCFunction) decompress_chunk,
1648 METH_VARARGS | METH_KEYWORDS, decompress_chunk__doc
1649 },
1650 {NULL, NULL, 0, NULL} /* Sentinel */
1651 };
1652
1653 PyDoc_STRVAR(lz4frame__doc,
1654 "A Python wrapper for the LZ4 frame protocol"
1655 );
1656
1657 static struct PyModuleDef moduledef =
1658 {
1659 PyModuleDef_HEAD_INIT,
1660 "_frame",
1661 lz4frame__doc,
1662 -1,
1663 module_methods
1664 };
1665
1666 PyMODINIT_FUNC
1667 PyInit__frame(void)
1668 {
1669 PyObject *module = PyModule_Create (&moduledef);
1670
1671 if (module == NULL)
1672 return NULL;
1673
1674 PyModule_AddIntConstant (module, "BLOCKSIZE_DEFAULT", LZ4F_default);
1675 PyModule_AddIntConstant (module, "BLOCKSIZE_MAX64KB", LZ4F_max64KB);
1676 PyModule_AddIntConstant (module, "BLOCKSIZE_MAX256KB", LZ4F_max256KB);
1677 PyModule_AddIntConstant (module, "BLOCKSIZE_MAX1MB", LZ4F_max1MB);
1678 PyModule_AddIntConstant (module, "BLOCKSIZE_MAX4MB", LZ4F_max4MB);
1679
1680 #ifdef Py_GIL_DISABLED
1681 PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED);
1682 #endif
1683
1684 return module;
1685 }