Debian Codegraph @

lz4/block/_block.c

raw symbols SCIP
1 /*
2 * Copyright (c) 2012-2018, Steeve Morin, Jonathan 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 Steeve Morin nor the names of its contributors may be
16 * used to endorse or promote products derived from this software without
17 * 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
45 #ifndef Py_UNUSED /* This is already defined for Python 3.4 onwards */
46 #ifdef __GNUC__
47 #define Py_UNUSED(name) _unused_ ## name __attribute__((unused))
48 #else
49 #define Py_UNUSED(name) _unused_ ## name
50 #endif
51 #endif
52
53 #if defined(_WIN32) && defined(_MSC_VER)
54 #if _MSC_VER >= 1600
55 #include <stdint.h>
56 #else /* _MSC_VER >= 1600 */
57 typedef signed char int8_t;
58 typedef signed short int16_t;
59 typedef signed int int32_t;
60 typedef unsigned char uint8_t;
61 typedef unsigned short uint16_t;
62 typedef unsigned int uint32_t;
63 #endif /* _MSC_VER >= 1600 */
64 #endif
65
66 static inline void
67 store_le32 (char *c, uint32_t x)
68 {
69 c[0] = x & 0xff;
70 c[1] = (x >> 8) & 0xff;
71 c[2] = (x >> 16) & 0xff;
72 c[3] = (x >> 24) & 0xff;
73 }
74
75 static inline uint32_t
76 load_le32 (const char *c)
77 {
78 const uint8_t *d = (const uint8_t *) c;
79 return d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
80 }
81
82 static const size_t hdr_size = sizeof (uint32_t);
83
84 typedef enum
85 {
86 DEFAULT,
87 FAST,
88 HIGH_COMPRESSION
89 } compression_type;
90
91 static PyObject * LZ4BlockError;
92
93 static inline int
94 lz4_compress_generic (int comp, char* source, char* dest, int source_size, int dest_size,
95 char* dict, int dict_size, int acceleration, int compression)
96 {
97 if (comp != HIGH_COMPRESSION)
98 {
99 LZ4_stream_t lz4_state;
100 LZ4_resetStream (&lz4_state);
101 if (dict)
102 {
103 LZ4_loadDict (&lz4_state, dict, dict_size);
104 }
105 if (comp != FAST)
106 {
107 acceleration = 1;
108 }
109 return LZ4_compress_fast_continue (&lz4_state, source, dest, source_size, dest_size, acceleration);
110 }
111 else
112 {
113 LZ4_streamHC_t lz4_state;
114 LZ4_resetStreamHC (&lz4_state, compression);
115 if (dict)
116 {
117 LZ4_loadDictHC (&lz4_state, dict, dict_size);
118 }
119 return LZ4_compress_HC_continue (&lz4_state, source, dest, source_size, dest_size);
120 }
121 }
122
123 #ifdef inline
124 #undef inline
125 #endif
126
127 static PyObject *
128 compress (PyObject * Py_UNUSED (self), PyObject * args, PyObject * kwargs)
129 {
130 const char *mode = "default";
131 size_t dest_size, total_size;
132 int acceleration = 1;
133 int compression = 9;
134 int store_size = 1;
135 PyObject *py_dest;
136 char *dest, *dest_start;
137 compression_type comp;
138 int output_size;
139 Py_buffer source;
140 int source_size;
141 int return_bytearray = 0;
142 Py_buffer dict = {0};
143 static char *argnames[] = {
144 "source",
145 "mode",
146 "store_size",
147 "acceleration",
148 "compression",
149 "return_bytearray",
150 "dict",
151 NULL
152 };
153
154 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "y*|spiipz*", argnames,
155 &source,
156 &mode, &store_size, &acceleration, &compression,
157 &return_bytearray, &dict))
158 {
159 return NULL;
160 }
161
162 if (source.len > INT_MAX)
163 {
164 PyBuffer_Release(&source);
165 PyBuffer_Release(&dict);
166 PyErr_Format(PyExc_OverflowError,
167 "Input too large for LZ4 API");
168 return NULL;
169 }
170
171 if (dict.len > INT_MAX)
172 {
173 PyBuffer_Release(&source);
174 PyBuffer_Release(&dict);
175 PyErr_Format(PyExc_OverflowError,
176 "Dictionary too large for LZ4 API");
177 return NULL;
178 }
179
180 source_size = (int) source.len;
181
182 if (!strncmp (mode, "default", sizeof ("default")))
183 {
184 comp = DEFAULT;
185 }
186 else if (!strncmp (mode, "fast", sizeof ("fast")))
187 {
188 comp = FAST;
189 }
190 else if (!strncmp (mode, "high_compression", sizeof ("high_compression")))
191 {
192 comp = HIGH_COMPRESSION;
193 }
194 else
195 {
196 PyBuffer_Release(&source);
197 PyBuffer_Release(&dict);
198 PyErr_Format (PyExc_ValueError,
199 "Invalid mode argument: %s. Must be one of: standard, fast, high_compression",
200 mode);
201 return NULL;
202 }
203
204 dest_size = LZ4_compressBound (source_size);
205
206 if (store_size)
207 {
208 total_size = dest_size + hdr_size;
209 }
210 else
211 {
212 total_size = dest_size;
213 }
214
215 dest = PyMem_Malloc (total_size * sizeof * dest);
216 if (dest == NULL)
217 {
218 return PyErr_NoMemory();
219 }
220
221 Py_BEGIN_ALLOW_THREADS
222
223 if (store_size)
224 {
225 store_le32 (dest, source_size);
226 dest_start = dest + hdr_size;
227 }
228 else
229 {
230 dest_start = dest;
231 }
232
233 output_size = lz4_compress_generic (comp, source.buf, dest_start, source_size,
234 (int) dest_size, dict.buf, (int) dict.len,
235 acceleration, compression);
236
237 Py_END_ALLOW_THREADS
238
239 PyBuffer_Release(&source);
240 PyBuffer_Release(&dict);
241
242 if (output_size <= 0)
243 {
244 PyErr_SetString (LZ4BlockError, "Compression failed");
245 PyMem_Free (dest);
246 return NULL;
247 }
248
249 if (store_size)
250 {
251 output_size += (int) hdr_size;
252 }
253
254 if (return_bytearray)
255 {
256 py_dest = PyByteArray_FromStringAndSize (dest, (Py_ssize_t) output_size);
257 }
258 else
259 {
260 py_dest = PyBytes_FromStringAndSize (dest, (Py_ssize_t) output_size);
261 }
262
263 PyMem_Free (dest);
264
265 if (py_dest == NULL)
266 {
267 return PyErr_NoMemory ();
268 }
269
270 return py_dest;
271 }
272
273 static PyObject *
274 decompress (PyObject * Py_UNUSED (self), PyObject * args, PyObject * kwargs)
275 {
276 Py_buffer source;
277 const char * source_start;
278 size_t source_size;
279 PyObject *py_dest;
280 char *dest;
281 int output_size;
282 size_t dest_size;
283 int uncompressed_size = -1;
284 int return_bytearray = 0;
285 Py_buffer dict = {0};
286 static char *argnames[] = {
287 "source",
288 "uncompressed_size",
289 "return_bytearray",
290 "dict",
291 NULL
292 };
293
294 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "y*|ipz*", argnames,
295 &source, &uncompressed_size,
296 &return_bytearray, &dict))
297 {
298 return NULL;
299 }
300
301 if (source.len > INT_MAX)
302 {
303 PyBuffer_Release(&source);
304 PyBuffer_Release(&dict);
305 PyErr_Format(PyExc_OverflowError,
306 "Input too large for LZ4 API");
307 return NULL;
308 }
309
310 if (dict.len > INT_MAX)
311 {
312 PyBuffer_Release(&source);
313 PyBuffer_Release(&dict);
314 PyErr_Format(PyExc_OverflowError,
315 "Dictionary too large for LZ4 API");
316 return NULL;
317 }
318
319 source_start = (const char *) source.buf;
320 source_size = (int) source.len;
321
322 if (uncompressed_size >= 0)
323 {
324 dest_size = uncompressed_size;
325 }
326 else
327 {
328 if (source_size < hdr_size)
329 {
330 PyBuffer_Release(&source);
331 PyBuffer_Release(&dict);
332 PyErr_SetString (PyExc_ValueError, "Input source data size too small");
333 return NULL;
334 }
335 dest_size = load_le32 (source_start);
336 source_start += hdr_size;
337 source_size -= hdr_size;
338 }
339
340 if (dest_size > INT_MAX)
341 {
342 PyBuffer_Release(&source);
343 PyBuffer_Release(&dict);
344 PyErr_Format (PyExc_ValueError, "Invalid size: 0x%zu",
345 dest_size);
346 return NULL;
347 }
348
349 dest = PyMem_Malloc (dest_size * sizeof * dest);
350 if (dest == NULL)
351 {
352 return PyErr_NoMemory();
353 }
354
355 Py_BEGIN_ALLOW_THREADS
356
357 output_size =
358 LZ4_decompress_safe_usingDict (source_start, dest, source_size, (int) dest_size,
359 dict.buf, (int) dict.len);
360
361 Py_END_ALLOW_THREADS
362
363 PyBuffer_Release(&source);
364 PyBuffer_Release(&dict);
365
366 if (output_size < 0)
367 {
368 PyErr_Format (LZ4BlockError,
369 "Decompression failed: corrupt input or insufficient space in destination buffer. Error code: %u",
370 -output_size);
371 PyMem_Free (dest);
372 return NULL;
373 }
374 else if (((size_t)output_size != dest_size) && (uncompressed_size < 0))
375 {
376 PyErr_Format (LZ4BlockError,
377 "Decompressor wrote %u bytes, but %zu bytes expected from header",
378 output_size, dest_size);
379 PyMem_Free (dest);
380 return NULL;
381 }
382
383 if (return_bytearray)
384 {
385 py_dest = PyByteArray_FromStringAndSize (dest, (Py_ssize_t) output_size);
386 }
387 else
388 {
389 py_dest = PyBytes_FromStringAndSize (dest, (Py_ssize_t) output_size);
390 }
391
392 PyMem_Free (dest);
393
394 if (py_dest == NULL)
395 {
396 return PyErr_NoMemory ();
397 }
398
399 return py_dest;
400 }
401
402 PyDoc_STRVAR(compress__doc,
403 "compress(source, mode='default', acceleration=1, compression=0, return_bytearray=False)\n\n" \
404 "Compress source, returning the compressed data as a string.\n" \
405 "Raises an exception if any error occurs.\n" \
406 "\n" \
407 "Args:\n" \
408 " source (str, bytes or buffer-compatible object): Data to compress\n" \
409 "\n" \
410 "Keyword Args:\n" \
411 " mode (str): If ``'default'`` or unspecified use the default LZ4\n" \
412 " compression mode. Set to ``'fast'`` to use the fast compression\n" \
413 " LZ4 mode at the expense of compression. Set to\n" \
414 " ``'high_compression'`` to use the LZ4 high-compression mode at\n" \
415 " the exepense of speed.\n" \
416 " acceleration (int): When mode is set to ``'fast'`` this argument\n" \
417 " specifies the acceleration. The larger the acceleration, the\n" \
418 " faster the but the lower the compression. The default\n" \
419 " compression corresponds to a value of ``1``.\n" \
420 " compression (int): When mode is set to ``high_compression`` this\n" \
421 " argument specifies the compression. Valid values are between\n" \
422 " ``1`` and ``12``. Values between ``4-9`` are recommended, and\n" \
423 " ``9`` is the default.\n"
424 " store_size (bool): If ``True`` (the default) then the size of the\n" \
425 " uncompressed data is stored at the start of the compressed\n" \
426 " block.\n" \
427 " return_bytearray (bool): If ``False`` (the default) then the function\n" \
428 " will return a bytes object. If ``True``, then the function will\n" \
429 " return a bytearray object.\n\n" \
430 " dict (str, bytes or buffer-compatible object): If specified, perform\n" \
431 " compression using this initial dictionary.\n" \
432 "Returns:\n" \
433 " bytes or bytearray: Compressed data.\n");
434
435 PyDoc_STRVAR(decompress__doc,
436 "decompress(source, uncompressed_size=-1, return_bytearray=False)\n\n" \
437 "Decompress source, returning the uncompressed data as a string.\n" \
438 "Raises an exception if any error occurs.\n" \
439 "\n" \
440 "Args:\n" \
441 " source (str, bytes or buffer-compatible object): Data to decompress.\n" \
442 "\n" \
443 "Keyword Args:\n" \
444 " uncompressed_size (int): If not specified or negative, the uncompressed\n" \
445 " data size is read from the start of the source block. If specified,\n" \
446 " it is assumed that the full source data is compressed data. If this\n" \
447 " argument is specified, it is considered to be a maximum possible size\n" \
448 " for the buffer used to hold the uncompressed data, and so less data\n" \
449 " may be returned. If `uncompressed_size` is too small, `LZ4BlockError`\n" \
450 " will be raised. By catching `LZ4BlockError` it is possible to increase\n" \
451 " `uncompressed_size` and try again.\n" \
452 " return_bytearray (bool): If ``False`` (the default) then the function\n" \
453 " will return a bytes object. If ``True``, then the function will\n" \
454 " return a bytearray object.\n\n" \
455 " dict (str, bytes or buffer-compatible object): If specified, perform\n" \
456 " decompression using this initial dictionary.\n" \
457 "\n" \
458 "Returns:\n" \
459 " bytes or bytearray: Decompressed data.\n" \
460 "\n" \
461 "Raises:\n" \
462 " LZ4BlockError: raised if the call to the LZ4 library fails. This can be\n" \
463 " caused by `uncompressed_size` being too small, or invalid data.\n");
464
465 PyDoc_STRVAR(lz4block__doc,
466 "A Python wrapper for the LZ4 block protocol"
467 );
468
469 static PyMethodDef module_methods[] = {
470 {
471 "compress",
472 (PyCFunction) compress,
473 METH_VARARGS | METH_KEYWORDS,
474 compress__doc
475 },
476 {
477 "decompress",
478 (PyCFunction) decompress,
479 METH_VARARGS | METH_KEYWORDS,
480 decompress__doc
481 },
482 {
483 /* Sentinel */
484 NULL,
485 NULL,
486 0,
487 NULL
488 }
489 };
490
491 static struct PyModuleDef moduledef =
492 {
493 PyModuleDef_HEAD_INIT,
494 "_block",
495 lz4block__doc,
496 -1,
497 module_methods
498 };
499
500 PyMODINIT_FUNC
501 PyInit__block(void)
502 {
503 PyObject *module = PyModule_Create (&moduledef);
504
505 if (module == NULL)
506 return NULL;
507
508 PyModule_AddIntConstant (module, "HC_LEVEL_MIN", LZ4HC_CLEVEL_MIN);
509 PyModule_AddIntConstant (module, "HC_LEVEL_DEFAULT", LZ4HC_CLEVEL_DEFAULT);
510 PyModule_AddIntConstant (module, "HC_LEVEL_OPT_MIN", LZ4HC_CLEVEL_OPT_MIN);
511 PyModule_AddIntConstant (module, "HC_LEVEL_MAX", LZ4HC_CLEVEL_MAX);
512
513 LZ4BlockError = PyErr_NewExceptionWithDoc("_block.LZ4BlockError", "Call to LZ4 library failed.", NULL, NULL);
514 if (LZ4BlockError == NULL)
515 {
516 return NULL;
517 }
518 Py_INCREF(LZ4BlockError);
519 PyModule_AddObject(module, "LZ4BlockError", LZ4BlockError);
520
521 #ifdef Py_GIL_DISABLED
522 PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED);
523 #endif
524
525 return module;
526 }