Debian Codegraph @

src/c/compression_zstd/compressor.c

raw symbols SCIP
1 /* Low level interface to the Zstandard algorithm & the zstd library. */
2
3 /* ZstdCompressor class definitions */
4
5 /*[clinic input]
6 module _zstd
7 class _zstd.ZstdCompressor "ZstdCompressor *" "&zstd_compressor_type_spec"
8 [clinic start generated code]*/
9 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7166021db1ef7df8]*/
10
11 #ifndef Py_BUILD_CORE_BUILTIN
12 # define Py_BUILD_CORE_MODULE 1
13 #endif
14
15 #include "backports_zstd_compat.h"
16 #include "backports_zstd_edits.h"
17
18 #include "Python.h"
19
20 #include "_zstdmodule.h"
21 #include "buffer.h"
22
23 #include <stddef.h> // offsetof()
24 #include <zstd.h> // ZSTD_*()
25
26 typedef struct {
27 PyObject_HEAD
28
29 /* Compression context */
30 ZSTD_CCtx *cctx;
31
32 /* ZstdDict object in use */
33 PyObject *dict;
34
35 /* Last mode, initialized to ZSTD_e_end */
36 int last_mode;
37
38 /* (nbWorker >= 1) ? 1 : 0 */
39 int use_multithread;
40
41 /* Compression level */
42 int compression_level;
43
44 /* Lock to protect the compression context */
45 BACKPORTSZSTD_LOCK lock;
46 } ZstdCompressor;
47
48 #define ZstdCompressor_CAST(op) ((ZstdCompressor *)op)
49
50 /*[python input]
51
52 class zstd_contentsize_converter(CConverter):
53 type = 'unsigned long long'
54 converter = 'zstd_contentsize_converter'
55
56 [python start generated code]*/
57 /*[python end generated code: output=da39a3ee5e6b4b0d input=0932c350d633c7de]*/
58
59
60 static int
61 zstd_contentsize_converter(PyObject *size, unsigned long long *p)
62 {
63 // None means the user indicates the size is unknown.
64 if (size == Py_None) {
65 *p = ZSTD_CONTENTSIZE_UNKNOWN;
66 }
67 else {
68 /* ZSTD_CONTENTSIZE_UNKNOWN is 0ULL - 1
69 ZSTD_CONTENTSIZE_ERROR is 0ULL - 2
70 Users should only pass values < ZSTD_CONTENTSIZE_ERROR */
71 unsigned long long pledged_size = PyLong_AsUnsignedLongLong(size);
72 /* Here we check for (unsigned long long)-1 as a sign of an error in
73 PyLong_AsUnsignedLongLong */
74 if (pledged_size == (unsigned long long)-1 && PyErr_Occurred()) {
75 *p = ZSTD_CONTENTSIZE_ERROR;
76 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
77 PyErr_Format(PyExc_ValueError,
78 "size argument should be a positive int less "
79 "than %llu", ZSTD_CONTENTSIZE_ERROR);
80 return 0;
81 }
82 return 0;
83 }
84 if (pledged_size >= ZSTD_CONTENTSIZE_ERROR) {
85 *p = ZSTD_CONTENTSIZE_ERROR;
86 PyErr_Format(PyExc_ValueError,
87 "size argument should be a positive int less "
88 "than %llu", ZSTD_CONTENTSIZE_ERROR);
89 return 0;
90 }
91 *p = pledged_size;
92 }
93 return 1;
94 }
95
96 #include "clinic/compressor.c.h"
97
98 static int
99 _zstd_set_c_level(ZstdCompressor *self, int level)
100 {
101 /* Set integer compression level */
102 int min_level = ZSTD_minCLevel();
103 int max_level = ZSTD_maxCLevel();
104 if (level < min_level || level > max_level) {
105 PyErr_Format(PyExc_ValueError,
106 "illegal compression level %d; the valid range is [%d, %d]",
107 level, min_level, max_level);
108 return -1;
109 }
110
111 /* Save for generating ZSTD_CDICT */
112 self->compression_level = level;
113
114 /* Set compressionLevel to compression context */
115 size_t zstd_ret = ZSTD_CCtx_setParameter(
116 self->cctx, ZSTD_c_compressionLevel, level);
117
118 /* Check error */
119 if (ZSTD_isError(zstd_ret)) {
120 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
121 set_zstd_error(mod_state, ERR_SET_C_LEVEL, zstd_ret);
122 return -1;
123 }
124 return 0;
125 }
126
127 static int
128 _zstd_set_c_parameters(ZstdCompressor *self, PyObject *options)
129 {
130 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
131 if (mod_state == NULL) {
132 return -1;
133 }
134
135 if (!PyDict_Check(options)) {
136 BACKPORTSZSTD_PyErr_Format_AppendPT(PyExc_TypeError,
137 "ZstdCompressor() argument 'options' must be dict, not ",
138 options);
139 return -1;
140 }
141
142 Py_ssize_t pos = 0;
143 PyObject *key, *value;
144 while (PyDict_Next(options, &pos, &key, &value)) {
145 /* Check key type */
146 if (Py_TYPE(key) == mod_state->DParameter_type) {
147 PyErr_SetString(PyExc_TypeError,
148 "compression options dictionary key must not be a "
149 "DecompressionParameter attribute");
150 return -1;
151 }
152
153 Py_INCREF(key);
154 Py_INCREF(value);
155 int key_v = PyLong_AsInt(key);
156 Py_DECREF(key);
157 if (key_v == -1 && PyErr_Occurred()) {
158 Py_DECREF(value);
159 return -1;
160 }
161
162 int value_v = PyLong_AsInt(value);
163 Py_DECREF(value);
164 if (value_v == -1 && PyErr_Occurred()) {
165 return -1;
166 }
167
168 if (key_v == ZSTD_c_compressionLevel) {
169 if (_zstd_set_c_level(self, value_v) < 0) {
170 return -1;
171 }
172 continue;
173 }
174 if (key_v == ZSTD_c_nbWorkers) {
175 /* From the zstd library docs:
176 1. When nbWorkers >= 1, triggers asynchronous mode when
177 used with ZSTD_compressStream2().
178 2, Default value is `0`, aka "single-threaded mode" : no
179 worker is spawned, compression is performed inside
180 caller's thread, all invocations are blocking. */
181 if (value_v != 0) {
182 self->use_multithread = 1;
183 }
184 }
185
186 /* Set parameter to compression context */
187 size_t zstd_ret = ZSTD_CCtx_setParameter(self->cctx, key_v, value_v);
188
189 /* Check error */
190 if (ZSTD_isError(zstd_ret)) {
191 set_parameter_error(1, key_v, value_v);
192 return -1;
193 }
194 }
195 return 0;
196 }
197
198 static void
199 capsule_free_cdict(PyObject *capsule)
200 {
201 ZSTD_CDict *cdict = PyCapsule_GetPointer(capsule, NULL);
202 ZSTD_freeCDict(cdict);
203 }
204
205 ZSTD_CDict *
206 _get_CDict(ZstdDict *self, int compressionLevel)
207 {
208 assert(BACKPORTSZSTD_LOCK_isLocked(&self->lock));
209 PyObject *level = NULL;
210 PyObject *capsule = NULL;
211 ZSTD_CDict *cdict;
212 int ret;
213
214
215 /* int level object */
216 level = PyLong_FromLong(compressionLevel);
217 if (level == NULL) {
218 goto error;
219 }
220
221 /* Get PyCapsule object from self->c_dicts */
222 ret = PyDict_GetItemRef(self->c_dicts, level, &capsule);
223 if (ret < 0) {
224 goto error;
225 }
226 if (capsule == NULL) {
227 /* Create ZSTD_CDict instance */
228 Py_BEGIN_ALLOW_THREADS
229 cdict = ZSTD_createCDict(self->dict_buffer, self->dict_len,
230 compressionLevel);
231 Py_END_ALLOW_THREADS
232
233 if (cdict == NULL) {
234 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
235 if (mod_state != NULL) {
236 PyErr_SetString(mod_state->ZstdError,
237 "Failed to create a ZSTD_CDict instance from "
238 "Zstandard dictionary content.");
239 }
240 goto error;
241 }
242
243 /* Put ZSTD_CDict instance into PyCapsule object */
244 capsule = PyCapsule_New(cdict, NULL, capsule_free_cdict);
245 if (capsule == NULL) {
246 ZSTD_freeCDict(cdict);
247 goto error;
248 }
249
250 /* Add PyCapsule object to self->c_dicts */
251 ret = PyDict_SetItem(self->c_dicts, level, capsule);
252 if (ret < 0) {
253 goto error;
254 }
255 }
256 else {
257 /* ZSTD_CDict instance already exists */
258 cdict = PyCapsule_GetPointer(capsule, NULL);
259 }
260 goto success;
261
262 error:
263 cdict = NULL;
264 success:
265 Py_XDECREF(level);
266 Py_XDECREF(capsule);
267 return cdict;
268 }
269
270 static int
271 _zstd_load_impl(ZstdCompressor *self, ZstdDict *zd,
272 _zstd_state *mod_state, int type)
273 {
274 size_t zstd_ret;
275 if (type == DICT_TYPE_DIGESTED) {
276 /* Get ZSTD_CDict */
277 ZSTD_CDict *c_dict = _get_CDict(zd, self->compression_level);
278 if (c_dict == NULL) {
279 return -1;
280 }
281 /* Reference a prepared dictionary.
282 It overrides some compression context's parameters. */
283 zstd_ret = ZSTD_CCtx_refCDict(self->cctx, c_dict);
284 }
285 else if (type == DICT_TYPE_UNDIGESTED) {
286 /* Load a dictionary.
287 It doesn't override compression context's parameters. */
288 zstd_ret = ZSTD_CCtx_loadDictionary(self->cctx, zd->dict_buffer,
289 zd->dict_len);
290 }
291 else if (type == DICT_TYPE_PREFIX) {
292 /* Load a prefix */
293 zstd_ret = ZSTD_CCtx_refPrefix(self->cctx, zd->dict_buffer,
294 zd->dict_len);
295 }
296 else {
297 Py_UNREACHABLE();
298 }
299
300 /* Check error */
301 if (ZSTD_isError(zstd_ret)) {
302 set_zstd_error(mod_state, ERR_LOAD_C_DICT, zstd_ret);
303 return -1;
304 }
305 return 0;
306 }
307
308 static int
309 _zstd_load_c_dict(ZstdCompressor *self, PyObject *dict)
310 {
311 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
312 /* When compressing, use undigested dictionary by default. */
313 int type = DICT_TYPE_UNDIGESTED;
314 ZstdDict *zd = _Py_parse_zstd_dict(mod_state, dict, &type);
315 if (zd == NULL) {
316 return -1;
317 }
318 int ret;
319 BACKPORTSZSTD_LOCK_lock(&zd->lock);
320 ret = _zstd_load_impl(self, zd, mod_state, type);
321 BACKPORTSZSTD_LOCK_unlock(&zd->lock);
322 return ret;
323 }
324
325 /*[clinic input]
326 @classmethod
327 _zstd.ZstdCompressor.__new__ as _zstd_ZstdCompressor_new
328 level: object = None
329 The compression level to use. Defaults to COMPRESSION_LEVEL_DEFAULT.
330 options: object = None
331 A dict object that contains advanced compression parameters.
332 zstd_dict: object = None
333 A ZstdDict object, a pre-trained Zstandard dictionary.
334
335 Create a compressor object for compressing data incrementally.
336
337 Thread-safe at method level. For one-shot compression, use the
338 compress() function instead.
339 [clinic start generated code]*/
340
341 static PyObject *
342 _zstd_ZstdCompressor_new_impl(PyTypeObject *type, PyObject *level,
343 PyObject *options, PyObject *zstd_dict)
344 /*[clinic end generated code: output=cdef61eafecac3d7 input=bbfeeaa06fd3bd4d]*/
345 {
346 ZstdCompressor* self = PyObject_GC_New(ZstdCompressor, type);
347 if (self == NULL) {
348 goto error;
349 }
350
351 self->use_multithread = 0;
352 self->compression_level = ZSTD_CLEVEL_DEFAULT;
353 self->dict = NULL;
354 self->lock = BACKPORTSZSTD_LOCK_allocate();
355 if(BACKPORTSZSTD_LOCK_isError(self->lock)) {
356 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
357 if (mod_state != NULL) {
358 PyErr_SetString(mod_state->ZstdError,
359 "Unable to allocate lock");
360 }
361 goto error;
362 }
363
364 /* Compression context */
365 self->cctx = ZSTD_createCCtx();
366 if (self->cctx == NULL) {
367 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
368 if (mod_state != NULL) {
369 PyErr_SetString(mod_state->ZstdError,
370 "Unable to create ZSTD_CCtx instance.");
371 }
372 goto error;
373 }
374
375 /* Last mode */
376 self->last_mode = ZSTD_e_end;
377
378 if (level != Py_None && options != Py_None) {
379 PyErr_SetString(PyExc_TypeError,
380 "Only one of level or options should be used.");
381 goto error;
382 }
383
384 /* Set compression level */
385 if (level != Py_None) {
386 if (!PyLong_Check(level)) {
387 PyErr_SetString(PyExc_TypeError,
388 "invalid type for level, expected int");
389 goto error;
390 }
391 int level_v = PyLong_AsInt(level);
392 if (level_v == -1 && PyErr_Occurred()) {
393 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
394 PyErr_Format(PyExc_ValueError,
395 "illegal compression level; the valid range is [%d, %d]",
396 ZSTD_minCLevel(), ZSTD_maxCLevel());
397 }
398 goto error;
399 }
400 if (_zstd_set_c_level(self, level_v) < 0) {
401 goto error;
402 }
403 }
404
405 /* Set options dictionary */
406 if (options != Py_None) {
407 if (_zstd_set_c_parameters(self, options) < 0) {
408 goto error;
409 }
410 }
411
412 /* Load Zstandard dictionary to compression context */
413 if (zstd_dict != Py_None) {
414 if (_zstd_load_c_dict(self, zstd_dict) < 0) {
415 goto error;
416 }
417 Py_INCREF(zstd_dict);
418 self->dict = zstd_dict;
419 }
420
421 // We can only start GC tracking once self->dict is set.
422 PyObject_GC_Track(self);
423
424 return (PyObject*)self;
425
426 error:
427 Py_XDECREF(self);
428 return NULL;
429 }
430
431 static void
432 ZstdCompressor_dealloc(PyObject *ob)
433 {
434 ZstdCompressor *self = ZstdCompressor_CAST(ob);
435
436 PyObject_GC_UnTrack(self);
437
438 /* Free compression context */
439 if (self->cctx) {
440 ZSTD_freeCCtx(self->cctx);
441 }
442
443 assert(!BACKPORTSZSTD_LOCK_isLocked(&self->lock));
444 BACKPORTSZSTD_LOCK_free(self->lock);
445
446 /* Py_XDECREF the dict after free the compression context */
447 Py_CLEAR(self->dict);
448
449 PyTypeObject *tp = Py_TYPE(self);
450 PyObject_GC_Del(ob);
451 Py_DECREF(tp);
452 }
453
454 static PyObject *
455 compress_lock_held(ZstdCompressor *self, Py_buffer *data,
456 ZSTD_EndDirective end_directive)
457 {
458 assert(BACKPORTSZSTD_LOCK_isLocked(&self->lock));
459 ZSTD_inBuffer in;
460 ZSTD_outBuffer out;
461 _BlocksOutputBuffer buffer = {.list = NULL};
462 size_t zstd_ret;
463 PyObject *ret;
464
465 /* Prepare input & output buffers */
466 if (data != NULL) {
467 in.src = data->buf;
468 in.size = data->len;
469 in.pos = 0;
470 }
471 else {
472 in.src = &in;
473 in.size = 0;
474 in.pos = 0;
475 }
476
477 /* Calculate output buffer's size */
478 size_t output_buffer_size = ZSTD_compressBound(in.size);
479 if (output_buffer_size > (size_t) PY_SSIZE_T_MAX) {
480 PyErr_NoMemory();
481 goto error;
482 }
483
484 if (_OutputBuffer_InitWithSize(&buffer, &out, -1,
485 (Py_ssize_t) output_buffer_size) < 0) {
486 goto error;
487 }
488
489
490 /* Zstandard stream compress */
491 while (1) {
492 Py_BEGIN_ALLOW_THREADS
493 zstd_ret = ZSTD_compressStream2(self->cctx, &out, &in, end_directive);
494 Py_END_ALLOW_THREADS
495
496 /* Check error */
497 if (ZSTD_isError(zstd_ret)) {
498 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
499 set_zstd_error(mod_state, ERR_COMPRESS, zstd_ret);
500 goto error;
501 }
502
503 /* Finished */
504 if (zstd_ret == 0) {
505 break;
506 }
507
508 /* Output buffer should be exhausted, grow the buffer. */
509 assert(out.pos == out.size);
510 if (out.pos == out.size) {
511 if (_OutputBuffer_Grow(&buffer, &out) < 0) {
512 goto error;
513 }
514 }
515 }
516
517 /* Return a bytes object */
518 ret = _OutputBuffer_Finish(&buffer, &out);
519 if (ret != NULL) {
520 return ret;
521 }
522
523 error:
524 _OutputBuffer_OnError(&buffer);
525 return NULL;
526 }
527
528 #ifndef NDEBUG
529 static inline int
530 mt_continue_should_break(ZSTD_inBuffer *in, ZSTD_outBuffer *out)
531 {
532 return in->size == in->pos && out->size != out->pos;
533 }
534 #endif
535
536 static PyObject *
537 compress_mt_continue_lock_held(ZstdCompressor *self, Py_buffer *data)
538 {
539 assert(BACKPORTSZSTD_LOCK_isLocked(&self->lock));
540 ZSTD_inBuffer in;
541 ZSTD_outBuffer out;
542 _BlocksOutputBuffer buffer = {.list = NULL};
543 size_t zstd_ret;
544 PyObject *ret;
545
546 /* Prepare input & output buffers */
547 in.src = data->buf;
548 in.size = data->len;
549 in.pos = 0;
550
551 if (_OutputBuffer_InitAndGrow(&buffer, &out, -1) < 0) {
552 goto error;
553 }
554
555 /* Zstandard stream compress */
556 while (1) {
557 Py_BEGIN_ALLOW_THREADS
558 do {
559 zstd_ret = ZSTD_compressStream2(self->cctx, &out, &in,
560 ZSTD_e_continue);
561 } while (out.pos != out.size
562 && in.pos != in.size
563 && !ZSTD_isError(zstd_ret));
564 Py_END_ALLOW_THREADS
565
566 /* Check error */
567 if (ZSTD_isError(zstd_ret)) {
568 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
569 set_zstd_error(mod_state, ERR_COMPRESS, zstd_ret);
570 goto error;
571 }
572
573 /* Like compress_lock_held(), output as much as possible. */
574 if (out.pos == out.size) {
575 if (_OutputBuffer_Grow(&buffer, &out) < 0) {
576 goto error;
577 }
578 }
579 else if (in.pos == in.size) {
580 /* Finished */
581 assert(mt_continue_should_break(&in, &out));
582 break;
583 }
584 }
585
586 /* Return a bytes object */
587 ret = _OutputBuffer_Finish(&buffer, &out);
588 if (ret != NULL) {
589 return ret;
590 }
591
592 error:
593 _OutputBuffer_OnError(&buffer);
594 return NULL;
595 }
596
597 /*[clinic input]
598 _zstd.ZstdCompressor.compress
599
600 data: Py_buffer
601 mode: int(c_default="ZSTD_e_continue") = ZstdCompressor.CONTINUE
602 Can be these 3 values ZstdCompressor.CONTINUE,
603 ZstdCompressor.FLUSH_BLOCK, ZstdCompressor.FLUSH_FRAME
604
605 Provide data to the compressor object.
606
607 Return a chunk of compressed data if possible, or b'' otherwise.
608 When you have finished providing data to the compressor, call the
609 flush() method to finish the compression process.
610 [clinic start generated code]*/
611
612 static PyObject *
613 _zstd_ZstdCompressor_compress_impl(ZstdCompressor *self, Py_buffer *data,
614 int mode)
615 /*[clinic end generated code: output=ed7982d1cf7b4f98 input=11726dff64d7b2f9]*/
616 {
617 PyObject *ret;
618
619 /* Check mode value */
620 if (mode != ZSTD_e_continue &&
621 mode != ZSTD_e_flush &&
622 mode != ZSTD_e_end)
623 {
624 PyErr_SetString(PyExc_ValueError,
625 "mode argument wrong value, it should be one of "
626 "ZstdCompressor.CONTINUE, ZstdCompressor.FLUSH_BLOCK, "
627 "ZstdCompressor.FLUSH_FRAME.");
628 return NULL;
629 }
630
631 /* Thread-safe code */
632 BACKPORTSZSTD_LOCK_lock(&self->lock);
633
634 /* Compress */
635 if (self->use_multithread && mode == ZSTD_e_continue) {
636 ret = compress_mt_continue_lock_held(self, data);
637 }
638 else {
639 ret = compress_lock_held(self, data, mode);
640 }
641
642 if (ret) {
643 self->last_mode = mode;
644 }
645 else {
646 self->last_mode = ZSTD_e_end;
647
648 /* Resetting cctx's session never fail */
649 ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
650 }
651 BACKPORTSZSTD_LOCK_unlock(&self->lock);
652
653 return ret;
654 }
655
656 /*[clinic input]
657 _zstd.ZstdCompressor.flush
658
659 mode: int(c_default="ZSTD_e_end") = ZstdCompressor.FLUSH_FRAME
660 Can be these 2 values ZstdCompressor.FLUSH_FRAME,
661 ZstdCompressor.FLUSH_BLOCK
662
663 Finish the compression process.
664
665 Flush any remaining data left in internal buffers. Since Zstandard
666 data consists of one or more independent frames, the compressor
667 object can still be used after this method is called.
668 [clinic start generated code]*/
669
670 static PyObject *
671 _zstd_ZstdCompressor_flush_impl(ZstdCompressor *self, int mode)
672 /*[clinic end generated code: output=b7cf2c8d64dcf2e3 input=130e0b1eddf0f498]*/
673 {
674 PyObject *ret;
675
676 /* Check mode value */
677 if (mode != ZSTD_e_end && mode != ZSTD_e_flush) {
678 PyErr_SetString(PyExc_ValueError,
679 "mode argument wrong value, it should be "
680 "ZstdCompressor.FLUSH_FRAME or "
681 "ZstdCompressor.FLUSH_BLOCK.");
682 return NULL;
683 }
684
685 /* Thread-safe code */
686 BACKPORTSZSTD_LOCK_lock(&self->lock);
687
688 ret = compress_lock_held(self, NULL, mode);
689
690 if (ret) {
691 self->last_mode = mode;
692 }
693 else {
694 self->last_mode = ZSTD_e_end;
695
696 /* Resetting cctx's session never fail */
697 ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
698 }
699 BACKPORTSZSTD_LOCK_unlock(&self->lock);
700
701 return ret;
702 }
703
704
705 /*[clinic input]
706 _zstd.ZstdCompressor.set_pledged_input_size
707
708 size: zstd_contentsize
709 The size of the uncompressed data to be provided to the compressor.
710 /
711
712 Set the uncompressed content size to be written into the frame header.
713
714 This method can be used to ensure the header of the frame about to
715 be written includes the size of the data, unless the
716 CompressionParameter.content_size_flag is set to False.
717 If last_mode != FLUSH_FRAME, then a RuntimeError is raised.
718
719 It is important to ensure that the pledged data size matches the
720 actual data size. If they do not match the compressed output data
721 may be corrupted and the final chunk written may be lost.
722 [clinic start generated code]*/
723
724 static PyObject *
725 _zstd_ZstdCompressor_set_pledged_input_size_impl(ZstdCompressor *self,
726 unsigned long long size)
727 /*[clinic end generated code: output=3a09e55cc0e3b4f9 input=d6d1669171af3da4]*/
728 {
729 // Error occured while converting argument, should be unreachable
730 assert(size != ZSTD_CONTENTSIZE_ERROR);
731
732 /* Thread-safe code */
733 BACKPORTSZSTD_LOCK_lock(&self->lock);
734
735 /* Check the current mode */
736 if (self->last_mode != ZSTD_e_end) {
737 PyErr_SetString(PyExc_ValueError,
738 "set_pledged_input_size() method must be called "
739 "when last_mode == FLUSH_FRAME");
740 BACKPORTSZSTD_LOCK_unlock(&self->lock);
741 return NULL;
742 }
743
744 /* Set pledged content size */
745 size_t zstd_ret = ZSTD_CCtx_setPledgedSrcSize(self->cctx, size);
746 BACKPORTSZSTD_LOCK_unlock(&self->lock);
747 if (ZSTD_isError(zstd_ret)) {
748 _zstd_state* mod_state = PyType_GetModuleState(Py_TYPE(self));
749 set_zstd_error(mod_state, ERR_SET_PLEDGED_INPUT_SIZE, zstd_ret);
750 return NULL;
751 }
752
753 Py_RETURN_NONE;
754 }
755
756 static PyMethodDef ZstdCompressor_methods[] = {
757 _ZSTD_ZSTDCOMPRESSOR_COMPRESS_METHODDEF
758 _ZSTD_ZSTDCOMPRESSOR_FLUSH_METHODDEF
759 _ZSTD_ZSTDCOMPRESSOR_SET_PLEDGED_INPUT_SIZE_METHODDEF
760 {NULL, NULL}
761 };
762
763 PyDoc_STRVAR(ZstdCompressor_last_mode_doc,
764 "The last mode used to this compressor object, its value can be .CONTINUE,\n"
765 ".FLUSH_BLOCK, .FLUSH_FRAME. Initialized to .FLUSH_FRAME.\n\n"
766 "It can be used to get the current state of a compressor, such as, data\n"
767 "flushed, or a frame ended.");
768
769 static PyMemberDef ZstdCompressor_members[] = {
770 {"last_mode", Py_T_INT, offsetof(ZstdCompressor, last_mode),
771 Py_READONLY, ZstdCompressor_last_mode_doc},
772 {NULL}
773 };
774
775 static int
776 ZstdCompressor_traverse(PyObject *ob, visitproc visit, void *arg)
777 {
778 ZstdCompressor *self = ZstdCompressor_CAST(ob);
779 Py_VISIT(self->dict);
780 return 0;
781 }
782
783 static int
784 ZstdCompressor_clear(PyObject *ob)
785 {
786 ZstdCompressor *self = ZstdCompressor_CAST(ob);
787 Py_CLEAR(self->dict);
788 return 0;
789 }
790
791 static PyType_Slot zstdcompressor_slots[] = {
792 {Py_tp_new, _zstd_ZstdCompressor_new},
793 {Py_tp_dealloc, ZstdCompressor_dealloc},
794 {Py_tp_methods, ZstdCompressor_methods},
795 {Py_tp_members, ZstdCompressor_members},
796 {Py_tp_doc, (void *)_zstd_ZstdCompressor_new__doc__},
797 {Py_tp_traverse, ZstdCompressor_traverse},
798 {Py_tp_clear, ZstdCompressor_clear},
799 {0, 0}
800 };
801
802 PyType_Spec zstd_compressor_type_spec = {
803 .name = "backports.zstd.ZstdCompressor",
804 .basicsize = sizeof(ZstdCompressor),
805 // Py_TPFLAGS_IMMUTABLETYPE is not used here as several
806 // associated constants need to be added to the type.
807 // PyType_Freeze is called later to set the flag.
808 .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
809 .slots = zstdcompressor_slots,
810 };