Debian Codegraph @

c-ext/compressionreader.c

raw
1 /**
2 * Copyright (c) 2017-present, Gregory Szorc
3 * All rights reserved.
4 *
5 * This software may be modified and distributed under the terms
6 * of the BSD license. See the LICENSE file for details.
7 */
8
9 #include "python-zstandard.h"
10
11 extern PyObject *ZstdError;
12
13 static void compressionreader_dealloc(ZstdCompressionReader *self) {
14 Py_XDECREF(self->compressor);
15 Py_XDECREF(self->reader);
16
17 if (self->buffer.buf) {
18 PyBuffer_Release(&self->buffer);
19 memset(&self->buffer, 0, sizeof(self->buffer));
20 }
21
22 PyObject_Del(self);
23 }
24
25 static ZstdCompressionReader *
26 compressionreader_enter(ZstdCompressionReader *self) {
27 if (self->entered) {
28 PyErr_SetString(PyExc_ValueError, "cannot __enter__ multiple times");
29 return NULL;
30 }
31
32 if (self->closed) {
33 PyErr_SetString(PyExc_ValueError, "stream is closed");
34 return NULL;
35 }
36
37 self->entered = 1;
38
39 Py_INCREF(self);
40 return self;
41 }
42
43 static PyObject *compressionreader_exit(ZstdCompressionReader *self,
44 PyObject *args) {
45 PyObject *exc_type;
46 PyObject *exc_value;
47 PyObject *exc_tb;
48 PyObject *result;
49
50 if (!PyArg_ParseTuple(args, "OOO:__exit__", &exc_type, &exc_value,
51 &exc_tb)) {
52 return NULL;
53 }
54
55 self->entered = 0;
56
57 result = PyObject_CallMethod((PyObject *)self, "close", NULL);
58 if (NULL == result) {
59 return NULL;
60 }
61
62 /* Release resources associated with source. */
63 Py_CLEAR(self->reader);
64 if (self->buffer.buf) {
65 PyBuffer_Release(&self->buffer);
66 memset(&self->buffer, 0, sizeof(self->buffer));
67 }
68
69 Py_CLEAR(self->compressor);
70
71 Py_RETURN_FALSE;
72 }
73
74 static PyObject *compressionreader_readable(ZstdCompressionReader *self) {
75 Py_RETURN_TRUE;
76 }
77
78 static PyObject *compressionreader_writable(ZstdCompressionReader *self) {
79 Py_RETURN_FALSE;
80 }
81
82 static PyObject *compressionreader_seekable(ZstdCompressionReader *self) {
83 Py_RETURN_FALSE;
84 }
85
86 static PyObject *compressionreader_readline(PyObject *self, PyObject *args) {
87 set_io_unsupported_operation();
88 return NULL;
89 }
90
91 static PyObject *compressionreader_readlines(PyObject *self, PyObject *args) {
92 set_io_unsupported_operation();
93 return NULL;
94 }
95
96 static PyObject *compressionreader_write(PyObject *self, PyObject *args) {
97 PyErr_SetString(PyExc_OSError, "stream is not writable");
98 return NULL;
99 }
100
101 static PyObject *compressionreader_writelines(PyObject *self, PyObject *args) {
102 PyErr_SetString(PyExc_OSError, "stream is not writable");
103 return NULL;
104 }
105
106 static PyObject *compressionreader_isatty(PyObject *self) {
107 Py_RETURN_FALSE;
108 }
109
110 static PyObject *compressionreader_flush(PyObject *self) {
111 Py_RETURN_NONE;
112 }
113
114 static PyObject *compressionreader_close(ZstdCompressionReader *self) {
115 if (self->closed) {
116 Py_RETURN_NONE;
117 }
118
119 self->closed = 1;
120
121 if (self->closefd && self->reader != NULL &&
122 PyObject_HasAttrString(self->reader, "close")) {
123 return PyObject_CallMethod(self->reader, "close", NULL);
124 }
125
126 Py_RETURN_NONE;
127 }
128
129 static PyObject *compressionreader_tell(ZstdCompressionReader *self) {
130 /* TODO should this raise OSError since stream isn't seekable? */
131 return PyLong_FromUnsignedLongLong(self->bytesCompressed);
132 }
133
134 int read_compressor_input(ZstdCompressionReader *self) {
135 if (self->finishedInput) {
136 return 0;
137 }
138
139 if (self->input.pos != self->input.size) {
140 return 0;
141 }
142
143 if (self->reader) {
144 Py_buffer buffer;
145
146 assert(self->readResult == NULL);
147
148 self->readResult =
149 PyObject_CallMethod(self->reader, "read", "k", self->readSize);
150
151 if (NULL == self->readResult) {
152 return -1;
153 }
154
155 memset(&buffer, 0, sizeof(buffer));
156
157 if (0 !=
158 PyObject_GetBuffer(self->readResult, &buffer, PyBUF_CONTIG_RO)) {
159 return -1;
160 }
161
162 /* EOF */
163 if (0 == buffer.len) {
164 self->finishedInput = 1;
165 Py_CLEAR(self->readResult);
166 }
167 else {
168 self->input.src = buffer.buf;
169 self->input.size = buffer.len;
170 self->input.pos = 0;
171 }
172
173 PyBuffer_Release(&buffer);
174 }
175 else {
176 assert(self->buffer.buf);
177
178 self->input.src = self->buffer.buf;
179 self->input.size = self->buffer.len;
180 self->input.pos = 0;
181 }
182
183 return 1;
184 }
185
186 int compress_input(ZstdCompressionReader *self, ZSTD_outBuffer *output) {
187 size_t oldPos;
188 size_t zresult;
189
190 /* If we have data left over, consume it. */
191 if (self->input.pos < self->input.size) {
192 oldPos = output->pos;
193
194 Py_BEGIN_ALLOW_THREADS zresult = ZSTD_compressStream2(
195 self->compressor->cctx, output, &self->input, ZSTD_e_continue);
196 Py_END_ALLOW_THREADS
197
198 self->bytesCompressed += output->pos - oldPos;
199
200 /* Input exhausted. Clear out state tracking. */
201 if (self->input.pos == self->input.size) {
202 memset(&self->input, 0, sizeof(self->input));
203 Py_CLEAR(self->readResult);
204
205 if (self->buffer.buf) {
206 self->finishedInput = 1;
207 }
208 }
209
210 if (ZSTD_isError(zresult)) {
211 PyErr_Format(ZstdError, "zstd compress error: %s",
212 ZSTD_getErrorName(zresult));
213 return -1;
214 }
215 }
216
217 if (output->pos && output->pos == output->size) {
218 return 1;
219 }
220 else {
221 return 0;
222 }
223 }
224
225 static PyObject *compressionreader_read(ZstdCompressionReader *self,
226 PyObject *args, PyObject *kwargs) {
227 static char *kwlist[] = {"size", NULL};
228
229 Py_ssize_t size = -1;
230 PyObject *result = NULL;
231 char *resultBuffer;
232 Py_ssize_t resultSize;
233 size_t zresult;
234 size_t oldPos;
235 int readResult, compressResult;
236
237 if (self->closed) {
238 PyErr_SetString(PyExc_ValueError, "stream is closed");
239 return NULL;
240 }
241
242 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n", kwlist, &size)) {
243 return NULL;
244 }
245
246 if (size < -1) {
247 PyErr_SetString(PyExc_ValueError,
248 "cannot read negative amounts less than -1");
249 return NULL;
250 }
251
252 if (size == -1) {
253 return PyObject_CallMethod((PyObject *)self, "readall", NULL);
254 }
255
256 if (self->finishedOutput || size == 0) {
257 return PyBytes_FromStringAndSize("", 0);
258 }
259
260 result = PyBytes_FromStringAndSize(NULL, size);
261 if (NULL == result) {
262 return NULL;
263 }
264
265 PyBytes_AsStringAndSize(result, &resultBuffer, &resultSize);
266
267 self->output.dst = resultBuffer;
268 self->output.size = resultSize;
269 self->output.pos = 0;
270
271 readinput:
272
273 compressResult = compress_input(self, &self->output);
274
275 if (-1 == compressResult) {
276 Py_XDECREF(result);
277 return NULL;
278 }
279 else if (0 == compressResult) {
280 /* There is room in the output. We fall through to below, which will
281 * either get more input for us or will attempt to end the stream.
282 */
283 }
284 else if (1 == compressResult) {
285 memset(&self->output, 0, sizeof(self->output));
286 return result;
287 }
288 else {
289 assert(0);
290 }
291
292 readResult = read_compressor_input(self);
293
294 if (-1 == readResult) {
295 return NULL;
296 }
297 else if (0 == readResult) {
298 }
299 else if (1 == readResult) {
300 }
301 else {
302 assert(0);
303 }
304
305 if (self->input.size) {
306 goto readinput;
307 }
308
309 /* Else EOF */
310 oldPos = self->output.pos;
311
312 zresult = ZSTD_compressStream2(self->compressor->cctx, &self->output,
313 &self->input, ZSTD_e_end);
314
315 self->bytesCompressed += self->output.pos - oldPos;
316
317 if (ZSTD_isError(zresult)) {
318 PyErr_Format(ZstdError, "error ending compression stream: %s",
319 ZSTD_getErrorName(zresult));
320 Py_XDECREF(result);
321 return NULL;
322 }
323
324 assert(self->output.pos);
325
326 if (0 == zresult) {
327 self->finishedOutput = 1;
328 }
329
330 if (safe_pybytes_resize(&result, self->output.pos)) {
331 Py_XDECREF(result);
332 return NULL;
333 }
334
335 memset(&self->output, 0, sizeof(self->output));
336
337 return result;
338 }
339
340 static PyObject *compressionreader_read1(ZstdCompressionReader *self,
341 PyObject *args, PyObject *kwargs) {
342 static char *kwlist[] = {"size", NULL};
343
344 Py_ssize_t size = -1;
345 PyObject *result = NULL;
346 char *resultBuffer;
347 Py_ssize_t resultSize;
348 ZSTD_outBuffer output;
349 int compressResult;
350 size_t oldPos;
351 size_t zresult;
352
353 if (self->closed) {
354 PyErr_SetString(PyExc_ValueError, "stream is closed");
355 return NULL;
356 }
357
358 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n:read1", kwlist, &size)) {
359 return NULL;
360 }
361
362 if (size < -1) {
363 PyErr_SetString(PyExc_ValueError,
364 "cannot read negative amounts less than -1");
365 return NULL;
366 }
367
368 if (self->finishedOutput || size == 0) {
369 return PyBytes_FromStringAndSize("", 0);
370 }
371
372 if (size == -1) {
373 size = ZSTD_CStreamOutSize();
374 }
375
376 result = PyBytes_FromStringAndSize(NULL, size);
377 if (NULL == result) {
378 return NULL;
379 }
380
381 PyBytes_AsStringAndSize(result, &resultBuffer, &resultSize);
382
383 output.dst = resultBuffer;
384 output.size = resultSize;
385 output.pos = 0;
386
387 /* read1() is supposed to use at most 1 read() from the underlying stream.
388 However, we can't satisfy this requirement with compression because
389 not every input will generate output. We /could/ flush the compressor,
390 but this may not be desirable. We allow multiple read() from the
391 underlying stream. But unlike read(), we return as soon as output data
392 is available.
393 */
394
395 compressResult = compress_input(self, &output);
396
397 if (-1 == compressResult) {
398 Py_XDECREF(result);
399 return NULL;
400 }
401 else if (0 == compressResult || 1 == compressResult) {
402 }
403 else {
404 assert(0);
405 }
406
407 if (output.pos) {
408 goto finally;
409 }
410
411 while (!self->finishedInput) {
412 int readResult = read_compressor_input(self);
413
414 if (-1 == readResult) {
415 Py_XDECREF(result);
416 return NULL;
417 }
418 else if (0 == readResult || 1 == readResult) {
419 }
420 else {
421 assert(0);
422 }
423
424 compressResult = compress_input(self, &output);
425
426 if (-1 == compressResult) {
427 Py_XDECREF(result);
428 return NULL;
429 }
430 else if (0 == compressResult || 1 == compressResult) {
431 }
432 else {
433 assert(0);
434 }
435
436 if (output.pos) {
437 goto finally;
438 }
439 }
440
441 /* EOF */
442 oldPos = output.pos;
443
444 zresult = ZSTD_compressStream2(self->compressor->cctx, &output,
445 &self->input, ZSTD_e_end);
446
447 self->bytesCompressed += output.pos - oldPos;
448
449 if (ZSTD_isError(zresult)) {
450 PyErr_Format(ZstdError, "error ending compression stream: %s",
451 ZSTD_getErrorName(zresult));
452 Py_XDECREF(result);
453 return NULL;
454 }
455
456 if (zresult == 0) {
457 self->finishedOutput = 1;
458 }
459
460 finally:
461 if (result) {
462 if (safe_pybytes_resize(&result, output.pos)) {
463 Py_XDECREF(result);
464 return NULL;
465 }
466 }
467
468 return result;
469 }
470
471 static PyObject *compressionreader_readall(PyObject *self) {
472 PyObject *chunks = NULL;
473 PyObject *empty = NULL;
474 PyObject *result = NULL;
475
476 /* Our strategy is to collect chunks into a list then join all the
477 * chunks at the end. We could potentially use e.g. an io.BytesIO. But
478 * this feels simple enough to implement and avoids potentially expensive
479 * reallocations of large buffers.
480 */
481 chunks = PyList_New(0);
482 if (NULL == chunks) {
483 return NULL;
484 }
485
486 while (1) {
487 PyObject *chunk = PyObject_CallMethod(self, "read", "i", 1048576);
488 if (NULL == chunk) {
489 Py_DECREF(chunks);
490 return NULL;
491 }
492
493 if (!PyBytes_Size(chunk)) {
494 Py_DECREF(chunk);
495 break;
496 }
497
498 if (PyList_Append(chunks, chunk)) {
499 Py_DECREF(chunk);
500 Py_DECREF(chunks);
501 return NULL;
502 }
503
504 Py_DECREF(chunk);
505 }
506
507 empty = PyBytes_FromStringAndSize("", 0);
508 if (NULL == empty) {
509 Py_DECREF(chunks);
510 return NULL;
511 }
512
513 result = PyObject_CallMethod(empty, "join", "O", chunks);
514
515 Py_DECREF(empty);
516 Py_DECREF(chunks);
517
518 return result;
519 }
520
521 static PyObject *compressionreader_readinto(ZstdCompressionReader *self,
522 PyObject *args) {
523 Py_buffer dest;
524 ZSTD_outBuffer output;
525 int readResult, compressResult;
526 PyObject *result = NULL;
527 size_t zresult;
528 size_t oldPos;
529
530 if (self->closed) {
531 PyErr_SetString(PyExc_ValueError, "stream is closed");
532 return NULL;
533 }
534
535 if (self->finishedOutput) {
536 return PyLong_FromLong(0);
537 }
538
539 if (!PyArg_ParseTuple(args, "w*:readinto", &dest)) {
540 return NULL;
541 }
542
543 output.dst = dest.buf;
544 output.size = dest.len;
545 output.pos = 0;
546
547 compressResult = compress_input(self, &output);
548
549 if (-1 == compressResult) {
550 goto finally;
551 }
552 else if (0 == compressResult) {
553 }
554 else if (1 == compressResult) {
555 result = PyLong_FromSize_t(output.pos);
556 goto finally;
557 }
558 else {
559 assert(0);
560 }
561
562 while (!self->finishedInput) {
563 readResult = read_compressor_input(self);
564
565 if (-1 == readResult) {
566 goto finally;
567 }
568 else if (0 == readResult || 1 == readResult) {
569 }
570 else {
571 assert(0);
572 }
573
574 compressResult = compress_input(self, &output);
575
576 if (-1 == compressResult) {
577 goto finally;
578 }
579 else if (0 == compressResult) {
580 }
581 else if (1 == compressResult) {
582 result = PyLong_FromSize_t(output.pos);
583 goto finally;
584 }
585 else {
586 assert(0);
587 }
588 }
589
590 /* EOF */
591 oldPos = output.pos;
592
593 zresult = ZSTD_compressStream2(self->compressor->cctx, &output,
594 &self->input, ZSTD_e_end);
595
596 self->bytesCompressed += self->output.pos - oldPos;
597
598 if (ZSTD_isError(zresult)) {
599 PyErr_Format(ZstdError, "error ending compression stream: %s",
600 ZSTD_getErrorName(zresult));
601 goto finally;
602 }
603
604 assert(output.pos);
605
606 if (0 == zresult) {
607 self->finishedOutput = 1;
608 }
609
610 result = PyLong_FromSize_t(output.pos);
611
612 finally:
613 PyBuffer_Release(&dest);
614
615 return result;
616 }
617
618 static PyObject *compressionreader_readinto1(ZstdCompressionReader *self,
619 PyObject *args) {
620 Py_buffer dest;
621 PyObject *result = NULL;
622 ZSTD_outBuffer output;
623 int compressResult;
624 size_t oldPos;
625 size_t zresult;
626
627 if (self->closed) {
628 PyErr_SetString(PyExc_ValueError, "stream is closed");
629 return NULL;
630 }
631
632 if (self->finishedOutput) {
633 return PyLong_FromLong(0);
634 }
635
636 if (!PyArg_ParseTuple(args, "w*:readinto1", &dest)) {
637 return NULL;
638 }
639
640 output.dst = dest.buf;
641 output.size = dest.len;
642 output.pos = 0;
643
644 compressResult = compress_input(self, &output);
645
646 if (-1 == compressResult) {
647 goto finally;
648 }
649 else if (0 == compressResult || 1 == compressResult) {
650 }
651 else {
652 assert(0);
653 }
654
655 if (output.pos) {
656 result = PyLong_FromSize_t(output.pos);
657 goto finally;
658 }
659
660 while (!self->finishedInput) {
661 int readResult = read_compressor_input(self);
662
663 if (-1 == readResult) {
664 goto finally;
665 }
666 else if (0 == readResult || 1 == readResult) {
667 }
668 else {
669 assert(0);
670 }
671
672 compressResult = compress_input(self, &output);
673
674 if (-1 == compressResult) {
675 goto finally;
676 }
677 else if (0 == compressResult) {
678 }
679 else if (1 == compressResult) {
680 result = PyLong_FromSize_t(output.pos);
681 goto finally;
682 }
683 else {
684 assert(0);
685 }
686
687 /* If we produced output and we're not done with input, emit
688 * that output now, as we've hit restrictions of read1().
689 */
690 if (output.pos && !self->finishedInput) {
691 result = PyLong_FromSize_t(output.pos);
692 goto finally;
693 }
694
695 /* Otherwise we either have no output or we've exhausted the
696 * input. Either we try to get more input or we fall through
697 * to EOF below */
698 }
699
700 /* EOF */
701 oldPos = output.pos;
702
703 zresult = ZSTD_compressStream2(self->compressor->cctx, &output,
704 &self->input, ZSTD_e_end);
705
706 self->bytesCompressed += self->output.pos - oldPos;
707
708 if (ZSTD_isError(zresult)) {
709 PyErr_Format(ZstdError, "error ending compression stream: %s",
710 ZSTD_getErrorName(zresult));
711 goto finally;
712 }
713
714 assert(output.pos);
715
716 if (0 == zresult) {
717 self->finishedOutput = 1;
718 }
719
720 result = PyLong_FromSize_t(output.pos);
721
722 finally:
723 PyBuffer_Release(&dest);
724
725 return result;
726 }
727
728 static PyObject *compressionreader_iter(PyObject *self) {
729 set_io_unsupported_operation();
730 return NULL;
731 }
732
733 static PyObject *compressionreader_iternext(PyObject *self) {
734 set_io_unsupported_operation();
735 return NULL;
736 }
737
738 static PyMethodDef compressionreader_methods[] = {
739 {"__enter__", (PyCFunction)compressionreader_enter, METH_NOARGS,
740 PyDoc_STR("Enter a compression context")},
741 {"__exit__", (PyCFunction)compressionreader_exit, METH_VARARGS,
742 PyDoc_STR("Exit a compression context")},
743 {"close", (PyCFunction)compressionreader_close, METH_NOARGS,
744 PyDoc_STR("Close the stream so it cannot perform any more operations")},
745 {"flush", (PyCFunction)compressionreader_flush, METH_NOARGS,
746 PyDoc_STR("no-ops")},
747 {"isatty", (PyCFunction)compressionreader_isatty, METH_NOARGS,
748 PyDoc_STR("Returns False")},
749 {"readable", (PyCFunction)compressionreader_readable, METH_NOARGS,
750 PyDoc_STR("Returns True")},
751 {"read", (PyCFunction)compressionreader_read, METH_VARARGS | METH_KEYWORDS,
752 PyDoc_STR("read compressed data")},
753 {"read1", (PyCFunction)compressionreader_read1,
754 METH_VARARGS | METH_KEYWORDS, NULL},
755 {"readall", (PyCFunction)compressionreader_readall, METH_NOARGS,
756 PyDoc_STR("Not implemented")},
757 {"readinto", (PyCFunction)compressionreader_readinto, METH_VARARGS, NULL},
758 {"readinto1", (PyCFunction)compressionreader_readinto1, METH_VARARGS, NULL},
759 {"readline", (PyCFunction)compressionreader_readline, METH_VARARGS,
760 PyDoc_STR("Not implemented")},
761 {"readlines", (PyCFunction)compressionreader_readlines, METH_VARARGS,
762 PyDoc_STR("Not implemented")},
763 {"seekable", (PyCFunction)compressionreader_seekable, METH_NOARGS,
764 PyDoc_STR("Returns False")},
765 {"tell", (PyCFunction)compressionreader_tell, METH_NOARGS,
766 PyDoc_STR("Returns current number of bytes compressed")},
767 {"writable", (PyCFunction)compressionreader_writable, METH_NOARGS,
768 PyDoc_STR("Returns False")},
769 {"write", compressionreader_write, METH_VARARGS,
770 PyDoc_STR("Raises OSError")},
771 {"writelines", compressionreader_writelines, METH_VARARGS,
772 PyDoc_STR("Not implemented")},
773 {NULL, NULL}};
774
775 static PyMemberDef compressionreader_members[] = {
776 {"closed", T_BOOL, offsetof(ZstdCompressionReader, closed), READONLY,
777 "whether stream is closed"},
778 {NULL}};
779
780 PyType_Slot ZstdCompressionReaderSlots[] = {
781 {Py_tp_dealloc, compressionreader_dealloc},
782 {Py_tp_iter, compressionreader_iter},
783 {Py_tp_iternext, compressionreader_iternext},
784 {Py_tp_methods, compressionreader_methods},
785 {Py_tp_members, compressionreader_members},
786 {Py_tp_new, PyType_GenericNew},
787 {0, NULL},
788 };
789
790 PyType_Spec ZstdCompressionReaderSpec = {
791 "zstandard.backend_c.ZstdCompressionReader",
792 sizeof(ZstdCompressionReader),
793 0,
794 Py_TPFLAGS_DEFAULT,
795 ZstdCompressionReaderSlots,
796 };
797
798 PyTypeObject *ZstdCompressionReaderType;
799
800 void compressionreader_module_init(PyObject *mod) {
801 /* TODO make reader a sub-class of io.RawIOBase */
802
803 ZstdCompressionReaderType =
804 (PyTypeObject *)PyType_FromSpec(&ZstdCompressionReaderSpec);
805 if (PyType_Ready(ZstdCompressionReaderType) < 0) {
806 return;
807 }
808
809 Py_INCREF((PyObject *)ZstdCompressionReaderType);
810 PyModule_AddObject(mod, "ZstdCompressionReader",
811 (PyObject *)ZstdCompressionReaderType);
812 }