Debian Codegraph @

lz4/stream/_stream.c

raw symbols SCIP
1 /*
2 * Copyright (c) 2019, Samuel Martin
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 <math.h>
42 #include <lz4.h>
43 #include <lz4hc.h>
44 #include <stddef.h>
45 #include <stdio.h>
46
47 #if defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1600
48 /* MSVC 2008 and earlier lacks stdint.h */
49 typedef signed __int8 int8_t;
50 typedef signed __int16 int16_t;
51 typedef signed __int32 int32_t;
52 typedef signed __int64 int64_t;
53 typedef unsigned __int8 uint8_t;
54 typedef unsigned __int16 uint16_t;
55 typedef unsigned __int32 uint32_t;
56 typedef unsigned __int64 uint64_t;
57
58 #if !defined(UINT8_MAX)
59 #define UINT8_MAX 0xff
60 #endif
61 #if !defined(UINT16_MAX)
62 #define UINT16_MAX 0xffff
63 #endif
64 #if !defined(UINT32_MAX)
65 #define UINT32_MAX 0xffffffff
66 #endif
67 #if !defined(INT32_MAX)
68 #define INT32_MAX 0x7fffffff
69 #endif
70 #if !defined(CHAR_BIT)
71 #define CHAR_BIT 8
72 #endif
73
74 #else
75 /* Not MSVC, or MSVC 2010 or higher */
76 #include <stdint.h>
77 #endif /* _WIN32 && _MSC_VER && _MSC_VER < 1600 */
78
79 #define LZ4_VERSION_NUMBER_1_9_0 10900
80
81 static const char * stream_context_capsule_name = "_stream.LZ4S_ctx";
82
83 typedef enum {
84 DOUBLE_BUFFER,
85 RING_BUFFER,
86
87 BUFFER_STRATEGY_COUNT /* must be the last entry */
88 } buffer_strategy_e;
89
90 typedef enum {
91 COMPRESS,
92 DECOMPRESS,
93 } direction_e;
94
95 typedef enum {
96 DEFAULT,
97 FAST,
98 HIGH_COMPRESSION,
99 } compression_type_e;
100
101
102 /* Forward declarations */
103 static PyObject * LZ4StreamError;
104
105 #define DOUBLE_BUFFER_PAGE_COUNT (2)
106
107 #define DOUBLE_BUFFER_INDEX_MIN (0)
108 #define DOUBLE_BUFFER_INDEX_INVALID (-1)
109
110 #define _GET_MAX_UINT(byte_depth, type) (type)( ( 1ULL << ( CHAR_BIT * (byte_depth) ) ) - 1 )
111 #define _GET_MAX_UINT32(byte_depth) _GET_MAX_UINT((byte_depth), uint32_t)
112
113 typedef struct {
114 char * buf;
115 unsigned int len;
116 } buffer_t;
117
118 /* forward declaration */
119 typedef struct stream_context_t stream_context_t;
120
121 typedef struct {
122 /**
123 * Release buffer strategy's resources.
124 *
125 * \param[inout] context Stream context.
126 */
127 void (*release_resources) (stream_context_t *context);
128
129 /**
130 * Reserve buffer strategy's resources.
131 *
132 * \param[inout] context Stream context.
133 * \param[in] buffer_size Base buffer size to allocate and initialize.
134 *
135 * \return 0 on success, non-0 otherwise
136 */
137 int (*reserve_resources) (stream_context_t * context, unsigned int buffer_size);
138
139 /**
140 * Return a pointer on the work buffer.
141 *
142 * \param[inout] context Stream context.
143 *
144 * \return A pointer on the work buffer.
145 */
146 char * (*get_work_buffer) (const stream_context_t * context);
147
148 /**
149 * Return the length of (available space in) the work buffer.
150 *
151 * \param[inout] context Stream context.
152 *
153 * \return The length of the work buffer.
154 */
155 unsigned int (*get_work_buffer_size) (const stream_context_t * context);
156
157 /**
158 * Return the length of the output buffer.
159 *
160 * \param[inout] context Stream context.
161 *
162 * \return The length the output buffer.
163 */
164 unsigned int (*get_dest_buffer_size) (const stream_context_t * context);
165
166 /**
167 * Update the stream context at the end of the LZ4 operation (a block compression or
168 * decompression).
169 *
170 * \param[inout] context Stream context.
171 *
172 * \return 0 on success, non-0 otherwise
173 */
174 int (*update_context_after_process) (stream_context_t * context);
175 } strategy_ops_t;
176
177 struct stream_context_t {
178 /* Buffer strategy resources */
179 struct {
180 strategy_ops_t * ops;
181 union {
182 /* Double-buffer */
183 struct {
184 char * buf;
185 unsigned int page_size;
186 char * pages[DOUBLE_BUFFER_PAGE_COUNT];
187 int index;
188 } double_buffer;
189
190 /* Ring-buffer (not implemented) */
191 struct {
192 char * buf;
193 unsigned int size;
194 } ring_buffer;
195 } data;
196 } strategy;
197
198 buffer_t output;
199
200 /* LZ4 state */
201 union {
202 union {
203 LZ4_stream_t * fast;
204 LZ4_streamHC_t * hc;
205 } compress;
206 LZ4_streamDecode_t * decompress;
207 void * context;
208 } lz4_state;
209
210 /* LZ4 configuration */
211 struct {
212 int acceleration;
213 int compression_level;
214 int store_comp_size;
215 int return_bytearray;
216 direction_e direction;
217 compression_type_e comp;
218 } config;
219 };
220
221
222 #ifndef PyCapsule_Type
223 #define _PyCapsule_get_context(py_ctx) \
224 ((stream_context_t *) PyCapsule_GetPointer((py_ctx), stream_context_capsule_name))
225 #else
226 /* Compatibility with 2.6 via capsulethunk. */
227 #define _PyCapsule_get_context(py_ctx) \
228 ((stream_context_t *) (py_ctx))
229 #endif
230
231
232 static inline void
233 store_le8 (char * c, uint8_t x)
234 {
235 c[0] = x & 0xff;
236 }
237
238
239 /*************************
240 * block content helpers *
241 *************************/
242 static inline uint8_t
243 load_le8 (const char * c)
244 {
245 const uint8_t * d = (const uint8_t *) c;
246 return d[0];
247 }
248
249 static inline void
250 store_le16 (char * c, uint16_t x)
251 {
252 c[0] = x & 0xff;
253 c[1] = (x >> 8) & 0xff;
254 }
255
256 static inline uint16_t
257 load_le16 (const char * c)
258 {
259 const uint8_t * d = (const uint8_t *) c;
260 return (d[0] | (d[1] << 8));
261 }
262
263 static inline void
264 store_le32 (char * c, uint32_t x)
265 {
266 c[0] = x & 0xff;
267 c[1] = (x >> 8) & 0xff;
268 c[2] = (x >> 16) & 0xff;
269 c[3] = (x >> 24) & 0xff;
270 }
271
272 static inline uint32_t
273 load_le32 (const char * c)
274 {
275 const uint8_t * d = (const uint8_t *) c;
276 return (d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24));
277 }
278
279 static inline int
280 load_block_length (int block_length_size, const char *buf)
281 {
282 int block_length = -1;
283 switch (block_length_size)
284 {
285 case 1:
286 block_length = load_le8 (buf);
287 break;
288
289 case 2:
290 block_length = load_le16 (buf);
291 break;
292
293 case 4:
294 block_length = load_le32 (buf);
295 break;
296
297 case 0:
298 /* fallthrough */
299 default:
300 break;
301 }
302
303 return block_length;
304 }
305
306 static inline int
307 store_block_length (int block_length, int block_length_size, char * buf)
308 {
309 int status = 1;
310
311 switch (block_length_size)
312 {
313 case 0: /* do nothing */
314 break;
315
316 case 1:
317 {
318 if (block_length > UINT8_MAX)
319 {
320 status = 0;
321 break;
322 }
323 store_le8 (buf, (uint8_t) (block_length & UINT8_MAX));
324 }
325 break;
326
327 case 2:
328 {
329 if (block_length > UINT16_MAX)
330 {
331 status = 0;
332 break;
333 }
334 store_le16 (buf, (uint16_t) (block_length & UINT16_MAX));
335 }
336 break;
337
338 case 4:
339 {
340 if (block_length > INT32_MAX)
341 {
342 status = 0;
343 break;
344 }
345 store_le32 (buf, (uint32_t) (block_length & UINT32_MAX));
346 }
347 break;
348
349 default: /* unsupported cases */
350 status = 0;
351 break;
352 }
353
354 if (status != 1)
355 {
356 PyErr_SetString (LZ4StreamError, "Compressed stream size too large");
357 }
358
359 return status;
360 }
361
362
363 /***************
364 * LZ4 helpers *
365 ***************/
366 static inline uint32_t
367 get_compress_bound(uint32_t input_size)
368 {
369 /* result of LZ4_compressBound is null or positive */
370 return (uint32_t)LZ4_compressBound(input_size);
371 }
372
373
374 static inline uint32_t
375 get_input_bound(uint32_t compress_max_size)
376 {
377 uint64_t isize = 0;
378 uint64_t csize = (uint64_t) compress_max_size;
379
380 /* Reversing the LZ4_COMPRESSBOUND macro gives:
381 * isize = ((csize - 16) * 255) / 256
382 * = (((csize - 16) * 256) - (csize - 16)) / 256
383 * = ((csize * 256) - (16 * 256) - (csize - 16)) / 256
384 * = ((csize << 8) - (16 << 8) - csize + 16) >> 8
385 * = ((csize << 8) - csize + 16 - (16 << 8)) >> 8
386 * = ((csize << 8) - csize - 4080) >> 8
387 *
388 * Notes:
389 * - Using 64-bit long integer for intermediate computation to avoid any
390 * truncation when shifting left large csize values.
391 * - Due to the round integer approximation, running the following
392 * calculation can give a non-null result:
393 * result = n - _LZ4_inputBound( _LZ4_compressBound( n ) )
394 * but in all cases, this difference is between 0 and 1.
395 * Thus, the valid maximal input size returned by this funtcion is
396 * incremented by 1 to avoid any buffer overflow in case of decompression
397 * in a dynamically allocated buffer.
398 * - For small compressed length (shorter than 16 bytes), make sure a
399 * non-null size is returned.
400 */
401 if (csize < 16)
402 {
403 csize = 17;
404 }
405
406 if (csize <= get_compress_bound (LZ4_MAX_INPUT_SIZE))
407 {
408 isize = ((csize << 8) - csize - 4080) >> 8;
409
410 if (isize > (uint32_t)LZ4_MAX_INPUT_SIZE)
411 {
412 isize = 0;
413 }
414 else
415 {
416 isize += 1;
417 }
418 }
419
420 return (uint32_t)(isize & UINT32_MAX);
421 }
422
423
424 /**************************************
425 * LZ4 version-compatibility wrappers *
426 **************************************/
427 #if defined (__GNUC__)
428 /* Runtime detection of the support of new functions in the LZ4 API
429 * (old functions remain available but are deprecated and will trigger
430 * compilation warnings.
431 *
432 * Declare weak symbols on the required functions provided by recent versions
433 * of the library.
434 * This way, these symbols will always be available - NULL if the (old version
435 * of the) library does not define them.
436 */
437
438 /* Function introduced in LZ4 >= 1.9.0 */
439 __attribute__ ((weak)) void
440 LZ4_resetStreamHC_fast (LZ4_streamHC_t* streamHCPtr, int compressionLevel);
441
442 /* Function introduced in LZ4 >= 1.8.2 */
443 __attribute__ ((weak)) void
444 LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
445
446 #else
447 /* Assuming the bundled LZ4 library sources are always used, so meet the
448 * LZ4 minimal version requirements.
449 */
450 #endif
451
452 static inline void reset_stream (LZ4_stream_t* streamPtr)
453 {
454 if (LZ4_versionNumber () >= LZ4_VERSION_NUMBER_1_9_0)
455 {
456 if (LZ4_resetStream_fast)
457 {
458 LZ4_resetStream_fast (streamPtr);
459 }
460 else
461 {
462 PyErr_SetString (PyExc_RuntimeError,
463 "Inconsistent LZ4 library version/available APIs");
464 }
465 }
466 else
467 {
468 LZ4_resetStream (streamPtr);
469 }
470 }
471
472
473 static inline void reset_stream_hc (LZ4_streamHC_t* streamHCPtr, int compressionLevel)
474 {
475 if (LZ4_versionNumber () >= LZ4_VERSION_NUMBER_1_9_0)
476 {
477 if (LZ4_resetStreamHC_fast)
478 {
479 LZ4_resetStreamHC_fast (streamHCPtr, compressionLevel);
480 }
481 else
482 {
483 PyErr_SetString (PyExc_RuntimeError,
484 "Inconsistent LZ4 library version/available APIs");
485 }
486 }
487 else
488 {
489 LZ4_resetStreamHC (streamHCPtr, compressionLevel);
490 }
491 }
492
493
494 /*************************
495 * Double-buffer helpers *
496 *************************/
497 static int
498 double_buffer_update_index (stream_context_t * context)
499 {
500 #if DOUBLE_BUFFER_PAGE_COUNT != 2
501 #error "DOUBLE_BUFFER_PAGE_COUNT must be 2."
502 #endif /* DOUBLE_BUFFER_PAGE_COUNT != 2 */
503 context->strategy.data.double_buffer.index = (context->strategy.data.double_buffer.index + 1) & 0x1; /* modulo 2 */
504
505 return 0;
506 }
507
508 static char *
509 double_buffer_get_compression_page (const stream_context_t * context)
510 {
511 return context->strategy.data.double_buffer.pages[context->strategy.data.double_buffer.index];
512 }
513
514 static void
515 double_buffer_release_resources (stream_context_t * context)
516 {
517 unsigned int i;
518 for (i = DOUBLE_BUFFER_INDEX_MIN;
519 i < (DOUBLE_BUFFER_INDEX_MIN + DOUBLE_BUFFER_PAGE_COUNT);
520 ++i)
521 {
522 context->strategy.data.double_buffer.pages[i] = NULL;
523 }
524
525 if (context->strategy.data.double_buffer.buf != NULL)
526 {
527 PyMem_Free (context->strategy.data.double_buffer.buf);
528 }
529 context->strategy.data.double_buffer.buf = NULL;
530 context->strategy.data.double_buffer.index = DOUBLE_BUFFER_INDEX_INVALID;
531 context->strategy.data.double_buffer.page_size = 0;
532 }
533
534 static int
535 double_buffer_reserve_resources (stream_context_t * context, unsigned int buffer_size)
536 {
537 int status = 0;
538 unsigned int i;
539
540 context->strategy.data.double_buffer.page_size = buffer_size;
541 context->strategy.data.double_buffer.buf = PyMem_Malloc (buffer_size * DOUBLE_BUFFER_PAGE_COUNT);
542
543 if (context->strategy.data.double_buffer.buf == NULL)
544 {
545 PyErr_Format (PyExc_MemoryError,
546 "Could not allocate double-buffer");
547 status = -1;
548 goto exit_now;
549 }
550
551 for (i = DOUBLE_BUFFER_INDEX_MIN;
552 i < (DOUBLE_BUFFER_INDEX_MIN + DOUBLE_BUFFER_PAGE_COUNT);
553 ++i)
554 {
555 context->strategy.data.double_buffer.pages[i] = context->strategy.data.double_buffer.buf +
556 (i * buffer_size);
557 }
558
559 context->strategy.data.double_buffer.index = DOUBLE_BUFFER_INDEX_MIN;
560
561 exit_now:
562 return status;
563 }
564
565 static unsigned int
566 double_buffer_get_work_buffer_size (const stream_context_t * context)
567 {
568 return context->strategy.data.double_buffer.page_size;
569 }
570
571 static unsigned int
572 double_buffer_get_dest_buffer_size (const stream_context_t * context)
573 {
574 unsigned int len;
575
576 if (context->config.direction == COMPRESS)
577 {
578 len = context->output.len;
579 }
580 else
581 {
582 len = context->strategy.data.double_buffer.page_size;
583 }
584
585 return len;
586 }
587
588
589 /****************************************
590 * Ring-buffer helpers: Not implemented *
591 ****************************************/
592 static void
593 ring_buffer_release_resources (stream_context_t * context)
594 {
595 (void) context; /* unused */
596
597 /* Not implemented (yet) */
598 PyErr_Format (PyExc_NotImplementedError,
599 "Buffer strategy not implemented: ring_buffer");
600
601 return;
602 }
603
604 static int
605 ring_buffer_reserve_resources (stream_context_t * context, unsigned int buffer_size)
606 {
607 (void) context; /* unused */
608 (void) buffer_size; /* unused */
609
610 /* Not implemented (yet) */
611 PyErr_Format (PyExc_NotImplementedError,
612 "Buffer strategy not implemented: ring_buffer");
613 return -1;
614 }
615
616 static unsigned int
617 ring_buffer_get_dest_buffer_size (const stream_context_t * context)
618 {
619 (void) context; /* unused */
620
621 /* Not implemented (yet) */
622 PyErr_Format (PyExc_NotImplementedError,
623 "Buffer strategy not implemented: ring_buffer");
624
625 return 0;
626 }
627
628 static unsigned int
629 ring_buffer_get_work_buffer_size (const stream_context_t * context)
630 {
631 (void) context; /* unused */
632
633 /* Not implemented (yet) */
634 PyErr_Format (PyExc_NotImplementedError,
635 "Buffer strategy not implemented: ring_buffer");
636
637 return 0;
638 }
639
640 static char *
641 ring_buffer_get_buffer_position (const stream_context_t * context)
642 {
643 (void) context; /* unused */
644
645 /* Not implemented (yet) */
646 PyErr_Format (PyExc_NotImplementedError,
647 "Buffer strategy not implemented: ring_buffer");
648
649 return NULL;
650 }
651
652 static int
653 ring_buffer_update_context (stream_context_t * context)
654 {
655 (void) context; /* unused */
656
657 /* Not implemented (yet) */
658 PyErr_Format (PyExc_NotImplementedError,
659 "Buffer strategy not implemented: ring_buffer");
660
661 return -1;
662 }
663
664
665 /**********************
666 * strategy operators *
667 **********************/
668 static strategy_ops_t strategy_ops[BUFFER_STRATEGY_COUNT] = {
669 /* [DOUBLE_BUFFER] = */
670 {
671 /* .release_resources */ double_buffer_release_resources,
672 /* .reserve_resources */ double_buffer_reserve_resources,
673 /* .get_work_buffer */ double_buffer_get_compression_page,
674 /* .get_work_buffer_size */ double_buffer_get_work_buffer_size,
675 /* .get_dest_buffer_size */ double_buffer_get_dest_buffer_size,
676 /* .update_context_after_process */ double_buffer_update_index,
677 },
678 /* [RING_BUFFER] = */
679 {
680 /* .release_resources */ ring_buffer_release_resources,
681 /* .reserve_resources */ ring_buffer_reserve_resources,
682 /* .get_work_buffer */ ring_buffer_get_buffer_position,
683 /* .get_work_buffer_size */ ring_buffer_get_work_buffer_size,
684 /* .get_dest_buffer_size */ ring_buffer_get_dest_buffer_size,
685 /* .update_context_after_process */ ring_buffer_update_context,
686 },
687 };
688
689
690 /*******************
691 * generic helpers *
692 *******************/
693 static void
694 destroy_context (stream_context_t * context)
695 {
696 if (context == NULL)
697 {
698 return;
699 }
700
701 /* Release lz4 state */
702 Py_BEGIN_ALLOW_THREADS
703 if (context->lz4_state.context != NULL)
704 {
705 if (context->config.direction == COMPRESS)
706 {
707 if (context->config.comp == HIGH_COMPRESSION)
708 {
709 LZ4_freeStreamHC (context->lz4_state.compress.hc);
710 }
711 else
712 {
713 LZ4_freeStream (context->lz4_state.compress.fast);
714 }
715 }
716 else /* context->config.direction == DECOMPRESS */
717 {
718 LZ4_freeStreamDecode (context->lz4_state.decompress);
719 }
720 }
721 Py_END_ALLOW_THREADS
722 context->lz4_state.context = NULL;
723
724 /* Release strategy resources */
725 if (context->strategy.ops != NULL)
726 {
727 context->strategy.ops->release_resources (context);
728 }
729 context->strategy.ops = NULL;
730
731 /* Release output buffer */
732 if (context->output.buf != NULL)
733 {
734 PyMem_Free (context->output.buf);
735 }
736 context->output.buf = NULL;
737 context->output.len = 0;
738
739 /* Release python memory */
740 PyMem_Free (context);
741 }
742
743 static void
744 destroy_py_context (PyObject * py_context)
745 {
746 if (py_context == NULL)
747 {
748 return;
749 }
750
751 destroy_context (_PyCapsule_get_context (py_context));
752 }
753
754
755 /**************
756 * Python API *
757 **************/
758 static PyObject *
759 _create_context (PyObject * Py_UNUSED (self), PyObject * args, PyObject * kwds)
760 {
761 stream_context_t * context = NULL;
762
763 const char * direction = "";
764 const char * strategy_name = "";
765 unsigned int buffer_size;
766
767 buffer_strategy_e strategy = BUFFER_STRATEGY_COUNT;
768 const char * mode = "default";
769 int acceleration = 1;
770 int compression_level = 9;
771 int store_comp_size = 4;
772 int return_bytearray = 0;
773 Py_buffer dict = { NULL, NULL, };
774
775 int status = 0;
776 unsigned int total_size = 0;
777 uint32_t store_max_size;
778
779 static char * argnames[] = {
780 "strategy",
781 "direction",
782 "buffer_size",
783 "mode",
784 "acceleration",
785 "compression_level",
786 "return_bytearray",
787 "store_comp_size",
788 "dictionary",
789 NULL
790 };
791
792 if (!PyArg_ParseTupleAndKeywords (args, kwds, "ssI|sIIpIz*", argnames,
793 &strategy_name, &direction, &buffer_size,
794 &mode, &acceleration, &compression_level, &return_bytearray,
795 &store_comp_size, &dict))
796 {
797 goto abort_now;
798 }
799
800 /* Sanity checks on arguments */
801 if (dict.len > INT_MAX)
802 {
803 PyErr_Format (PyExc_OverflowError,
804 "Dictionary too large for LZ4 API");
805 goto abort_now;
806 }
807
808 /* Input max length limited to 0x7E000000 (2 113 929 216 bytes < 2GiB).
809 * https://github.com/lz4/lz4/blob/dev/lib/lz4.h#L161
810 *
811 * So, restrict the block length bitwise to 32 (signed 32 bit integer). */
812 if ((store_comp_size != 0) && (store_comp_size != 1) &&
813 (store_comp_size != 2) && (store_comp_size != 4))
814 {
815 PyErr_Format (PyExc_ValueError,
816 "Invalid store_comp_size, valid values: 0, 1, 2 or 4");
817 goto abort_now;
818 }
819
820 context = (stream_context_t *) PyMem_Malloc (sizeof (stream_context_t));
821 if (context == NULL)
822 {
823 PyErr_NoMemory ();
824 goto abort_now;
825 }
826
827 memset (context, 0x00, sizeof (stream_context_t));
828
829 /* Set buffer strategy */
830 if (!strncmp (strategy_name, "double_buffer", sizeof ("double_buffer")))
831 {
832 strategy = DOUBLE_BUFFER;
833 }
834 else if (!strncmp (strategy_name, "ring_buffer", sizeof ("ring_buffer")))
835 {
836 strategy = RING_BUFFER;
837 }
838 else
839 {
840 PyErr_Format (PyExc_ValueError,
841 "Invalid strategy argument: %s. Must be one of: double_buffer, ring_buffer",
842 strategy_name);
843 goto abort_now;
844 }
845
846 /* Set direction */
847 if (!strncmp (direction, "compress", sizeof ("compress")))
848 {
849 context->config.direction = COMPRESS;
850 }
851 else if (!strncmp (direction, "decompress", sizeof ("decompress")))
852 {
853 context->config.direction = DECOMPRESS;
854 }
855 else
856 {
857 PyErr_Format (PyExc_ValueError,
858 "Invalid direction argument: %s. Must be one of: compress, decompress",
859 direction);
860 goto abort_now;
861 }
862
863 /* Set compression mode */
864 if (!strncmp (mode, "default", sizeof ("default")))
865 {
866 context->config.comp = DEFAULT;
867 }
868 else if (!strncmp (mode, "fast", sizeof ("fast")))
869 {
870 context->config.comp = FAST;
871 }
872 else if (!strncmp (mode, "high_compression", sizeof ("high_compression")))
873 {
874 context->config.comp = HIGH_COMPRESSION;
875 }
876 else
877 {
878 PyErr_Format (PyExc_ValueError,
879 "Invalid mode argument: %s. Must be one of: default, fast, high_compression",
880 mode);
881 goto abort_now;
882 }
883
884 /* Initialize the output buffer
885 *
886 * In out-of-band block size case, use a best-effort strategy for scaling
887 * buffers.
888 */
889 if (store_comp_size == 0)
890 {
891 store_max_size = _GET_MAX_UINT32(4);
892 }
893 else
894 {
895 store_max_size = _GET_MAX_UINT32(store_comp_size);
896 }
897
898 if (context->config.direction == COMPRESS)
899 {
900 context->output.len = get_compress_bound (buffer_size);
901 total_size = context->output.len + store_comp_size;
902
903 if (context->output.len == 0)
904 {
905 PyErr_Format (PyExc_ValueError,
906 "Invalid buffer_size argument: %u. Cannot define output buffer size. "
907 "Must be lesser or equal to %u",
908 buffer_size, LZ4_MAX_INPUT_SIZE);
909 goto abort_now;
910 }
911
912 /* Assert the output buffer size and the store_comp_size values are consistent */
913 if (context->output.len > store_max_size)
914 {
915 /* The maximal/"worst case" compressed data length cannot fit in the
916 * store_comp_size bytes. */
917 PyErr_Format (LZ4StreamError,
918 "Inconsistent buffer_size/store_comp_size values. "
919 "Maximal compressed length (%u) cannot fit in a %u byte-long integer",
920 buffer_size, store_comp_size);
921 goto abort_now;
922 }
923 }
924 else /* context->config.direction == DECOMPRESS */
925 {
926 if (store_max_size > LZ4_MAX_INPUT_SIZE)
927 {
928 store_max_size = LZ4_MAX_INPUT_SIZE;
929 }
930
931 context->output.len = buffer_size;
932 total_size = context->output.len;
933
934 /* Here we cannot assert the maximal theoretical decompressed chunk length
935 * will fit in one page of the double_buffer, i.e.:
936 * assert( !(double_buffer.page_size < _LZ4_inputBound(store_max_size)) )
937 *
938 * Doing such a check would require aligning the page_size on the maximal
939 * value of the store_comp_size prefix, i.e.:
940 * page_size = 256B if store_comp_size == 1
941 * page_size = 64KB if store_comp_size == 2
942 * page_size = 4GB if store_comp_size == 4
943 *
944 * This constraint is too strict, so is not implemented.
945 *
946 * On the other hand, the compression logic tells the page size cannot be
947 * larger than the maximal value fitting in store_comp_size bytes.
948 * So here, the check could be checking the page_size is smaller or equal
949 * to the maximal decompressed chunk length, i.e.:
950 * assert( !(double_buffer.page_size > _LZ4_inputBound(store_max_size)) )
951 *
952 * But this check is not really relevant and could bring other limitations.
953 *
954 * So, on the decompression case, no check regarding the page_size and the
955 * store_comp_size values can reliably be done during the LZ4 context
956 * initialization, they will be deferred in the decompression process.
957 */
958 }
959
960 /* Set all remaining settings in the context */
961 context->config.store_comp_size = store_comp_size;
962 context->config.acceleration = acceleration;
963 context->config.compression_level = compression_level;
964 context->config.return_bytearray = !!return_bytearray;
965
966 /* Set internal resources related to the buffer strategy */
967 context->strategy.ops = &strategy_ops[strategy];
968
969 status = context->strategy.ops->reserve_resources (context, buffer_size);
970 if (status != 0)
971 {
972 /* Python exception already set in the strategy's resource creation helper */
973 goto abort_now;
974 }
975
976 /* Set output buffer */
977 context->output.buf = PyMem_Malloc (total_size * sizeof (* (context->output.buf)));
978 if (context->output.buf == NULL)
979 {
980 PyErr_Format (PyExc_MemoryError,
981 "Could not allocate output buffer");
982 goto abort_now;
983 }
984
985 /* Initialize lz4 state */
986 if (context->config.direction == COMPRESS)
987 {
988 if (context->config.comp == HIGH_COMPRESSION)
989 {
990 context->lz4_state.compress.hc = LZ4_createStreamHC ();
991 if (context->lz4_state.compress.hc == NULL)
992 {
993 PyErr_Format (PyExc_MemoryError,
994 "Could not create LZ4 state");
995 goto abort_now;
996 }
997
998 reset_stream_hc (context->lz4_state.compress.hc, context->config.compression_level);
999
1000 if (dict.len > 0)
1001 {
1002 LZ4_loadDictHC (context->lz4_state.compress.hc, dict.buf, dict.len);
1003 }
1004 }
1005 else
1006 {
1007 context->lz4_state.compress.fast = LZ4_createStream ();
1008 if (context->lz4_state.compress.fast == NULL)
1009 {
1010 PyErr_Format (PyExc_MemoryError,
1011 "Could not create LZ4 state");
1012 goto abort_now;
1013 }
1014
1015 reset_stream (context->lz4_state.compress.fast);
1016
1017 if (dict.len > 0)
1018 {
1019 LZ4_loadDict (context->lz4_state.compress.fast, dict.buf, dict.len);
1020 }
1021 }
1022 }
1023 else /* context->config.direction == DECOMPRESS */
1024 {
1025 context->lz4_state.decompress = LZ4_createStreamDecode ();
1026 if (context->lz4_state.decompress == NULL)
1027 {
1028 PyErr_Format (PyExc_MemoryError,
1029 "Could not create LZ4 state");
1030 goto abort_now;
1031 }
1032
1033 if (!LZ4_setStreamDecode (context->lz4_state.decompress, dict.buf, dict.len))
1034 {
1035 PyErr_Format (PyExc_RuntimeError,
1036 "Could not initialize LZ4 state");
1037 LZ4_freeStreamDecode (context->lz4_state.decompress);
1038 goto abort_now;
1039 }
1040 }
1041
1042 PyBuffer_Release (&dict);
1043
1044 return PyCapsule_New (context, stream_context_capsule_name, destroy_py_context);
1045
1046 abort_now:
1047 if (dict.buf != NULL)
1048 {
1049 PyBuffer_Release (&dict);
1050 }
1051 destroy_context (context);
1052
1053 return NULL;
1054 }
1055
1056 static PyObject *
1057 _compress_bound (PyObject * Py_UNUSED (self), PyObject * args)
1058 {
1059 PyObject * py_dest = NULL;
1060 uint32_t input_size;
1061
1062
1063 /* Positional arguments: input_size
1064 * Keyword arguments : none
1065 */
1066 if (!PyArg_ParseTuple (args, "OI", &input_size))
1067 {
1068 goto exit_now;
1069 }
1070
1071 py_dest = PyLong_FromUnsignedLong (get_compress_bound (input_size));
1072
1073 if (py_dest == NULL)
1074 {
1075 PyErr_NoMemory ();
1076 }
1077
1078 exit_now:
1079 return py_dest;
1080 }
1081
1082 static PyObject *
1083 _input_bound (PyObject * Py_UNUSED (self), PyObject * args)
1084 {
1085 PyObject * py_dest = NULL;
1086 uint32_t compress_max_size;
1087
1088 /* Positional arguments: compress_max_size
1089 * Keyword arguments : none
1090 */
1091 if (!PyArg_ParseTuple (args, "I", &compress_max_size))
1092 {
1093 goto exit_now;
1094 }
1095
1096 py_dest = PyLong_FromUnsignedLong (get_input_bound (compress_max_size));
1097
1098 if (py_dest == NULL)
1099 {
1100 PyErr_NoMemory ();
1101 }
1102
1103 exit_now:
1104 return py_dest;
1105 }
1106
1107 static inline int
1108 _compress_generic (stream_context_t * lz4_ctxt, char * source, int source_size,
1109 char * dest, int dest_size)
1110 {
1111 int comp_len;
1112
1113 if (lz4_ctxt->config.comp == HIGH_COMPRESSION)
1114 {
1115 LZ4_streamHC_t * lz4_state = lz4_ctxt->lz4_state.compress.hc;
1116
1117 comp_len = LZ4_compress_HC_continue (lz4_state, source, dest, source_size, dest_size);
1118 }
1119 else
1120 {
1121 LZ4_stream_t * lz4_state = lz4_ctxt->lz4_state.compress.fast;
1122 int acceleration = (lz4_ctxt->config.comp != FAST)
1123 ? 1 /* defaults */
1124 : lz4_ctxt->config.acceleration;
1125
1126 comp_len = LZ4_compress_fast_continue (lz4_state, source, dest, source_size, dest_size,
1127 acceleration);
1128 }
1129
1130 return comp_len;
1131 }
1132
1133 #ifdef inline
1134 #undef inline
1135 #endif
1136
1137 static PyObject *
1138 _compress (PyObject * Py_UNUSED (self), PyObject * args)
1139 {
1140 stream_context_t * context = NULL;
1141 PyObject * py_context = NULL;
1142 PyObject * py_dest = NULL;
1143 int output_size;
1144 Py_buffer source = { NULL, NULL, };
1145
1146 /* Positional arguments: capsule_context, source
1147 * Keyword arguments : none
1148 */
1149 if (!PyArg_ParseTuple (args, "Oy*", &py_context, &source))
1150 {
1151 goto exit_now;
1152 }
1153
1154 context = _PyCapsule_get_context (py_context);
1155 if ((context == NULL) || (context->lz4_state.context == NULL))
1156 {
1157 PyErr_SetString (PyExc_ValueError, "No valid LZ4 stream context supplied");
1158 goto exit_now;
1159 }
1160
1161 if (source.len > context->strategy.ops->get_work_buffer_size (context))
1162 {
1163 PyErr_SetString (PyExc_OverflowError,
1164 "Input too large for LZ4 API");
1165 goto exit_now;
1166 }
1167
1168 memcpy (context->strategy.ops->get_work_buffer (context), source.buf, source.len);
1169
1170 Py_BEGIN_ALLOW_THREADS
1171
1172 output_size = _compress_generic (context,
1173 context->strategy.ops->get_work_buffer (context),
1174 source.len,
1175 context->output.buf + context->config.store_comp_size,
1176 context->output.len);
1177
1178 Py_END_ALLOW_THREADS
1179
1180 if (output_size <= 0)
1181 {
1182 /* No error code set in output_size! */
1183 PyErr_SetString (LZ4StreamError,
1184 "Compression failed");
1185 goto exit_now;
1186 }
1187
1188 if (!store_block_length (output_size, context->config.store_comp_size, context->output.buf))
1189 {
1190 PyErr_SetString (LZ4StreamError,
1191 "Compressed stream size too large");
1192 goto exit_now;
1193 }
1194
1195 output_size += context->config.store_comp_size;
1196
1197 if (context->config.return_bytearray)
1198 {
1199 py_dest = PyByteArray_FromStringAndSize (context->output.buf, (Py_ssize_t) output_size);
1200 }
1201 else
1202 {
1203 py_dest = PyBytes_FromStringAndSize (context->output.buf, (Py_ssize_t) output_size);
1204 }
1205
1206 if (py_dest == NULL)
1207 {
1208 PyErr_NoMemory ();
1209 goto exit_now;
1210 }
1211
1212 if (context->strategy.ops->update_context_after_process (context) != 0)
1213 {
1214 PyErr_Format (PyExc_RuntimeError, "Internal error");
1215 goto exit_now;
1216 }
1217
1218 exit_now:
1219 if (source.buf != NULL)
1220 {
1221 PyBuffer_Release (&source);
1222 }
1223
1224 return py_dest;
1225 }
1226
1227 static PyObject *
1228 _get_block (PyObject * Py_UNUSED (self), PyObject * args)
1229 {
1230 stream_context_t * context = NULL;
1231 PyObject * py_context = NULL;
1232 PyObject * py_dest = NULL;
1233 Py_buffer source = { NULL, NULL, };
1234 buffer_t block = { NULL, 0, };
1235
1236 /* Positional arguments: capsule_context, source
1237 * Keyword arguments : none
1238 */
1239
1240 if (!PyArg_ParseTuple (args, "Oy*", &py_context, &source))
1241 {
1242 goto exit_now;
1243 }
1244
1245 context = _PyCapsule_get_context (py_context);
1246 if ((context == NULL) || (context->lz4_state.context == NULL))
1247 {
1248 PyErr_SetString (PyExc_ValueError, "No valid LZ4 stream context supplied");
1249 goto exit_now;
1250 }
1251
1252 if (source.len > INT_MAX)
1253 {
1254 PyErr_Format (PyExc_OverflowError,
1255 "Input too large for LZ4 API");
1256 goto exit_now;
1257 }
1258
1259 if (context->config.store_comp_size == 0)
1260 {
1261 PyErr_Format (LZ4StreamError,
1262 "LZ4 context is configured for storing block size out-of-band");
1263 goto exit_now;
1264 }
1265
1266 if (source.len < context->config.store_comp_size)
1267 {
1268 PyErr_Format (LZ4StreamError,
1269 "Invalid source, too small for holding any block");
1270 goto exit_now;
1271 }
1272
1273 block.buf = (char *) source.buf + context->config.store_comp_size;
1274 block.len = load_block_length (context->config.store_comp_size, source.buf);
1275
1276 if ((source.len - context->config.store_comp_size) < block.len)
1277 {
1278 PyErr_Format (LZ4StreamError,
1279 "Requested input size (%d) larger than source size (%ld)",
1280 block.len, (source.len - context->config.store_comp_size));
1281 goto exit_now;
1282 }
1283
1284 if (context->config.return_bytearray)
1285 {
1286 py_dest = PyByteArray_FromStringAndSize (block.buf, (Py_ssize_t) block.len);
1287 }
1288 else
1289 {
1290 py_dest = PyBytes_FromStringAndSize (block.buf, (Py_ssize_t) block.len);
1291 }
1292
1293 if (py_dest == NULL)
1294 {
1295 PyErr_NoMemory ();
1296 }
1297
1298 exit_now:
1299 if (source.buf != NULL)
1300 {
1301 PyBuffer_Release (&source);
1302 }
1303
1304 return py_dest;
1305 }
1306
1307 static PyObject *
1308 _decompress (PyObject * Py_UNUSED (self), PyObject * args)
1309 {
1310 stream_context_t * context = NULL;
1311 PyObject * py_context = NULL;
1312 PyObject * py_dest = NULL;
1313 int output_size = 0;
1314 uint32_t source_size_max = 0;
1315 Py_buffer source = { NULL, NULL, };
1316
1317 /* Positional arguments: capsule_context, source
1318 * Keyword arguments : none
1319 */
1320 if (!PyArg_ParseTuple (args, "Oy*", &py_context, &source))
1321 {
1322 goto exit_now;
1323 }
1324
1325 context = _PyCapsule_get_context (py_context);
1326 if ((context == NULL) || (context->lz4_state.context == NULL))
1327 {
1328 PyErr_SetString (PyExc_ValueError, "No valid LZ4 stream context supplied");
1329 goto exit_now;
1330 }
1331
1332 /* In out-of-band block size case, use a best-effort strategy for scaling
1333 * buffers.
1334 */
1335 if (context->config.store_comp_size == 0)
1336 {
1337 source_size_max = _GET_MAX_UINT32(4);
1338 }
1339 else
1340 {
1341 source_size_max = _GET_MAX_UINT32(context->config.store_comp_size);
1342 }
1343
1344 if (source.len > source_size_max)
1345 {
1346 PyErr_Format (PyExc_OverflowError,
1347 "Source length (%ld) too large for LZ4 store_comp_size (%d) value",
1348 source.len, context->config.store_comp_size);
1349 goto exit_now;
1350 }
1351
1352 if ((get_input_bound (source.len) == 0) ||
1353 (get_input_bound (source.len) > context->strategy.ops->get_dest_buffer_size (context)))
1354 {
1355 PyErr_Format (LZ4StreamError,
1356 "Maximal decompressed data (%d) cannot fit in LZ4 internal buffer (%u)",
1357 get_input_bound (source.len),
1358 context->strategy.ops->get_dest_buffer_size (context));
1359 goto exit_now;
1360 }
1361
1362 Py_BEGIN_ALLOW_THREADS
1363
1364 output_size = LZ4_decompress_safe_continue (context->lz4_state.decompress,
1365 (const char *) source.buf,
1366 context->strategy.ops->get_work_buffer (context),
1367 source.len,
1368 context->strategy.ops->get_dest_buffer_size (context));
1369
1370 Py_END_ALLOW_THREADS
1371
1372 if (output_size < 0)
1373 {
1374 /* In case of LZ4 decompression error, output_size holds the error code */
1375 PyErr_Format (LZ4StreamError,
1376 "Decompression failed. error: %d",
1377 -output_size);
1378 goto exit_now;
1379 }
1380
1381 if ((unsigned int) output_size > context->output.len)
1382 {
1383 output_size = -1;
1384 PyErr_Format (PyExc_OverflowError,
1385 "Decompressed stream too large for LZ4 API");
1386 goto exit_now;
1387 }
1388
1389 memcpy (context->output.buf,
1390 context->strategy.ops->get_work_buffer (context),
1391 output_size);
1392
1393 if ( context->strategy.ops->update_context_after_process (context) != 0)
1394 {
1395 PyErr_Format (PyExc_RuntimeError, "Internal error");
1396 goto exit_now;
1397 }
1398
1399 if (context->config.return_bytearray)
1400 {
1401 py_dest = PyByteArray_FromStringAndSize (context->output.buf, (Py_ssize_t) output_size);
1402 }
1403 else
1404 {
1405 py_dest = PyBytes_FromStringAndSize (context->output.buf, (Py_ssize_t) output_size);
1406 }
1407
1408 if (py_dest == NULL)
1409 {
1410 PyErr_NoMemory ();
1411 }
1412
1413 exit_now:
1414 if (source.buf != NULL)
1415 {
1416 PyBuffer_Release (&source);
1417 }
1418
1419 return py_dest;
1420 }
1421
1422
1423 PyDoc_STRVAR (_compress_bound__doc,
1424 "_compress_bound(input_size)\n" \
1425 "\n" \
1426 "Provides the maximum size that LZ4 compression may output in a \"worst case\"\n" \
1427 "scenario (input data not compressible).\n" \
1428 "This function is primarily useful for memory allocation purposes (destination\n" \
1429 "buffer size).\n" \
1430 "\n" \
1431 "Args:\n" \
1432 " input_size (int): Input data size.\n" \
1433 "\n" \
1434 "Returns:\n" \
1435 " int: Maximal (worst case) size of the compressed data;\n" \
1436 " or 0 if the input size is greater than 2 113 929 216.\n");
1437
1438 PyDoc_STRVAR (_input_bound__doc,
1439 "_input_bound(compress_max_size)\n" \
1440 "\n" \
1441 "Provides the maximum size that LZ4 decompression may output in a \"worst case\"\n" \
1442 "scenario (compressed data with null compression ratio).\n" \
1443 "This function is primarily useful for memory allocation purposes (destination\n" \
1444 "buffer size).\n" \
1445 "\n" \
1446 "Args:\n" \
1447 " compress_max_size (int): Compressed data size.\n" \
1448 "\n" \
1449 "Returns:\n" \
1450 " int: Maximal (worst case) size of the input data;\n" \
1451 " or 0 if the compressed maximal size is lower than the LZ4 compression\n" \
1452 " minimal overhead, or if the computed input size is greater than\n" \
1453 " 2 113 929 216.\n");
1454
1455 PyDoc_STRVAR (_compress__doc,
1456 "_compress(context, source)\n" \
1457 "\n" \
1458 "Compress source, using the given LZ4 stream context, returning the compressed\n" \
1459 "data as a bytearray or as a bytes object.\n" \
1460 "Raises an exception if any error occurs.\n" \
1461 "\n" \
1462 "Args:\n" \
1463 " context (ctx): LZ4 stream context.\n" \
1464 " source (str, bytes or buffer-compatible object): Data to compress.\n" \
1465 "\n" \
1466 "Returns:\n" \
1467 " bytes or bytearray: Compressed data.\n" \
1468 "\n" \
1469 "Raises:\n" \
1470 " OverflowError: raised if the source is too large for being compressed in\n" \
1471 " the given context.\n" \
1472 " RuntimeError: raised if some internal resources cannot be updated.\n" \
1473 " LZ4StreamError: raised if the call to the LZ4 library fails.\n");
1474
1475 PyDoc_STRVAR (_get_block__doc,
1476 "_get_block(context, source)\n" \
1477 "\n" \
1478 "Return the first LZ4 compressed block from ``'source'``. \n" \
1479 "\n" \
1480 "Args:\n" \
1481 " context (ctx): LZ4 stream context.\n" \
1482 " source (str, bytes or buffer-compatible object): LZ4 compressed stream.\n" \
1483 "\n" \
1484 "Returns:\n" \
1485 " bytes or bytearray: LZ4 compressed data block.\n" \
1486 "\n" \
1487 "Raises:\n" \
1488 " MemoryError: raised if the output buffer cannot be allocated.\n" \
1489 " OverflowError: raised if the source is too large for being handled by \n" \
1490 " the given context.\n");
1491
1492 PyDoc_STRVAR (_decompress__doc,
1493 "_decompress(context, source)\n" \
1494 "\n" \
1495 "Decompress source, using the given LZ4 stream context, returning the\n" \
1496 "uncompressed data as a bytearray or as a bytes object.\n" \
1497 "Raises an exception if any error occurs.\n" \
1498 "\n" \
1499 "Args:\n" \
1500 " context (obj): LZ4 stream context.\n" \
1501 " source (str, bytes or buffer-compatible object): Data to uncompress.\n" \
1502 "\n" \
1503 "Returns:\n" \
1504 " bytes or bytearray: Uncompressed data.\n" \
1505 "\n" \
1506 "Raises:\n" \
1507 " ValueError: raised if the source is inconsistent with a finite LZ4\n" \
1508 " stream block chain.\n" \
1509 " MemoryError: raised if the work output buffer cannot be allocated.\n" \
1510 " OverflowError: raised if the source is too large for being decompressed\n" \
1511 " in the given context.\n" \
1512 " RuntimeError: raised if some internal resources cannot be updated.\n" \
1513 " LZ4StreamError: raised if the call to the LZ4 library fails.\n");
1514
1515 PyDoc_STRVAR (_create_context__doc,
1516 "_create_context(strategy, direction, buffer_size,\n" \
1517 " mode='default', acceleration=1, compression_level=9,\n" \
1518 " return_bytearray=0, store_comp_size=4, dict=None)\n" \
1519 "\n" \
1520 "Instantiates and initializes a LZ4 stream context.\n" \
1521 "Raises an exception if any error occurs.\n" \
1522 "\n" \
1523 "Args:\n" \
1524 " strategy (str): Can be ``'double_buffer'``.\n" \
1525 " Only ``'double_buffer'`` is currently implemented.\n" \
1526 " direction (str): Can be ``'compress'`` or ``'decompress'``.\n" \
1527 " buffer_size (int): Base size of the buffer(s) used internally for stream\n" \
1528 " compression/decompression.\n" \
1529 " For the ``'double_buffer'`` strategy, this is the size of each buffer\n" \
1530 " of the double-buffer.\n" \
1531 "\n" \
1532 "Keyword Args:\n" \
1533 " mode (str): If ``'default'`` or unspecified use the default LZ4\n" \
1534 " compression mode. Set to ``'fast'`` to use the fast compression\n" \
1535 " LZ4 mode at the expense of compression. Set to\n" \
1536 " ``'high_compression'`` to use the LZ4 high-compression mode at\n" \
1537 " the expense of speed.\n" \
1538 " acceleration (int): When mode is set to ``'fast'`` this argument\n" \
1539 " specifies the acceleration. The larger the acceleration, the\n" \
1540 " faster the but the lower the compression. The default\n" \
1541 " compression corresponds to a value of ``1``.\n" \
1542 " Only relevant if ``'direction'`` is ``'compress'``.\n" \
1543 " compression_level (int): When mode is set to ``high_compression`` this\n" \
1544 " argument specifies the compression. Valid values are between\n" \
1545 " ``1`` and ``12``. Values between ``4-9`` are recommended, and\n" \
1546 " ``9`` is the default.\n" \
1547 " Only relevant if ``'direction'`` is ``'compress'`` and ``'mode'`` .\n" \
1548 " is ``'high_compression'``.\n" \
1549 " return_bytearray (bool): If ``False`` (the default) then the function\n" \
1550 " will return a bytes object. If ``True``, then the function will\n" \
1551 " return a bytearray object.\n" \
1552 " store_comp_size (int): Specify the size in bytes of the following\n" \
1553 " compressed block. Can be: ``1``, ``2`` or ``4`` (default: ``4``).\n" \
1554 " dict (str, bytes or buffer-compatible object): If specified, perform\n" \
1555 " compression using this initial dictionary.\n" \
1556 "\n" \
1557 "Returns:\n" \
1558 " lz4_ctx: A LZ4 stream context.\n" \
1559 "\n" \
1560 "Raises:\n" \
1561 " OverflowError: raised if the ``dict`` parameter is too large for the\n" \
1562 " LZ4 context.\n" \
1563 " ValueError: raised if some parameters are invalid.\n" \
1564 " MemoryError: raised if some internal resources cannot be allocated.\n" \
1565 " RuntimeError: raised if some internal resources cannot be initialized.\n");
1566
1567 PyDoc_STRVAR (lz4stream__doc,
1568 "A Python wrapper for the LZ4 stream protocol"
1569 );
1570
1571 static PyMethodDef module_methods[] = {
1572 {
1573 "_create_context", (PyCFunction) _create_context,
1574 METH_VARARGS | METH_KEYWORDS,
1575 _create_context__doc
1576 },
1577
1578 {
1579 "_compress",
1580 (PyCFunction) _compress,
1581 METH_VARARGS,
1582 _compress__doc
1583 },
1584 {
1585 "_decompress",
1586 (PyCFunction) _decompress,
1587 METH_VARARGS,
1588 _decompress__doc
1589 },
1590 {
1591 "_get_block",
1592 (PyCFunction) _get_block,
1593 METH_VARARGS,
1594 _get_block__doc
1595 },
1596 {
1597 "_compress_bound",
1598 (PyCFunction) _compress_bound,
1599 METH_VARARGS,
1600 _compress_bound__doc
1601 },
1602 {
1603 "_input_bound",
1604 (PyCFunction) _input_bound,
1605 METH_VARARGS,
1606 _input_bound__doc
1607 },
1608 {
1609 /* Sentinel */
1610 NULL,
1611 NULL,
1612 0,
1613 NULL
1614 }
1615 };
1616
1617 static PyModuleDef moduledef = {
1618 PyModuleDef_HEAD_INIT,
1619 /* m_name */ "_stream",
1620 /* m_doc */ lz4stream__doc,
1621 /* m_size */ -1,
1622 /* m_methods */ module_methods,
1623 };
1624
1625
1626 PyMODINIT_FUNC
1627 PyInit__stream(void)
1628 {
1629 PyObject * module = PyModule_Create (&moduledef);
1630
1631 if (module == NULL)
1632 {
1633 return NULL;
1634 }
1635
1636 PyModule_AddIntConstant (module, "HC_LEVEL_MIN", LZ4HC_CLEVEL_MIN);
1637 PyModule_AddIntConstant (module, "HC_LEVEL_DEFAULT", LZ4HC_CLEVEL_DEFAULT);
1638 PyModule_AddIntConstant (module, "HC_LEVEL_OPT_MIN", LZ4HC_CLEVEL_OPT_MIN);
1639 PyModule_AddIntConstant (module, "HC_LEVEL_MAX", LZ4HC_CLEVEL_MAX);
1640 PyModule_AddIntConstant (module, "LZ4_MAX_INPUT_SIZE", LZ4_MAX_INPUT_SIZE);
1641
1642 LZ4StreamError = PyErr_NewExceptionWithDoc ("_stream.LZ4StreamError",
1643 "Call to LZ4 library failed.",
1644 NULL, NULL);
1645 if (LZ4StreamError == NULL)
1646 {
1647 return NULL;
1648 }
1649 Py_INCREF (LZ4StreamError);
1650 PyModule_AddObject (module, "LZ4StreamError", LZ4StreamError);
1651
1652 #ifdef Py_GIL_DISABLED
1653 PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED);
1654 #endif
1655
1656 return module;
1657 }