LCOV - code coverage report
Current view: top level - Modules - zlibmodule.c (source / functions) Hit Total Coverage
Test: CPython 3.12 LCOV report [commit 5e6661bce9] Lines: 63 904 7.0 %
Date: 2023-03-20 08:15:36 Functions: 6 48 12.5 %
Branches: 47 479 9.8 %

           Branch data     Line data    Source code
       1                 :            : /* zlibmodule.c -- gzip-compatible data compression */
       2                 :            : /* See http://zlib.net/ */
       3                 :            : 
       4                 :            : /* Windows users:  read Python's PCbuild\readme.txt */
       5                 :            : 
       6                 :            : #define PY_SSIZE_T_CLEAN
       7                 :            : 
       8                 :            : #include "Python.h"
       9                 :            : #include "structmember.h"         // PyMemberDef
      10                 :            : #include "zlib.h"
      11                 :            : #include "stdbool.h"
      12                 :            : 
      13                 :            : #if defined(ZLIB_VERNUM) && ZLIB_VERNUM < 0x1221
      14                 :            : #error "At least zlib version 1.2.2.1 is required"
      15                 :            : #endif
      16                 :            : 
      17                 :            : // Blocks output buffer wrappers
      18                 :            : #include "pycore_blocks_output_buffer.h"
      19                 :            : 
      20                 :            : #if OUTPUT_BUFFER_MAX_BLOCK_SIZE > UINT32_MAX
      21                 :            :     #error "The maximum block size accepted by zlib is UINT32_MAX."
      22                 :            : #endif
      23                 :            : 
      24                 :            : /* On success, return value >= 0
      25                 :            :    On failure, return -1 */
      26                 :            : static inline Py_ssize_t
      27                 :          0 : OutputBuffer_InitAndGrow(_BlocksOutputBuffer *buffer, Py_ssize_t max_length,
      28                 :            :                          Bytef **next_out, uint32_t *avail_out)
      29                 :            : {
      30                 :            :     Py_ssize_t allocated;
      31                 :            : 
      32                 :          0 :     allocated = _BlocksOutputBuffer_InitAndGrow(
      33                 :            :                     buffer, max_length, (void**) next_out);
      34                 :          0 :     *avail_out = (uint32_t) allocated;
      35                 :          0 :     return allocated;
      36                 :            : }
      37                 :            : 
      38                 :            : /* On success, return value >= 0
      39                 :            :    On failure, return -1 */
      40                 :            : static inline Py_ssize_t
      41                 :          0 : OutputBuffer_Grow(_BlocksOutputBuffer *buffer,
      42                 :            :                   Bytef **next_out, uint32_t *avail_out)
      43                 :            : {
      44                 :            :     Py_ssize_t allocated;
      45                 :            : 
      46                 :          0 :     allocated = _BlocksOutputBuffer_Grow(
      47                 :          0 :                     buffer, (void**) next_out, (Py_ssize_t) *avail_out);
      48                 :          0 :     *avail_out = (uint32_t) allocated;
      49                 :          0 :     return allocated;
      50                 :            : }
      51                 :            : 
      52                 :            : static inline Py_ssize_t
      53                 :          0 : OutputBuffer_GetDataSize(_BlocksOutputBuffer *buffer, uint32_t avail_out)
      54                 :            : {
      55                 :          0 :     return _BlocksOutputBuffer_GetDataSize(buffer, (Py_ssize_t) avail_out);
      56                 :            : }
      57                 :            : 
      58                 :            : static inline PyObject *
      59                 :          0 : OutputBuffer_Finish(_BlocksOutputBuffer *buffer, uint32_t avail_out)
      60                 :            : {
      61                 :          0 :     return _BlocksOutputBuffer_Finish(buffer, (Py_ssize_t) avail_out);
      62                 :            : }
      63                 :            : 
      64                 :            : static inline void
      65                 :          0 : OutputBuffer_OnError(_BlocksOutputBuffer *buffer)
      66                 :            : {
      67                 :          0 :     _BlocksOutputBuffer_OnError(buffer);
      68                 :          0 : }
      69                 :            : 
      70                 :            : /* The max buffer size accepted by zlib is UINT32_MAX, the initial buffer size
      71                 :            :    `init_size` may > it in 64-bit build. These wrapper functions maintain an
      72                 :            :    UINT32_MAX sliding window for the first block:
      73                 :            :     1. OutputBuffer_WindowInitWithSize()
      74                 :            :     2. OutputBuffer_WindowGrow()
      75                 :            :     3. OutputBuffer_WindowFinish()
      76                 :            :     4. OutputBuffer_WindowOnError()
      77                 :            : 
      78                 :            :    ==== is the sliding window:
      79                 :            :     1. ====------
      80                 :            :            ^ next_posi, left_bytes is 6
      81                 :            :     2. ----====--
      82                 :            :                ^ next_posi, left_bytes is 2
      83                 :            :     3. --------==
      84                 :            :                  ^ next_posi, left_bytes is 0  */
      85                 :            : typedef struct {
      86                 :            :     Py_ssize_t left_bytes;
      87                 :            :     Bytef *next_posi;
      88                 :            : } _Uint32Window;
      89                 :            : 
      90                 :            : /* Initialize the buffer with an initial buffer size.
      91                 :            : 
      92                 :            :    On success, return value >= 0
      93                 :            :    On failure, return value < 0 */
      94                 :            : static inline Py_ssize_t
      95                 :          0 : OutputBuffer_WindowInitWithSize(_BlocksOutputBuffer *buffer, _Uint32Window *window,
      96                 :            :                                 Py_ssize_t init_size,
      97                 :            :                                 Bytef **next_out, uint32_t *avail_out)
      98                 :            : {
      99                 :          0 :     Py_ssize_t allocated = _BlocksOutputBuffer_InitWithSize(
     100                 :            :                                buffer, init_size, (void**) next_out);
     101                 :            : 
     102         [ #  # ]:          0 :     if (allocated >= 0) {
     103                 :            :         // the UINT32_MAX sliding window
     104                 :          0 :         Py_ssize_t window_size = Py_MIN((size_t)allocated, UINT32_MAX);
     105                 :          0 :         *avail_out = (uint32_t) window_size;
     106                 :            : 
     107                 :          0 :         window->left_bytes = allocated - window_size;
     108                 :          0 :         window->next_posi = *next_out + window_size;
     109                 :            :     }
     110                 :          0 :     return allocated;
     111                 :            : }
     112                 :            : 
     113                 :            : /* Grow the buffer.
     114                 :            : 
     115                 :            :    On success, return value >= 0
     116                 :            :    On failure, return value < 0 */
     117                 :            : static inline Py_ssize_t
     118                 :          0 : OutputBuffer_WindowGrow(_BlocksOutputBuffer *buffer, _Uint32Window *window,
     119                 :            :                         Bytef **next_out, uint32_t *avail_out)
     120                 :            : {
     121                 :            :     Py_ssize_t allocated;
     122                 :            : 
     123                 :            :     /* ensure no gaps in the data.
     124                 :            :        if inlined, this check could be optimized away.*/
     125         [ #  # ]:          0 :     if (*avail_out != 0) {
     126                 :          0 :         PyErr_SetString(PyExc_SystemError,
     127                 :            :                         "*avail_out != 0 in OutputBuffer_WindowGrow().");
     128                 :          0 :         return -1;
     129                 :            :     }
     130                 :            : 
     131                 :            :     // slide the UINT32_MAX sliding window
     132         [ #  # ]:          0 :     if (window->left_bytes > 0) {
     133                 :          0 :         Py_ssize_t window_size = Py_MIN((size_t)window->left_bytes, UINT32_MAX);
     134                 :            : 
     135                 :          0 :         *next_out = window->next_posi;
     136                 :          0 :         *avail_out = (uint32_t) window_size;
     137                 :            : 
     138                 :          0 :         window->left_bytes -= window_size;
     139                 :          0 :         window->next_posi += window_size;
     140                 :            : 
     141                 :          0 :         return window_size;
     142                 :            :     }
     143                 :            :     assert(window->left_bytes == 0);
     144                 :            : 
     145                 :            :     // only the first block may > UINT32_MAX
     146                 :          0 :     allocated = _BlocksOutputBuffer_Grow(
     147                 :          0 :                     buffer, (void**) next_out, (Py_ssize_t) *avail_out);
     148                 :          0 :     *avail_out = (uint32_t) allocated;
     149                 :          0 :     return allocated;
     150                 :            : }
     151                 :            : 
     152                 :            : /* Finish the buffer.
     153                 :            : 
     154                 :            :    On success, return a bytes object
     155                 :            :    On failure, return NULL */
     156                 :            : static inline PyObject *
     157                 :          0 : OutputBuffer_WindowFinish(_BlocksOutputBuffer *buffer, _Uint32Window *window,
     158                 :            :                           uint32_t avail_out)
     159                 :            : {
     160                 :          0 :     Py_ssize_t real_avail_out = (Py_ssize_t) avail_out + window->left_bytes;
     161                 :          0 :     return _BlocksOutputBuffer_Finish(buffer, real_avail_out);
     162                 :            : }
     163                 :            : 
     164                 :            : static inline void
     165                 :          0 : OutputBuffer_WindowOnError(_BlocksOutputBuffer *buffer, _Uint32Window *window)
     166                 :            : {
     167                 :          0 :     _BlocksOutputBuffer_OnError(buffer);
     168                 :          0 : }
     169                 :            : 
     170                 :            : 
     171                 :            : #define ENTER_ZLIB(obj) do {                      \
     172                 :            :     if (!PyThread_acquire_lock((obj)->lock, 0)) { \
     173                 :            :         Py_BEGIN_ALLOW_THREADS                    \
     174                 :            :         PyThread_acquire_lock((obj)->lock, 1);    \
     175                 :            :         Py_END_ALLOW_THREADS                      \
     176                 :            :     } } while (0)
     177                 :            : #define LEAVE_ZLIB(obj) PyThread_release_lock((obj)->lock);
     178                 :            : 
     179                 :            : 
     180                 :            : /* The following parameters are copied from zutil.h, version 0.95 */
     181                 :            : #define DEFLATED   8
     182                 :            : #if MAX_MEM_LEVEL >= 8
     183                 :            : #  define DEF_MEM_LEVEL 8
     184                 :            : #else
     185                 :            : #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
     186                 :            : #endif
     187                 :            : 
     188                 :            : /* Initial buffer size. */
     189                 :            : #define DEF_BUF_SIZE (16*1024)
     190                 :            : #define DEF_MAX_INITIAL_BUF_SIZE (16 * 1024 * 1024)
     191                 :            : 
     192                 :            : static PyModuleDef zlibmodule;
     193                 :            : 
     194                 :            : typedef struct {
     195                 :            :     PyTypeObject *Comptype;
     196                 :            :     PyTypeObject *Decomptype;
     197                 :            :     PyTypeObject *ZlibDecompressorType;
     198                 :            :     PyObject *ZlibError;
     199                 :            : } zlibstate;
     200                 :            : 
     201                 :            : static inline zlibstate*
     202                 :         51 : get_zlib_state(PyObject *module)
     203                 :            : {
     204                 :         51 :     void *state = PyModule_GetState(module);
     205                 :            :     assert(state != NULL);
     206                 :         51 :     return (zlibstate *)state;
     207                 :            : }
     208                 :            : 
     209                 :            : typedef struct
     210                 :            : {
     211                 :            :     PyObject_HEAD
     212                 :            :     z_stream zst;
     213                 :            :     PyObject *unused_data;
     214                 :            :     PyObject *unconsumed_tail;
     215                 :            :     char eof;
     216                 :            :     bool is_initialised;
     217                 :            :     PyObject *zdict;
     218                 :            :     PyThread_type_lock lock;
     219                 :            : } compobject;
     220                 :            : 
     221                 :            : static void
     222                 :          0 : zlib_error(zlibstate *state, z_stream zst, int err, const char *msg)
     223                 :            : {
     224                 :          0 :     const char *zmsg = Z_NULL;
     225                 :            :     /* In case of a version mismatch, zst.msg won't be initialized.
     226                 :            :        Check for this case first, before looking at zst.msg. */
     227         [ #  # ]:          0 :     if (err == Z_VERSION_ERROR)
     228                 :          0 :         zmsg = "library version mismatch";
     229         [ #  # ]:          0 :     if (zmsg == Z_NULL)
     230                 :          0 :         zmsg = zst.msg;
     231         [ #  # ]:          0 :     if (zmsg == Z_NULL) {
     232   [ #  #  #  # ]:          0 :         switch (err) {
     233                 :          0 :         case Z_BUF_ERROR:
     234                 :          0 :             zmsg = "incomplete or truncated stream";
     235                 :          0 :             break;
     236                 :          0 :         case Z_STREAM_ERROR:
     237                 :          0 :             zmsg = "inconsistent stream state";
     238                 :          0 :             break;
     239                 :          0 :         case Z_DATA_ERROR:
     240                 :          0 :             zmsg = "invalid input data";
     241                 :          0 :             break;
     242                 :            :         }
     243                 :          0 :     }
     244         [ #  # ]:          0 :     if (zmsg == Z_NULL)
     245                 :          0 :         PyErr_Format(state->ZlibError, "Error %d %s", err, msg);
     246                 :            :     else
     247                 :          0 :         PyErr_Format(state->ZlibError, "Error %d %s: %.200s", err, msg, zmsg);
     248                 :          0 : }
     249                 :            : 
     250                 :            : /*[clinic input]
     251                 :            : module zlib
     252                 :            : class zlib.Compress "compobject *" "&Comptype"
     253                 :            : class zlib.Decompress "compobject *" "&Decomptype"
     254                 :            : [clinic start generated code]*/
     255                 :            : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=093935115c3e3158]*/
     256                 :            : 
     257                 :            : static compobject *
     258                 :          0 : newcompobject(PyTypeObject *type)
     259                 :            : {
     260                 :            :     compobject *self;
     261                 :          0 :     self = PyObject_New(compobject, type);
     262         [ #  # ]:          0 :     if (self == NULL)
     263                 :          0 :         return NULL;
     264                 :          0 :     self->eof = 0;
     265                 :          0 :     self->is_initialised = 0;
     266                 :          0 :     self->zdict = NULL;
     267                 :          0 :     self->unused_data = PyBytes_FromStringAndSize("", 0);
     268         [ #  # ]:          0 :     if (self->unused_data == NULL) {
     269                 :          0 :         Py_DECREF(self);
     270                 :          0 :         return NULL;
     271                 :            :     }
     272                 :          0 :     self->unconsumed_tail = PyBytes_FromStringAndSize("", 0);
     273         [ #  # ]:          0 :     if (self->unconsumed_tail == NULL) {
     274                 :          0 :         Py_DECREF(self);
     275                 :          0 :         return NULL;
     276                 :            :     }
     277                 :          0 :     self->lock = PyThread_allocate_lock();
     278         [ #  # ]:          0 :     if (self->lock == NULL) {
     279                 :          0 :         Py_DECREF(self);
     280                 :          0 :         PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
     281                 :          0 :         return NULL;
     282                 :            :     }
     283                 :          0 :     return self;
     284                 :            : }
     285                 :            : 
     286                 :            : static void*
     287                 :          0 : PyZlib_Malloc(voidpf ctx, uInt items, uInt size)
     288                 :            : {
     289   [ #  #  #  # ]:          0 :     if (size != 0 && items > (size_t)PY_SSIZE_T_MAX / size)
     290                 :          0 :         return NULL;
     291                 :            :     /* PyMem_Malloc() cannot be used: the GIL is not held when
     292                 :            :        inflate() and deflate() are called */
     293                 :          0 :     return PyMem_RawMalloc((size_t)items * (size_t)size);
     294                 :            : }
     295                 :            : 
     296                 :            : static void
     297                 :          0 : PyZlib_Free(voidpf ctx, void *ptr)
     298                 :            : {
     299                 :          0 :     PyMem_RawFree(ptr);
     300                 :          0 : }
     301                 :            : 
     302                 :            : static void
     303                 :          0 : arrange_input_buffer(z_stream *zst, Py_ssize_t *remains)
     304                 :            : {
     305         [ #  # ]:          0 :     zst->avail_in = (uInt)Py_MIN((size_t)*remains, UINT_MAX);
     306                 :          0 :     *remains -= zst->avail_in;
     307                 :          0 : }
     308                 :            : 
     309                 :            : /*[clinic input]
     310                 :            : zlib.compress
     311                 :            : 
     312                 :            :     data: Py_buffer
     313                 :            :         Binary data to be compressed.
     314                 :            :     /
     315                 :            :     level: int(c_default="Z_DEFAULT_COMPRESSION") = Z_DEFAULT_COMPRESSION
     316                 :            :         Compression level, in 0-9 or -1.
     317                 :            :     wbits: int(c_default="MAX_WBITS") = MAX_WBITS
     318                 :            :         The window buffer size and container format.
     319                 :            : 
     320                 :            : Returns a bytes object containing compressed data.
     321                 :            : [clinic start generated code]*/
     322                 :            : 
     323                 :            : static PyObject *
     324                 :          0 : zlib_compress_impl(PyObject *module, Py_buffer *data, int level, int wbits)
     325                 :            : /*[clinic end generated code: output=46bd152fadd66df2 input=c4d06ee5782a7e3f]*/
     326                 :            : {
     327                 :            :     PyObject *return_value;
     328                 :            :     int flush;
     329                 :            :     z_stream zst;
     330                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
     331                 :            : 
     332                 :          0 :     zlibstate *state = get_zlib_state(module);
     333                 :            : 
     334                 :          0 :     Byte *ibuf = data->buf;
     335                 :          0 :     Py_ssize_t ibuflen = data->len;
     336                 :            : 
     337         [ #  # ]:          0 :     if (OutputBuffer_InitAndGrow(&buffer, -1, &zst.next_out, &zst.avail_out) < 0) {
     338                 :          0 :         goto error;
     339                 :            :     }
     340                 :            : 
     341                 :          0 :     zst.opaque = NULL;
     342                 :          0 :     zst.zalloc = PyZlib_Malloc;
     343                 :          0 :     zst.zfree = PyZlib_Free;
     344                 :          0 :     zst.next_in = ibuf;
     345                 :          0 :     int err = deflateInit2(&zst, level, DEFLATED, wbits, DEF_MEM_LEVEL,
     346                 :            :                            Z_DEFAULT_STRATEGY);
     347                 :            : 
     348   [ #  #  #  # ]:          0 :     switch (err) {
     349                 :          0 :     case Z_OK:
     350                 :          0 :         break;
     351                 :          0 :     case Z_MEM_ERROR:
     352                 :          0 :         PyErr_SetString(PyExc_MemoryError,
     353                 :            :                         "Out of memory while compressing data");
     354                 :          0 :         goto error;
     355                 :          0 :     case Z_STREAM_ERROR:
     356                 :          0 :         PyErr_SetString(state->ZlibError, "Bad compression level");
     357                 :          0 :         goto error;
     358                 :          0 :     default:
     359                 :          0 :         deflateEnd(&zst);
     360                 :          0 :         zlib_error(state, zst, err, "while compressing data");
     361                 :          0 :         goto error;
     362                 :            :     }
     363                 :            : 
     364                 :          0 :     do {
     365                 :          0 :         arrange_input_buffer(&zst, &ibuflen);
     366         [ #  # ]:          0 :         flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
     367                 :            : 
     368                 :            :         do {
     369         [ #  # ]:          0 :             if (zst.avail_out == 0) {
     370         [ #  # ]:          0 :                 if (OutputBuffer_Grow(&buffer, &zst.next_out, &zst.avail_out) < 0) {
     371                 :          0 :                     deflateEnd(&zst);
     372                 :          0 :                     goto error;
     373                 :            :                 }
     374                 :            :             }
     375                 :            : 
     376                 :          0 :             Py_BEGIN_ALLOW_THREADS
     377                 :          0 :             err = deflate(&zst, flush);
     378                 :          0 :             Py_END_ALLOW_THREADS
     379                 :            : 
     380         [ #  # ]:          0 :             if (err == Z_STREAM_ERROR) {
     381                 :          0 :                 deflateEnd(&zst);
     382                 :          0 :                 zlib_error(state, zst, err, "while compressing data");
     383                 :          0 :                 goto error;
     384                 :            :             }
     385                 :            : 
     386         [ #  # ]:          0 :         } while (zst.avail_out == 0);
     387                 :            :         assert(zst.avail_in == 0);
     388                 :            : 
     389         [ #  # ]:          0 :     } while (flush != Z_FINISH);
     390                 :            :     assert(err == Z_STREAM_END);
     391                 :            : 
     392                 :          0 :     err = deflateEnd(&zst);
     393         [ #  # ]:          0 :     if (err == Z_OK) {
     394                 :          0 :         return_value = OutputBuffer_Finish(&buffer, zst.avail_out);
     395         [ #  # ]:          0 :         if (return_value == NULL) {
     396                 :          0 :             goto error;
     397                 :            :         }
     398                 :          0 :         return return_value;
     399                 :            :     }
     400                 :            :     else
     401                 :          0 :         zlib_error(state, zst, err, "while finishing compression");
     402                 :          0 :  error:
     403                 :          0 :     OutputBuffer_OnError(&buffer);
     404                 :          0 :     return NULL;
     405                 :            : }
     406                 :            : 
     407                 :            : /*[clinic input]
     408                 :            : zlib.decompress
     409                 :            : 
     410                 :            :     data: Py_buffer
     411                 :            :         Compressed data.
     412                 :            :     /
     413                 :            :     wbits: int(c_default="MAX_WBITS") = MAX_WBITS
     414                 :            :         The window buffer size and container format.
     415                 :            :     bufsize: Py_ssize_t(c_default="DEF_BUF_SIZE") = DEF_BUF_SIZE
     416                 :            :         The initial output buffer size.
     417                 :            : 
     418                 :            : Returns a bytes object containing the uncompressed data.
     419                 :            : [clinic start generated code]*/
     420                 :            : 
     421                 :            : static PyObject *
     422                 :          0 : zlib_decompress_impl(PyObject *module, Py_buffer *data, int wbits,
     423                 :            :                      Py_ssize_t bufsize)
     424                 :            : /*[clinic end generated code: output=77c7e35111dc8c42 input=a9ac17beff1f893f]*/
     425                 :            : {
     426                 :            :     PyObject *return_value;
     427                 :            :     Byte *ibuf;
     428                 :            :     Py_ssize_t ibuflen;
     429                 :            :     int err, flush;
     430                 :            :     z_stream zst;
     431                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
     432                 :            :     _Uint32Window window;  // output buffer's UINT32_MAX sliding window
     433                 :            : 
     434                 :          0 :     zlibstate *state = get_zlib_state(module);
     435                 :            : 
     436         [ #  # ]:          0 :     if (bufsize < 0) {
     437                 :          0 :         PyErr_SetString(PyExc_ValueError, "bufsize must be non-negative");
     438                 :          0 :         return NULL;
     439         [ #  # ]:          0 :     } else if (bufsize == 0) {
     440                 :          0 :         bufsize = 1;
     441                 :            :     }
     442                 :            : 
     443         [ #  # ]:          0 :     if (OutputBuffer_WindowInitWithSize(&buffer, &window, bufsize,
     444                 :            :                                         &zst.next_out, &zst.avail_out) < 0) {
     445                 :          0 :         goto error;
     446                 :            :     }
     447                 :            : 
     448                 :          0 :     ibuf = data->buf;
     449                 :          0 :     ibuflen = data->len;
     450                 :            : 
     451                 :          0 :     zst.opaque = NULL;
     452                 :          0 :     zst.zalloc = PyZlib_Malloc;
     453                 :          0 :     zst.zfree = PyZlib_Free;
     454                 :          0 :     zst.avail_in = 0;
     455                 :          0 :     zst.next_in = ibuf;
     456                 :          0 :     err = inflateInit2(&zst, wbits);
     457                 :            : 
     458      [ #  #  # ]:          0 :     switch (err) {
     459                 :          0 :     case Z_OK:
     460                 :          0 :         break;
     461                 :          0 :     case Z_MEM_ERROR:
     462                 :          0 :         PyErr_SetString(PyExc_MemoryError,
     463                 :            :                         "Out of memory while decompressing data");
     464                 :          0 :         goto error;
     465                 :          0 :     default:
     466                 :          0 :         inflateEnd(&zst);
     467                 :          0 :         zlib_error(state, zst, err, "while preparing to decompress data");
     468                 :          0 :         goto error;
     469                 :            :     }
     470                 :            : 
     471                 :          0 :     do {
     472                 :          0 :         arrange_input_buffer(&zst, &ibuflen);
     473         [ #  # ]:          0 :         flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
     474                 :            : 
     475                 :            :         do {
     476         [ #  # ]:          0 :             if (zst.avail_out == 0) {
     477         [ #  # ]:          0 :                 if (OutputBuffer_WindowGrow(&buffer, &window,
     478                 :            :                                             &zst.next_out, &zst.avail_out) < 0) {
     479                 :          0 :                     inflateEnd(&zst);
     480                 :          0 :                     goto error;
     481                 :            :                 }
     482                 :            :             }
     483                 :            : 
     484                 :          0 :             Py_BEGIN_ALLOW_THREADS
     485                 :          0 :             err = inflate(&zst, flush);
     486                 :          0 :             Py_END_ALLOW_THREADS
     487                 :            : 
     488      [ #  #  # ]:          0 :             switch (err) {
     489                 :          0 :             case Z_OK:            /* fall through */
     490                 :            :             case Z_BUF_ERROR:     /* fall through */
     491                 :            :             case Z_STREAM_END:
     492                 :          0 :                 break;
     493                 :          0 :             case Z_MEM_ERROR:
     494                 :          0 :                 inflateEnd(&zst);
     495                 :          0 :                 PyErr_SetString(PyExc_MemoryError,
     496                 :            :                                 "Out of memory while decompressing data");
     497                 :          0 :                 goto error;
     498                 :          0 :             default:
     499                 :          0 :                 inflateEnd(&zst);
     500                 :          0 :                 zlib_error(state, zst, err, "while decompressing data");
     501                 :          0 :                 goto error;
     502                 :            :             }
     503                 :            : 
     504         [ #  # ]:          0 :         } while (zst.avail_out == 0);
     505                 :            : 
     506   [ #  #  #  # ]:          0 :     } while (err != Z_STREAM_END && ibuflen != 0);
     507                 :            : 
     508                 :            : 
     509         [ #  # ]:          0 :     if (err != Z_STREAM_END) {
     510                 :          0 :         inflateEnd(&zst);
     511                 :          0 :         zlib_error(state, zst, err, "while decompressing data");
     512                 :          0 :         goto error;
     513                 :            :     }
     514                 :            : 
     515                 :          0 :     err = inflateEnd(&zst);
     516         [ #  # ]:          0 :     if (err != Z_OK) {
     517                 :          0 :         zlib_error(state, zst, err, "while finishing decompression");
     518                 :          0 :         goto error;
     519                 :            :     }
     520                 :            : 
     521                 :          0 :     return_value = OutputBuffer_WindowFinish(&buffer, &window, zst.avail_out);
     522         [ #  # ]:          0 :     if (return_value != NULL) {
     523                 :          0 :         return return_value;
     524                 :            :     }
     525                 :            : 
     526                 :          0 :  error:
     527                 :          0 :     OutputBuffer_WindowOnError(&buffer, &window);
     528                 :          0 :     return NULL;
     529                 :            : }
     530                 :            : 
     531                 :            : /*[clinic input]
     532                 :            : zlib.compressobj
     533                 :            : 
     534                 :            :     level: int(c_default="Z_DEFAULT_COMPRESSION") = Z_DEFAULT_COMPRESSION
     535                 :            :         The compression level (an integer in the range 0-9 or -1; default is
     536                 :            :         currently equivalent to 6).  Higher compression levels are slower,
     537                 :            :         but produce smaller results.
     538                 :            :     method: int(c_default="DEFLATED") = DEFLATED
     539                 :            :         The compression algorithm.  If given, this must be DEFLATED.
     540                 :            :     wbits: int(c_default="MAX_WBITS") = MAX_WBITS
     541                 :            :         +9 to +15: The base-two logarithm of the window size.  Include a zlib
     542                 :            :             container.
     543                 :            :         -9 to -15: Generate a raw stream.
     544                 :            :         +25 to +31: Include a gzip container.
     545                 :            :     memLevel: int(c_default="DEF_MEM_LEVEL") = DEF_MEM_LEVEL
     546                 :            :         Controls the amount of memory used for internal compression state.
     547                 :            :         Valid values range from 1 to 9.  Higher values result in higher memory
     548                 :            :         usage, faster compression, and smaller output.
     549                 :            :     strategy: int(c_default="Z_DEFAULT_STRATEGY") = Z_DEFAULT_STRATEGY
     550                 :            :         Used to tune the compression algorithm.  Possible values are
     551                 :            :         Z_DEFAULT_STRATEGY, Z_FILTERED, and Z_HUFFMAN_ONLY.
     552                 :            :     zdict: Py_buffer = None
     553                 :            :         The predefined compression dictionary - a sequence of bytes
     554                 :            :         containing subsequences that are likely to occur in the input data.
     555                 :            : 
     556                 :            : Return a compressor object.
     557                 :            : [clinic start generated code]*/
     558                 :            : 
     559                 :            : static PyObject *
     560                 :          0 : zlib_compressobj_impl(PyObject *module, int level, int method, int wbits,
     561                 :            :                       int memLevel, int strategy, Py_buffer *zdict)
     562                 :            : /*[clinic end generated code: output=8b5bed9c8fc3814d input=2fa3d026f90ab8d5]*/
     563                 :            : {
     564                 :          0 :     zlibstate *state = get_zlib_state(module);
     565   [ #  #  #  # ]:          0 :     if (zdict->buf != NULL && (size_t)zdict->len > UINT_MAX) {
     566                 :          0 :         PyErr_SetString(PyExc_OverflowError,
     567                 :            :                         "zdict length does not fit in an unsigned int");
     568                 :          0 :         return NULL;
     569                 :            :     }
     570                 :            : 
     571                 :          0 :     compobject *self = newcompobject(state->Comptype);
     572         [ #  # ]:          0 :     if (self == NULL)
     573                 :          0 :         goto error;
     574                 :          0 :     self->zst.opaque = NULL;
     575                 :          0 :     self->zst.zalloc = PyZlib_Malloc;
     576                 :          0 :     self->zst.zfree = PyZlib_Free;
     577                 :          0 :     self->zst.next_in = NULL;
     578                 :          0 :     self->zst.avail_in = 0;
     579                 :          0 :     int err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy);
     580   [ #  #  #  # ]:          0 :     switch (err) {
     581                 :          0 :     case Z_OK:
     582                 :          0 :         self->is_initialised = 1;
     583         [ #  # ]:          0 :         if (zdict->buf == NULL) {
     584                 :          0 :             goto success;
     585                 :            :         } else {
     586                 :          0 :             err = deflateSetDictionary(&self->zst,
     587                 :          0 :                                        zdict->buf, (unsigned int)zdict->len);
     588      [ #  #  # ]:          0 :             switch (err) {
     589                 :          0 :             case Z_OK:
     590                 :          0 :                 goto success;
     591                 :          0 :             case Z_STREAM_ERROR:
     592                 :          0 :                 PyErr_SetString(PyExc_ValueError, "Invalid dictionary");
     593                 :          0 :                 goto error;
     594                 :          0 :             default:
     595                 :          0 :                 PyErr_SetString(PyExc_ValueError, "deflateSetDictionary()");
     596                 :          0 :                 goto error;
     597                 :            :             }
     598                 :            :        }
     599                 :          0 :     case Z_MEM_ERROR:
     600                 :          0 :         PyErr_SetString(PyExc_MemoryError,
     601                 :            :                         "Can't allocate memory for compression object");
     602                 :          0 :         goto error;
     603                 :          0 :     case Z_STREAM_ERROR:
     604                 :          0 :         PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
     605                 :          0 :         goto error;
     606                 :          0 :     default:
     607                 :          0 :         zlib_error(state, self->zst, err, "while creating compression object");
     608                 :          0 :         goto error;
     609                 :            :     }
     610                 :            : 
     611                 :          0 :  error:
     612         [ #  # ]:          0 :     Py_CLEAR(self);
     613                 :          0 :  success:
     614                 :          0 :     return (PyObject *)self;
     615                 :            : }
     616                 :            : 
     617                 :            : static int
     618                 :          0 : set_inflate_zdict(zlibstate *state, compobject *self)
     619                 :            : {
     620                 :            :     Py_buffer zdict_buf;
     621         [ #  # ]:          0 :     if (PyObject_GetBuffer(self->zdict, &zdict_buf, PyBUF_SIMPLE) == -1) {
     622                 :          0 :         return -1;
     623                 :            :     }
     624         [ #  # ]:          0 :     if ((size_t)zdict_buf.len > UINT_MAX) {
     625                 :          0 :         PyErr_SetString(PyExc_OverflowError,
     626                 :            :                         "zdict length does not fit in an unsigned int");
     627                 :          0 :         PyBuffer_Release(&zdict_buf);
     628                 :          0 :         return -1;
     629                 :            :     }
     630                 :            :     int err;
     631                 :          0 :     err = inflateSetDictionary(&self->zst,
     632                 :          0 :                                zdict_buf.buf, (unsigned int)zdict_buf.len);
     633                 :          0 :     PyBuffer_Release(&zdict_buf);
     634         [ #  # ]:          0 :     if (err != Z_OK) {
     635                 :          0 :         zlib_error(state, self->zst, err, "while setting zdict");
     636                 :          0 :         return -1;
     637                 :            :     }
     638                 :          0 :     return 0;
     639                 :            : }
     640                 :            : 
     641                 :            : /*[clinic input]
     642                 :            : zlib.decompressobj
     643                 :            : 
     644                 :            :     wbits: int(c_default="MAX_WBITS") = MAX_WBITS
     645                 :            :         The window buffer size and container format.
     646                 :            :     zdict: object(c_default="NULL") = b''
     647                 :            :         The predefined compression dictionary.  This must be the same
     648                 :            :         dictionary as used by the compressor that produced the input data.
     649                 :            : 
     650                 :            : Return a decompressor object.
     651                 :            : [clinic start generated code]*/
     652                 :            : 
     653                 :            : static PyObject *
     654                 :          0 : zlib_decompressobj_impl(PyObject *module, int wbits, PyObject *zdict)
     655                 :            : /*[clinic end generated code: output=3069b99994f36906 input=d3832b8511fc977b]*/
     656                 :            : {
     657                 :          0 :     zlibstate *state = get_zlib_state(module);
     658                 :            : 
     659   [ #  #  #  # ]:          0 :     if (zdict != NULL && !PyObject_CheckBuffer(zdict)) {
     660                 :          0 :         PyErr_SetString(PyExc_TypeError,
     661                 :            :                         "zdict argument must support the buffer protocol");
     662                 :          0 :         return NULL;
     663                 :            :     }
     664                 :            : 
     665                 :          0 :     compobject *self = newcompobject(state->Decomptype);
     666         [ #  # ]:          0 :     if (self == NULL)
     667                 :          0 :         return NULL;
     668                 :          0 :     self->zst.opaque = NULL;
     669                 :          0 :     self->zst.zalloc = PyZlib_Malloc;
     670                 :          0 :     self->zst.zfree = PyZlib_Free;
     671                 :          0 :     self->zst.next_in = NULL;
     672                 :          0 :     self->zst.avail_in = 0;
     673         [ #  # ]:          0 :     if (zdict != NULL) {
     674                 :          0 :         self->zdict = Py_NewRef(zdict);
     675                 :            :     }
     676                 :          0 :     int err = inflateInit2(&self->zst, wbits);
     677   [ #  #  #  # ]:          0 :     switch (err) {
     678                 :          0 :     case Z_OK:
     679                 :          0 :         self->is_initialised = 1;
     680   [ #  #  #  # ]:          0 :         if (self->zdict != NULL && wbits < 0) {
     681         [ #  # ]:          0 :             if (set_inflate_zdict(state, self) < 0) {
     682                 :          0 :                 Py_DECREF(self);
     683                 :          0 :                 return NULL;
     684                 :            :             }
     685                 :            :         }
     686                 :          0 :         return (PyObject *)self;
     687                 :          0 :     case Z_STREAM_ERROR:
     688                 :          0 :         Py_DECREF(self);
     689                 :          0 :         PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
     690                 :          0 :         return NULL;
     691                 :          0 :     case Z_MEM_ERROR:
     692                 :          0 :         Py_DECREF(self);
     693                 :          0 :         PyErr_SetString(PyExc_MemoryError,
     694                 :            :                         "Can't allocate memory for decompression object");
     695                 :          0 :         return NULL;
     696                 :          0 :     default:
     697                 :          0 :         zlib_error(state, self->zst, err, "while creating decompression object");
     698                 :          0 :         Py_DECREF(self);
     699                 :          0 :         return NULL;
     700                 :            :     }
     701                 :            : }
     702                 :            : 
     703                 :            : static void
     704                 :          0 : Dealloc(compobject *self)
     705                 :            : {
     706                 :          0 :     PyObject *type = (PyObject *)Py_TYPE(self);
     707                 :          0 :     PyThread_free_lock(self->lock);
     708                 :          0 :     Py_XDECREF(self->unused_data);
     709                 :          0 :     Py_XDECREF(self->unconsumed_tail);
     710                 :          0 :     Py_XDECREF(self->zdict);
     711                 :          0 :     PyObject_Free(self);
     712                 :          0 :     Py_DECREF(type);
     713                 :          0 : }
     714                 :            : 
     715                 :            : static void
     716                 :          0 : Comp_dealloc(compobject *self)
     717                 :            : {
     718         [ #  # ]:          0 :     if (self->is_initialised)
     719                 :          0 :         deflateEnd(&self->zst);
     720                 :          0 :     Dealloc(self);
     721                 :          0 : }
     722                 :            : 
     723                 :            : static void
     724                 :          0 : Decomp_dealloc(compobject *self)
     725                 :            : {
     726         [ #  # ]:          0 :     if (self->is_initialised)
     727                 :          0 :         inflateEnd(&self->zst);
     728                 :          0 :     Dealloc(self);
     729                 :          0 : }
     730                 :            : 
     731                 :            : /*[clinic input]
     732                 :            : zlib.Compress.compress
     733                 :            : 
     734                 :            :     cls: defining_class
     735                 :            :     data: Py_buffer
     736                 :            :         Binary data to be compressed.
     737                 :            :     /
     738                 :            : 
     739                 :            : Returns a bytes object containing compressed data.
     740                 :            : 
     741                 :            : After calling this function, some of the input data may still
     742                 :            : be stored in internal buffers for later processing.
     743                 :            : Call the flush() method to clear these buffers.
     744                 :            : [clinic start generated code]*/
     745                 :            : 
     746                 :            : static PyObject *
     747                 :          0 : zlib_Compress_compress_impl(compobject *self, PyTypeObject *cls,
     748                 :            :                             Py_buffer *data)
     749                 :            : /*[clinic end generated code: output=6731b3f0ff357ca6 input=04d00f65ab01d260]*/
     750                 :            : {
     751                 :            :     PyObject *return_value;
     752                 :            :     int err;
     753                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
     754                 :          0 :     zlibstate *state = PyType_GetModuleState(cls);
     755                 :            : 
     756         [ #  # ]:          0 :     ENTER_ZLIB(self);
     757                 :            : 
     758                 :          0 :     self->zst.next_in = data->buf;
     759                 :          0 :     Py_ssize_t ibuflen = data->len;
     760                 :            : 
     761         [ #  # ]:          0 :     if (OutputBuffer_InitAndGrow(&buffer, -1, &self->zst.next_out, &self->zst.avail_out) < 0) {
     762                 :          0 :         goto error;
     763                 :            :     }
     764                 :            : 
     765                 :            :     do {
     766                 :          0 :         arrange_input_buffer(&self->zst, &ibuflen);
     767                 :            : 
     768                 :            :         do {
     769         [ #  # ]:          0 :             if (self->zst.avail_out == 0) {
     770         [ #  # ]:          0 :                 if (OutputBuffer_Grow(&buffer, &self->zst.next_out, &self->zst.avail_out) < 0) {
     771                 :          0 :                     goto error;
     772                 :            :                 }
     773                 :            :             }
     774                 :            : 
     775                 :          0 :             Py_BEGIN_ALLOW_THREADS
     776                 :          0 :             err = deflate(&self->zst, Z_NO_FLUSH);
     777                 :          0 :             Py_END_ALLOW_THREADS
     778                 :            : 
     779         [ #  # ]:          0 :             if (err == Z_STREAM_ERROR) {
     780                 :          0 :                 zlib_error(state, self->zst, err, "while compressing data");
     781                 :          0 :                 goto error;
     782                 :            :             }
     783                 :            : 
     784         [ #  # ]:          0 :         } while (self->zst.avail_out == 0);
     785                 :            :         assert(self->zst.avail_in == 0);
     786                 :            : 
     787         [ #  # ]:          0 :     } while (ibuflen != 0);
     788                 :            : 
     789                 :          0 :     return_value = OutputBuffer_Finish(&buffer, self->zst.avail_out);
     790         [ #  # ]:          0 :     if (return_value != NULL) {
     791                 :          0 :         goto success;
     792                 :            :     }
     793                 :            : 
     794                 :          0 :  error:
     795                 :          0 :     OutputBuffer_OnError(&buffer);
     796                 :          0 :     return_value = NULL;
     797                 :          0 :  success:
     798                 :          0 :     LEAVE_ZLIB(self);
     799                 :          0 :     return return_value;
     800                 :            : }
     801                 :            : 
     802                 :            : /* Helper for objdecompress() and flush(). Saves any unconsumed input data in
     803                 :            :    self->unused_data or self->unconsumed_tail, as appropriate. */
     804                 :            : static int
     805                 :          0 : save_unconsumed_input(compobject *self, Py_buffer *data, int err)
     806                 :            : {
     807         [ #  # ]:          0 :     if (err == Z_STREAM_END) {
     808                 :            :         /* The end of the compressed data has been reached. Store the leftover
     809                 :            :            input data in self->unused_data. */
     810         [ #  # ]:          0 :         if (self->zst.avail_in > 0) {
     811                 :          0 :             Py_ssize_t old_size = PyBytes_GET_SIZE(self->unused_data);
     812                 :            :             Py_ssize_t new_size, left_size;
     813                 :            :             PyObject *new_data;
     814                 :          0 :             left_size = (Byte *)data->buf + data->len - self->zst.next_in;
     815         [ #  # ]:          0 :             if (left_size > (PY_SSIZE_T_MAX - old_size)) {
     816                 :          0 :                 PyErr_NoMemory();
     817                 :          0 :                 return -1;
     818                 :            :             }
     819                 :          0 :             new_size = old_size + left_size;
     820                 :          0 :             new_data = PyBytes_FromStringAndSize(NULL, new_size);
     821         [ #  # ]:          0 :             if (new_data == NULL)
     822                 :          0 :                 return -1;
     823                 :          0 :             memcpy(PyBytes_AS_STRING(new_data),
     824                 :          0 :                       PyBytes_AS_STRING(self->unused_data), old_size);
     825                 :          0 :             memcpy(PyBytes_AS_STRING(new_data) + old_size,
     826                 :          0 :                       self->zst.next_in, left_size);
     827                 :          0 :             Py_SETREF(self->unused_data, new_data);
     828                 :          0 :             self->zst.avail_in = 0;
     829                 :            :         }
     830                 :            :     }
     831                 :            : 
     832   [ #  #  #  # ]:          0 :     if (self->zst.avail_in > 0 || PyBytes_GET_SIZE(self->unconsumed_tail)) {
     833                 :            :         /* This code handles two distinct cases:
     834                 :            :            1. Output limit was reached. Save leftover input in unconsumed_tail.
     835                 :            :            2. All input data was consumed. Clear unconsumed_tail. */
     836                 :          0 :         Py_ssize_t left_size = (Byte *)data->buf + data->len - self->zst.next_in;
     837                 :          0 :         PyObject *new_data = PyBytes_FromStringAndSize(
     838                 :          0 :                 (char *)self->zst.next_in, left_size);
     839         [ #  # ]:          0 :         if (new_data == NULL)
     840                 :          0 :             return -1;
     841                 :          0 :         Py_SETREF(self->unconsumed_tail, new_data);
     842                 :            :     }
     843                 :            : 
     844                 :          0 :     return 0;
     845                 :            : }
     846                 :            : 
     847                 :            : /*[clinic input]
     848                 :            : zlib.Decompress.decompress
     849                 :            : 
     850                 :            :     cls: defining_class
     851                 :            :     data: Py_buffer
     852                 :            :         The binary data to decompress.
     853                 :            :     /
     854                 :            :     max_length: Py_ssize_t = 0
     855                 :            :         The maximum allowable length of the decompressed data.
     856                 :            :         Unconsumed input data will be stored in
     857                 :            :         the unconsumed_tail attribute.
     858                 :            : 
     859                 :            : Return a bytes object containing the decompressed version of the data.
     860                 :            : 
     861                 :            : After calling this function, some of the input data may still be stored in
     862                 :            : internal buffers for later processing.
     863                 :            : Call the flush() method to clear these buffers.
     864                 :            : [clinic start generated code]*/
     865                 :            : 
     866                 :            : static PyObject *
     867                 :          0 : zlib_Decompress_decompress_impl(compobject *self, PyTypeObject *cls,
     868                 :            :                                 Py_buffer *data, Py_ssize_t max_length)
     869                 :            : /*[clinic end generated code: output=b024a93c2c922d57 input=bfb37b3864cfb606]*/
     870                 :            : {
     871                 :          0 :     int err = Z_OK;
     872                 :            :     Py_ssize_t ibuflen;
     873                 :            :     PyObject *return_value;
     874                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
     875                 :            : 
     876                 :          0 :     PyObject *module = PyType_GetModule(cls);
     877         [ #  # ]:          0 :     if (module == NULL)
     878                 :          0 :         return NULL;
     879                 :            : 
     880                 :          0 :     zlibstate *state = get_zlib_state(module);
     881         [ #  # ]:          0 :     if (max_length < 0) {
     882                 :          0 :         PyErr_SetString(PyExc_ValueError, "max_length must be non-negative");
     883                 :          0 :         return NULL;
     884         [ #  # ]:          0 :     } else if (max_length == 0) {
     885                 :          0 :         max_length = -1;
     886                 :            :     }
     887                 :            : 
     888         [ #  # ]:          0 :     ENTER_ZLIB(self);
     889                 :            : 
     890                 :          0 :     self->zst.next_in = data->buf;
     891                 :          0 :     ibuflen = data->len;
     892                 :            : 
     893         [ #  # ]:          0 :     if (OutputBuffer_InitAndGrow(&buffer, max_length, &self->zst.next_out, &self->zst.avail_out) < 0) {
     894                 :          0 :         goto abort;
     895                 :            :     }
     896                 :            : 
     897                 :            :     do {
     898                 :          0 :         arrange_input_buffer(&self->zst, &ibuflen);
     899                 :            : 
     900                 :            :         do {
     901         [ #  # ]:          0 :             if (self->zst.avail_out == 0) {
     902         [ #  # ]:          0 :                 if (OutputBuffer_GetDataSize(&buffer, self->zst.avail_out) == max_length) {
     903                 :          0 :                     goto save;
     904                 :            :                 }
     905         [ #  # ]:          0 :                 if (OutputBuffer_Grow(&buffer, &self->zst.next_out, &self->zst.avail_out) < 0) {
     906                 :          0 :                     goto abort;
     907                 :            :                 }
     908                 :            :             }
     909                 :            : 
     910                 :          0 :             Py_BEGIN_ALLOW_THREADS
     911                 :          0 :             err = inflate(&self->zst, Z_SYNC_FLUSH);
     912                 :          0 :             Py_END_ALLOW_THREADS
     913                 :            : 
     914         [ #  # ]:          0 :             switch (err) {
     915                 :          0 :             case Z_OK:            /* fall through */
     916                 :            :             case Z_BUF_ERROR:     /* fall through */
     917                 :            :             case Z_STREAM_END:
     918                 :          0 :                 break;
     919                 :          0 :             default:
     920   [ #  #  #  # ]:          0 :                 if (err == Z_NEED_DICT && self->zdict != NULL) {
     921         [ #  # ]:          0 :                     if (set_inflate_zdict(state, self) < 0) {
     922                 :          0 :                         goto abort;
     923                 :            :                     }
     924                 :            :                     else
     925                 :          0 :                         break;
     926                 :            :                 }
     927                 :          0 :                 goto save;
     928                 :            :             }
     929                 :            : 
     930   [ #  #  #  # ]:          0 :         } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);
     931                 :            : 
     932   [ #  #  #  # ]:          0 :     } while (err != Z_STREAM_END && ibuflen != 0);
     933                 :            : 
     934                 :          0 :  save:
     935         [ #  # ]:          0 :     if (save_unconsumed_input(self, data, err) < 0)
     936                 :          0 :         goto abort;
     937                 :            : 
     938         [ #  # ]:          0 :     if (err == Z_STREAM_END) {
     939                 :            :         /* This is the logical place to call inflateEnd, but the old behaviour
     940                 :            :            of only calling it on flush() is preserved. */
     941                 :          0 :         self->eof = 1;
     942   [ #  #  #  # ]:          0 :     } else if (err != Z_OK && err != Z_BUF_ERROR) {
     943                 :            :         /* We will only get Z_BUF_ERROR if the output buffer was full
     944                 :            :            but there wasn't more output when we tried again, so it is
     945                 :            :            not an error condition.
     946                 :            :         */
     947                 :          0 :         zlib_error(state, self->zst, err, "while decompressing data");
     948                 :          0 :         goto abort;
     949                 :            :     }
     950                 :            : 
     951                 :          0 :     return_value = OutputBuffer_Finish(&buffer, self->zst.avail_out);
     952         [ #  # ]:          0 :     if (return_value != NULL) {
     953                 :          0 :         goto success;
     954                 :            :     }
     955                 :            : 
     956                 :          0 :  abort:
     957                 :          0 :     OutputBuffer_OnError(&buffer);
     958                 :          0 :     return_value = NULL;
     959                 :          0 :  success:
     960                 :          0 :     LEAVE_ZLIB(self);
     961                 :          0 :     return return_value;
     962                 :            : }
     963                 :            : 
     964                 :            : /*[clinic input]
     965                 :            : zlib.Compress.flush
     966                 :            : 
     967                 :            :     cls: defining_class
     968                 :            :     mode: int(c_default="Z_FINISH") = zlib.Z_FINISH
     969                 :            :         One of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH.
     970                 :            :         If mode == Z_FINISH, the compressor object can no longer be
     971                 :            :         used after calling the flush() method.  Otherwise, more data
     972                 :            :         can still be compressed.
     973                 :            :     /
     974                 :            : 
     975                 :            : Return a bytes object containing any remaining compressed data.
     976                 :            : [clinic start generated code]*/
     977                 :            : 
     978                 :            : static PyObject *
     979                 :          0 : zlib_Compress_flush_impl(compobject *self, PyTypeObject *cls, int mode)
     980                 :            : /*[clinic end generated code: output=c7efd13efd62add2 input=286146e29442eb6c]*/
     981                 :            : {
     982                 :            :     int err;
     983                 :            :     PyObject *return_value;
     984                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
     985                 :            : 
     986                 :          0 :     zlibstate *state = PyType_GetModuleState(cls);
     987                 :            :     /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
     988                 :            :        doing any work at all; just return an empty string. */
     989         [ #  # ]:          0 :     if (mode == Z_NO_FLUSH) {
     990                 :          0 :         return PyBytes_FromStringAndSize(NULL, 0);
     991                 :            :     }
     992                 :            : 
     993         [ #  # ]:          0 :     ENTER_ZLIB(self);
     994                 :            : 
     995                 :          0 :     self->zst.avail_in = 0;
     996                 :            : 
     997         [ #  # ]:          0 :     if (OutputBuffer_InitAndGrow(&buffer, -1, &self->zst.next_out, &self->zst.avail_out) < 0) {
     998                 :          0 :         goto error;
     999                 :            :     }
    1000                 :            : 
    1001                 :            :     do {
    1002         [ #  # ]:          0 :         if (self->zst.avail_out == 0) {
    1003         [ #  # ]:          0 :             if (OutputBuffer_Grow(&buffer, &self->zst.next_out, &self->zst.avail_out) < 0) {
    1004                 :          0 :                 goto error;
    1005                 :            :             }
    1006                 :            :         }
    1007                 :            : 
    1008                 :          0 :         Py_BEGIN_ALLOW_THREADS
    1009                 :          0 :         err = deflate(&self->zst, mode);
    1010                 :          0 :         Py_END_ALLOW_THREADS
    1011                 :            : 
    1012         [ #  # ]:          0 :         if (err == Z_STREAM_ERROR) {
    1013                 :          0 :             zlib_error(state, self->zst, err, "while flushing");
    1014                 :          0 :             goto error;
    1015                 :            :         }
    1016         [ #  # ]:          0 :     } while (self->zst.avail_out == 0);
    1017                 :            :     assert(self->zst.avail_in == 0);
    1018                 :            : 
    1019                 :            :     /* If mode is Z_FINISH, we also have to call deflateEnd() to free
    1020                 :            :        various data structures. Note we should only get Z_STREAM_END when
    1021                 :            :        mode is Z_FINISH, but checking both for safety*/
    1022   [ #  #  #  # ]:          0 :     if (err == Z_STREAM_END && mode == Z_FINISH) {
    1023                 :          0 :         err = deflateEnd(&self->zst);
    1024         [ #  # ]:          0 :         if (err != Z_OK) {
    1025                 :          0 :             zlib_error(state, self->zst, err, "while finishing compression");
    1026                 :          0 :             goto error;
    1027                 :            :         }
    1028                 :            :         else
    1029                 :          0 :             self->is_initialised = 0;
    1030                 :            : 
    1031                 :            :         /* We will only get Z_BUF_ERROR if the output buffer was full
    1032                 :            :            but there wasn't more output when we tried again, so it is
    1033                 :            :            not an error condition.
    1034                 :            :         */
    1035   [ #  #  #  # ]:          0 :     } else if (err != Z_OK && err != Z_BUF_ERROR) {
    1036                 :          0 :         zlib_error(state, self->zst, err, "while flushing");
    1037                 :          0 :         goto error;
    1038                 :            :     }
    1039                 :            : 
    1040                 :          0 :     return_value = OutputBuffer_Finish(&buffer, self->zst.avail_out);
    1041         [ #  # ]:          0 :     if (return_value != NULL) {
    1042                 :          0 :         goto success;
    1043                 :            :     }
    1044                 :            : 
    1045                 :          0 : error:
    1046                 :          0 :     OutputBuffer_OnError(&buffer);
    1047                 :          0 :     return_value = NULL;
    1048                 :          0 : success:
    1049                 :          0 :     LEAVE_ZLIB(self);
    1050                 :          0 :     return return_value;
    1051                 :            : }
    1052                 :            : 
    1053                 :            : #ifdef HAVE_ZLIB_COPY
    1054                 :            : 
    1055                 :            : /*[clinic input]
    1056                 :            : zlib.Compress.copy
    1057                 :            : 
    1058                 :            :     cls: defining_class
    1059                 :            : 
    1060                 :            : Return a copy of the compression object.
    1061                 :            : [clinic start generated code]*/
    1062                 :            : 
    1063                 :            : static PyObject *
    1064                 :          0 : zlib_Compress_copy_impl(compobject *self, PyTypeObject *cls)
    1065                 :            : /*[clinic end generated code: output=c4d2cfb4b0d7350b input=235497e482d40986]*/
    1066                 :            : {
    1067                 :          0 :     zlibstate *state = PyType_GetModuleState(cls);
    1068                 :            : 
    1069                 :          0 :     compobject *return_value = newcompobject(state->Comptype);
    1070         [ #  # ]:          0 :     if (!return_value) return NULL;
    1071                 :            : 
    1072                 :            :     /* Copy the zstream state
    1073                 :            :      * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe
    1074                 :            :      */
    1075         [ #  # ]:          0 :     ENTER_ZLIB(self);
    1076                 :          0 :     int err = deflateCopy(&return_value->zst, &self->zst);
    1077   [ #  #  #  # ]:          0 :     switch (err) {
    1078                 :          0 :     case Z_OK:
    1079                 :          0 :         break;
    1080                 :          0 :     case Z_STREAM_ERROR:
    1081                 :          0 :         PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
    1082                 :          0 :         goto error;
    1083                 :          0 :     case Z_MEM_ERROR:
    1084                 :          0 :         PyErr_SetString(PyExc_MemoryError,
    1085                 :            :                         "Can't allocate memory for compression object");
    1086                 :          0 :         goto error;
    1087                 :          0 :     default:
    1088                 :          0 :         zlib_error(state, self->zst, err, "while copying compression object");
    1089                 :          0 :         goto error;
    1090                 :            :     }
    1091                 :          0 :     Py_XSETREF(return_value->unused_data, Py_NewRef(self->unused_data));
    1092                 :          0 :     Py_XSETREF(return_value->unconsumed_tail, Py_NewRef(self->unconsumed_tail));
    1093                 :          0 :     Py_XSETREF(return_value->zdict, Py_XNewRef(self->zdict));
    1094                 :          0 :     return_value->eof = self->eof;
    1095                 :            : 
    1096                 :            :     /* Mark it as being initialized */
    1097                 :          0 :     return_value->is_initialised = 1;
    1098                 :            : 
    1099                 :          0 :     LEAVE_ZLIB(self);
    1100                 :          0 :     return (PyObject *)return_value;
    1101                 :            : 
    1102                 :          0 : error:
    1103                 :          0 :     LEAVE_ZLIB(self);
    1104                 :          0 :     Py_XDECREF(return_value);
    1105                 :          0 :     return NULL;
    1106                 :            : }
    1107                 :            : 
    1108                 :            : /*[clinic input]
    1109                 :            : zlib.Compress.__copy__
    1110                 :            : 
    1111                 :            :     cls: defining_class
    1112                 :            : 
    1113                 :            : [clinic start generated code]*/
    1114                 :            : 
    1115                 :            : static PyObject *
    1116                 :          0 : zlib_Compress___copy___impl(compobject *self, PyTypeObject *cls)
    1117                 :            : /*[clinic end generated code: output=074613db332cb668 input=5c0188367ab0fe64]*/
    1118                 :            : {
    1119                 :          0 :     return zlib_Compress_copy_impl(self, cls);
    1120                 :            : }
    1121                 :            : 
    1122                 :            : /*[clinic input]
    1123                 :            : zlib.Compress.__deepcopy__
    1124                 :            : 
    1125                 :            :     cls: defining_class
    1126                 :            :     memo: object
    1127                 :            :     /
    1128                 :            : 
    1129                 :            : [clinic start generated code]*/
    1130                 :            : 
    1131                 :            : static PyObject *
    1132                 :          0 : zlib_Compress___deepcopy___impl(compobject *self, PyTypeObject *cls,
    1133                 :            :                                 PyObject *memo)
    1134                 :            : /*[clinic end generated code: output=24b3aed785f54033 input=c90347319a514430]*/
    1135                 :            : {
    1136                 :          0 :     return zlib_Compress_copy_impl(self, cls);
    1137                 :            : }
    1138                 :            : 
    1139                 :            : /*[clinic input]
    1140                 :            : zlib.Decompress.copy
    1141                 :            : 
    1142                 :            :     cls: defining_class
    1143                 :            : 
    1144                 :            : Return a copy of the decompression object.
    1145                 :            : [clinic start generated code]*/
    1146                 :            : 
    1147                 :            : static PyObject *
    1148                 :          0 : zlib_Decompress_copy_impl(compobject *self, PyTypeObject *cls)
    1149                 :            : /*[clinic end generated code: output=a7ddc016e1d0a781 input=20ef3aa208282ff2]*/
    1150                 :            : {
    1151                 :          0 :     zlibstate *state = PyType_GetModuleState(cls);
    1152                 :            : 
    1153                 :          0 :     compobject *return_value = newcompobject(state->Decomptype);
    1154         [ #  # ]:          0 :     if (!return_value) return NULL;
    1155                 :            : 
    1156                 :            :     /* Copy the zstream state
    1157                 :            :      * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe
    1158                 :            :      */
    1159         [ #  # ]:          0 :     ENTER_ZLIB(self);
    1160                 :          0 :     int err = inflateCopy(&return_value->zst, &self->zst);
    1161   [ #  #  #  # ]:          0 :     switch (err) {
    1162                 :          0 :     case Z_OK:
    1163                 :          0 :         break;
    1164                 :          0 :     case Z_STREAM_ERROR:
    1165                 :          0 :         PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
    1166                 :          0 :         goto error;
    1167                 :          0 :     case Z_MEM_ERROR:
    1168                 :          0 :         PyErr_SetString(PyExc_MemoryError,
    1169                 :            :                         "Can't allocate memory for decompression object");
    1170                 :          0 :         goto error;
    1171                 :          0 :     default:
    1172                 :          0 :         zlib_error(state, self->zst, err, "while copying decompression object");
    1173                 :          0 :         goto error;
    1174                 :            :     }
    1175                 :            : 
    1176                 :          0 :     Py_XSETREF(return_value->unused_data, Py_NewRef(self->unused_data));
    1177                 :          0 :     Py_XSETREF(return_value->unconsumed_tail, Py_NewRef(self->unconsumed_tail));
    1178                 :          0 :     Py_XSETREF(return_value->zdict, Py_XNewRef(self->zdict));
    1179                 :          0 :     return_value->eof = self->eof;
    1180                 :            : 
    1181                 :            :     /* Mark it as being initialized */
    1182                 :          0 :     return_value->is_initialised = 1;
    1183                 :            : 
    1184                 :          0 :     LEAVE_ZLIB(self);
    1185                 :          0 :     return (PyObject *)return_value;
    1186                 :            : 
    1187                 :          0 : error:
    1188                 :          0 :     LEAVE_ZLIB(self);
    1189                 :          0 :     Py_XDECREF(return_value);
    1190                 :          0 :     return NULL;
    1191                 :            : }
    1192                 :            : 
    1193                 :            : /*[clinic input]
    1194                 :            : zlib.Decompress.__copy__
    1195                 :            : 
    1196                 :            :     cls: defining_class
    1197                 :            : 
    1198                 :            : [clinic start generated code]*/
    1199                 :            : 
    1200                 :            : static PyObject *
    1201                 :          0 : zlib_Decompress___copy___impl(compobject *self, PyTypeObject *cls)
    1202                 :            : /*[clinic end generated code: output=cf1e6473744f53fa input=cc3143067b622bdf]*/
    1203                 :            : {
    1204                 :          0 :     return zlib_Decompress_copy_impl(self, cls);
    1205                 :            : }
    1206                 :            : 
    1207                 :            : /*[clinic input]
    1208                 :            : zlib.Decompress.__deepcopy__
    1209                 :            : 
    1210                 :            :     cls: defining_class
    1211                 :            :     memo: object
    1212                 :            :     /
    1213                 :            : 
    1214                 :            : [clinic start generated code]*/
    1215                 :            : 
    1216                 :            : static PyObject *
    1217                 :          0 : zlib_Decompress___deepcopy___impl(compobject *self, PyTypeObject *cls,
    1218                 :            :                                   PyObject *memo)
    1219                 :            : /*[clinic end generated code: output=34f7b719a0c0d51b input=fc13b9c58622544e]*/
    1220                 :            : {
    1221                 :          0 :     return zlib_Decompress_copy_impl(self, cls);
    1222                 :            : }
    1223                 :            : 
    1224                 :            : #endif
    1225                 :            : 
    1226                 :            : /*[clinic input]
    1227                 :            : zlib.Decompress.flush
    1228                 :            : 
    1229                 :            :     cls: defining_class
    1230                 :            :     length: Py_ssize_t(c_default="DEF_BUF_SIZE") = zlib.DEF_BUF_SIZE
    1231                 :            :         the initial size of the output buffer.
    1232                 :            :     /
    1233                 :            : 
    1234                 :            : Return a bytes object containing any remaining decompressed data.
    1235                 :            : [clinic start generated code]*/
    1236                 :            : 
    1237                 :            : static PyObject *
    1238                 :          0 : zlib_Decompress_flush_impl(compobject *self, PyTypeObject *cls,
    1239                 :            :                            Py_ssize_t length)
    1240                 :            : /*[clinic end generated code: output=4532fc280bd0f8f2 input=42f1f4b75230e2cd]*/
    1241                 :            : {
    1242                 :            :     int err, flush;
    1243                 :            :     Py_buffer data;
    1244                 :            :     PyObject *return_value;
    1245                 :            :     Py_ssize_t ibuflen;
    1246                 :          0 :     _BlocksOutputBuffer buffer = {.list = NULL};
    1247                 :            :     _Uint32Window window;  // output buffer's UINT32_MAX sliding window
    1248                 :            : 
    1249                 :          0 :     PyObject *module = PyType_GetModule(cls);
    1250         [ #  # ]:          0 :     if (module == NULL) {
    1251                 :          0 :         return NULL;
    1252                 :            :     }
    1253                 :            : 
    1254                 :          0 :     zlibstate *state = get_zlib_state(module);
    1255                 :            : 
    1256         [ #  # ]:          0 :     if (length <= 0) {
    1257                 :          0 :         PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
    1258                 :          0 :         return NULL;
    1259                 :            :     }
    1260                 :            : 
    1261         [ #  # ]:          0 :     ENTER_ZLIB(self);
    1262                 :            : 
    1263         [ #  # ]:          0 :     if (PyObject_GetBuffer(self->unconsumed_tail, &data, PyBUF_SIMPLE) == -1) {
    1264                 :          0 :         LEAVE_ZLIB(self);
    1265                 :          0 :         return NULL;
    1266                 :            :     }
    1267                 :            : 
    1268                 :          0 :     self->zst.next_in = data.buf;
    1269                 :          0 :     ibuflen = data.len;
    1270                 :            : 
    1271         [ #  # ]:          0 :     if (OutputBuffer_WindowInitWithSize(&buffer, &window, length,
    1272                 :          0 :                                         &self->zst.next_out, &self->zst.avail_out) < 0) {
    1273                 :          0 :         goto abort;
    1274                 :            :     }
    1275                 :            : 
    1276                 :            :     do {
    1277                 :          0 :         arrange_input_buffer(&self->zst, &ibuflen);
    1278         [ #  # ]:          0 :         flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
    1279                 :            : 
    1280                 :            :         do {
    1281         [ #  # ]:          0 :             if (self->zst.avail_out == 0) {
    1282         [ #  # ]:          0 :                 if (OutputBuffer_WindowGrow(&buffer, &window,
    1283                 :          0 :                                             &self->zst.next_out, &self->zst.avail_out) < 0) {
    1284                 :          0 :                     goto abort;
    1285                 :            :                 }
    1286                 :            :             }
    1287                 :            : 
    1288                 :          0 :             Py_BEGIN_ALLOW_THREADS
    1289                 :          0 :             err = inflate(&self->zst, flush);
    1290                 :          0 :             Py_END_ALLOW_THREADS
    1291                 :            : 
    1292         [ #  # ]:          0 :             switch (err) {
    1293                 :          0 :             case Z_OK:            /* fall through */
    1294                 :            :             case Z_BUF_ERROR:     /* fall through */
    1295                 :            :             case Z_STREAM_END:
    1296                 :          0 :                 break;
    1297                 :          0 :             default:
    1298                 :          0 :                 goto save;
    1299                 :            :             }
    1300                 :            : 
    1301   [ #  #  #  # ]:          0 :         } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);
    1302                 :            : 
    1303   [ #  #  #  # ]:          0 :     } while (err != Z_STREAM_END && ibuflen != 0);
    1304                 :            : 
    1305                 :          0 :  save:
    1306         [ #  # ]:          0 :     if (save_unconsumed_input(self, &data, err) < 0) {
    1307                 :          0 :         goto abort;
    1308                 :            :     }
    1309                 :            : 
    1310                 :            :     /* If at end of stream, clean up any memory allocated by zlib. */
    1311         [ #  # ]:          0 :     if (err == Z_STREAM_END) {
    1312                 :          0 :         self->eof = 1;
    1313                 :          0 :         self->is_initialised = 0;
    1314                 :          0 :         err = inflateEnd(&self->zst);
    1315         [ #  # ]:          0 :         if (err != Z_OK) {
    1316                 :          0 :             zlib_error(state, self->zst, err, "while finishing decompression");
    1317                 :          0 :             goto abort;
    1318                 :            :         }
    1319                 :            :     }
    1320                 :            : 
    1321                 :          0 :     return_value = OutputBuffer_WindowFinish(&buffer, &window, self->zst.avail_out);
    1322         [ #  # ]:          0 :     if (return_value != NULL) {
    1323                 :          0 :         goto success;
    1324                 :            :     }
    1325                 :            : 
    1326                 :          0 :  abort:
    1327                 :          0 :     OutputBuffer_WindowOnError(&buffer, &window);
    1328                 :          0 :     return_value = NULL;
    1329                 :          0 :  success:
    1330                 :          0 :     PyBuffer_Release(&data);
    1331                 :          0 :     LEAVE_ZLIB(self);
    1332                 :          0 :     return return_value;
    1333                 :            : }
    1334                 :            : 
    1335                 :            : 
    1336                 :            : typedef struct {
    1337                 :            :     PyObject_HEAD
    1338                 :            :     z_stream zst;
    1339                 :            :     PyObject *zdict;
    1340                 :            :     PyThread_type_lock lock;
    1341                 :            :     PyObject *unused_data;
    1342                 :            :     uint8_t *input_buffer;
    1343                 :            :     Py_ssize_t input_buffer_size;
    1344                 :            :     /* zst>avail_in is only 32 bit, so we store the true length
    1345                 :            :        separately. Conversion and looping is encapsulated in
    1346                 :            :        decompress_buf() */
    1347                 :            :     Py_ssize_t avail_in_real;
    1348                 :            :     bool is_initialised;
    1349                 :            :     char eof;           /* T_BOOL expects a char */
    1350                 :            :     char needs_input;
    1351                 :            : } ZlibDecompressor;
    1352                 :            : 
    1353                 :            : /*[clinic input]
    1354                 :            : class zlib.ZlibDecompressor "ZlibDecompressor *" "&ZlibDecompressorType"
    1355                 :            : [clinic start generated code]*/
    1356                 :            : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=0658178ab94645df]*/
    1357                 :            : 
    1358                 :            : static void
    1359                 :          0 : ZlibDecompressor_dealloc(ZlibDecompressor *self)
    1360                 :            : {
    1361                 :          0 :     PyObject *type = (PyObject *)Py_TYPE(self);
    1362                 :          0 :     PyThread_free_lock(self->lock);
    1363         [ #  # ]:          0 :     if (self->is_initialised) {
    1364                 :          0 :         inflateEnd(&self->zst);
    1365                 :            :     }
    1366                 :          0 :     PyMem_Free(self->input_buffer);
    1367         [ #  # ]:          0 :     Py_CLEAR(self->unused_data);
    1368         [ #  # ]:          0 :     Py_CLEAR(self->zdict);
    1369                 :          0 :     PyObject_Free(self);
    1370                 :          0 :     Py_DECREF(type);
    1371                 :          0 : }
    1372                 :            : 
    1373                 :            : static int
    1374                 :          0 : set_inflate_zdict_ZlibDecompressor(zlibstate *state, ZlibDecompressor *self)
    1375                 :            : {
    1376                 :            :     Py_buffer zdict_buf;
    1377         [ #  # ]:          0 :     if (PyObject_GetBuffer(self->zdict, &zdict_buf, PyBUF_SIMPLE) == -1) {
    1378                 :          0 :         return -1;
    1379                 :            :     }
    1380         [ #  # ]:          0 :     if ((size_t)zdict_buf.len > UINT_MAX) {
    1381                 :          0 :         PyErr_SetString(PyExc_OverflowError,
    1382                 :            :                         "zdict length does not fit in an unsigned int");
    1383                 :          0 :         PyBuffer_Release(&zdict_buf);
    1384                 :          0 :         return -1;
    1385                 :            :     }
    1386                 :            :     int err;
    1387                 :          0 :     err = inflateSetDictionary(&self->zst,
    1388                 :          0 :                                zdict_buf.buf, (unsigned int)zdict_buf.len);
    1389                 :          0 :     PyBuffer_Release(&zdict_buf);
    1390         [ #  # ]:          0 :     if (err != Z_OK) {
    1391                 :          0 :         zlib_error(state, self->zst, err, "while setting zdict");
    1392                 :          0 :         return -1;
    1393                 :            :     }
    1394                 :          0 :     return 0;
    1395                 :            : }
    1396                 :            : 
    1397                 :            : static Py_ssize_t
    1398                 :          0 : arrange_output_buffer_with_maximum(uint32_t *avail_out,
    1399                 :            :                                    uint8_t **next_out,
    1400                 :            :                                    PyObject **buffer,
    1401                 :            :                                    Py_ssize_t length,
    1402                 :            :                                    Py_ssize_t max_length)
    1403                 :            : {
    1404                 :            :     Py_ssize_t occupied;
    1405                 :            : 
    1406         [ #  # ]:          0 :     if (*buffer == NULL) {
    1407         [ #  # ]:          0 :         if (!(*buffer = PyBytes_FromStringAndSize(NULL, length)))
    1408                 :          0 :             return -1;
    1409                 :          0 :         occupied = 0;
    1410                 :            :     }
    1411                 :            :     else {
    1412                 :          0 :         occupied = *next_out - (uint8_t *)PyBytes_AS_STRING(*buffer);
    1413                 :            : 
    1414         [ #  # ]:          0 :         if (length == occupied) {
    1415                 :            :             Py_ssize_t new_length;
    1416                 :            :             assert(length <= max_length);
    1417                 :            :             /* can not scale the buffer over max_length */
    1418         [ #  # ]:          0 :             if (length == max_length)
    1419                 :          0 :                 return -2;
    1420         [ #  # ]:          0 :             if (length <= (max_length >> 1))
    1421                 :          0 :                 new_length = length << 1;
    1422                 :            :             else
    1423                 :          0 :                 new_length = max_length;
    1424         [ #  # ]:          0 :             if (_PyBytes_Resize(buffer, new_length) < 0)
    1425                 :          0 :                 return -1;
    1426                 :          0 :             length = new_length;
    1427                 :            :         }
    1428                 :            :     }
    1429                 :            : 
    1430         [ #  # ]:          0 :     *avail_out = (uint32_t)Py_MIN((size_t)(length - occupied), UINT32_MAX);
    1431                 :          0 :     *next_out = (uint8_t *)PyBytes_AS_STRING(*buffer) + occupied;
    1432                 :            : 
    1433                 :          0 :     return length;
    1434                 :            : }
    1435                 :            : 
    1436                 :            : /* Decompress data of length self->avail_in_real in self->state.next_in. The
    1437                 :            :    output buffer is allocated dynamically and returned. If the max_length is
    1438                 :            :    of sufficiently low size, max_length is allocated immediately. At most
    1439                 :            :    max_length bytes are returned, so some of the input may not be consumed.
    1440                 :            :    self->state.next_in and self->avail_in_real are updated to reflect the
    1441                 :            :    consumed input. */
    1442                 :            : static PyObject*
    1443                 :          0 : decompress_buf(ZlibDecompressor *self, Py_ssize_t max_length)
    1444                 :            : {
    1445                 :            :     /* data_size is strictly positive, but because we repeatedly have to
    1446                 :            :        compare against max_length and PyBytes_GET_SIZE we declare it as
    1447                 :            :        signed */
    1448                 :          0 :     PyObject *return_value = NULL;
    1449                 :            :     Py_ssize_t hard_limit;
    1450                 :            :     Py_ssize_t obuflen;
    1451                 :          0 :     zlibstate *state = PyType_GetModuleState(Py_TYPE(self));
    1452                 :            : 
    1453                 :          0 :     int err = Z_OK;
    1454                 :            : 
    1455                 :            :     /* When sys.maxsize is passed as default use DEF_BUF_SIZE as start buffer.
    1456                 :            :        In this particular case the data may not necessarily be very big, so
    1457                 :            :        it is better to grow dynamically.*/
    1458   [ #  #  #  # ]:          0 :     if ((max_length < 0) || max_length == PY_SSIZE_T_MAX) {
    1459                 :          0 :         hard_limit = PY_SSIZE_T_MAX;
    1460                 :          0 :         obuflen = DEF_BUF_SIZE;
    1461                 :            :     } else {
    1462                 :            :         /* Assume that decompressor is used in file decompression with a fixed
    1463                 :            :            block size of max_length. In that case we will reach max_length almost
    1464                 :            :            always (except at the end of the file). So it makes sense to allocate
    1465                 :            :            max_length. */
    1466                 :          0 :         hard_limit = max_length;
    1467                 :          0 :         obuflen = max_length;
    1468         [ #  # ]:          0 :         if (obuflen > DEF_MAX_INITIAL_BUF_SIZE){
    1469                 :            :             // Safeguard against memory overflow.
    1470                 :          0 :             obuflen = DEF_MAX_INITIAL_BUF_SIZE;
    1471                 :            :         }
    1472                 :            :     }
    1473                 :            : 
    1474                 :            :     do {
    1475                 :          0 :         arrange_input_buffer(&(self->zst), &(self->avail_in_real));
    1476                 :            : 
    1477                 :            :         do {
    1478                 :          0 :             obuflen = arrange_output_buffer_with_maximum(&(self->zst.avail_out),
    1479                 :          0 :                                                         &(self->zst.next_out),
    1480                 :            :                                                         &return_value,
    1481                 :            :                                                         obuflen,
    1482                 :            :                                                         hard_limit);
    1483         [ #  # ]:          0 :             if (obuflen == -1){
    1484                 :          0 :                 PyErr_SetString(PyExc_MemoryError,
    1485                 :            :                                 "Insufficient memory for buffer allocation");
    1486                 :          0 :                 goto error;
    1487                 :            :             }
    1488         [ #  # ]:          0 :             else if (obuflen == -2) {
    1489                 :          0 :                 break;
    1490                 :            :             }
    1491                 :          0 :             Py_BEGIN_ALLOW_THREADS
    1492                 :          0 :             err = inflate(&self->zst, Z_SYNC_FLUSH);
    1493                 :          0 :             Py_END_ALLOW_THREADS
    1494         [ #  # ]:          0 :             switch (err) {
    1495                 :          0 :             case Z_OK:            /* fall through */
    1496                 :            :             case Z_BUF_ERROR:     /* fall through */
    1497                 :            :             case Z_STREAM_END:
    1498                 :          0 :                 break;
    1499                 :          0 :             default:
    1500         [ #  # ]:          0 :                 if (err == Z_NEED_DICT) {
    1501                 :          0 :                     goto error;
    1502                 :            :                 }
    1503                 :            :                 else {
    1504                 :          0 :                     break;
    1505                 :            :                 }
    1506                 :            :             }
    1507         [ #  # ]:          0 :         } while (self->zst.avail_out == 0);
    1508   [ #  #  #  # ]:          0 :     } while(err != Z_STREAM_END && self->avail_in_real != 0);
    1509                 :            : 
    1510         [ #  # ]:          0 :     if (err == Z_STREAM_END) {
    1511                 :          0 :         self->eof = 1;
    1512                 :          0 :         self->is_initialised = 0;
    1513                 :            :         /* Unlike the Decompress object we call inflateEnd here as there are no
    1514                 :            :            backwards compatibility issues */
    1515                 :          0 :         err = inflateEnd(&self->zst);
    1516         [ #  # ]:          0 :         if (err != Z_OK) {
    1517                 :          0 :             zlib_error(state, self->zst, err, "while finishing decompression");
    1518                 :          0 :             goto error;
    1519                 :            :         }
    1520   [ #  #  #  # ]:          0 :     } else if (err != Z_OK && err != Z_BUF_ERROR) {
    1521                 :          0 :         zlib_error(state, self->zst, err, "while decompressing data");
    1522                 :          0 :         goto error;
    1523                 :            :     }
    1524                 :            : 
    1525                 :          0 :     self->avail_in_real += self->zst.avail_in;
    1526                 :            : 
    1527         [ #  # ]:          0 :     if (_PyBytes_Resize(&return_value, self->zst.next_out -
    1528                 :          0 :                         (uint8_t *)PyBytes_AS_STRING(return_value)) != 0) {
    1529                 :          0 :         goto error;
    1530                 :            :     }
    1531                 :            : 
    1532                 :          0 :     goto success;
    1533                 :          0 : error:
    1534         [ #  # ]:          0 :     Py_CLEAR(return_value);
    1535                 :          0 : success:
    1536                 :          0 :     return return_value;
    1537                 :            : }
    1538                 :            : 
    1539                 :            : 
    1540                 :            : static PyObject *
    1541                 :          0 : decompress(ZlibDecompressor *self, uint8_t *data,
    1542                 :            :            size_t len, Py_ssize_t max_length)
    1543                 :            : {
    1544                 :            :     bool input_buffer_in_use;
    1545                 :            :     PyObject *result;
    1546                 :            : 
    1547                 :            :     /* Prepend unconsumed input if necessary */
    1548         [ #  # ]:          0 :     if (self->zst.next_in != NULL) {
    1549                 :            :         size_t avail_now, avail_total;
    1550                 :            : 
    1551                 :            :         /* Number of bytes we can append to input buffer */
    1552                 :          0 :         avail_now = (self->input_buffer + self->input_buffer_size)
    1553                 :          0 :             - (self->zst.next_in + self->avail_in_real);
    1554                 :            : 
    1555                 :            :         /* Number of bytes we can append if we move existing
    1556                 :            :            contents to beginning of buffer (overwriting
    1557                 :            :            consumed input) */
    1558                 :          0 :         avail_total = self->input_buffer_size - self->avail_in_real;
    1559                 :            : 
    1560         [ #  # ]:          0 :         if (avail_total < len) {
    1561                 :          0 :             size_t offset = self->zst.next_in - self->input_buffer;
    1562                 :            :             uint8_t *tmp;
    1563                 :          0 :             size_t new_size = self->input_buffer_size + len - avail_now;
    1564                 :            : 
    1565                 :            :             /* Assign to temporary variable first, so we don't
    1566                 :            :                lose address of allocated buffer if realloc fails */
    1567                 :          0 :             tmp = PyMem_Realloc(self->input_buffer, new_size);
    1568         [ #  # ]:          0 :             if (tmp == NULL) {
    1569                 :          0 :                 PyErr_SetNone(PyExc_MemoryError);
    1570                 :          0 :                 return NULL;
    1571                 :            :             }
    1572                 :          0 :             self->input_buffer = tmp;
    1573                 :          0 :             self->input_buffer_size = new_size;
    1574                 :            : 
    1575                 :          0 :             self->zst.next_in = self->input_buffer + offset;
    1576                 :            :         }
    1577         [ #  # ]:          0 :         else if (avail_now < len) {
    1578                 :          0 :             memmove(self->input_buffer, self->zst.next_in,
    1579                 :          0 :                     self->avail_in_real);
    1580                 :          0 :             self->zst.next_in = self->input_buffer;
    1581                 :            :         }
    1582                 :          0 :         memcpy((void*)(self->zst.next_in + self->avail_in_real), data, len);
    1583                 :          0 :         self->avail_in_real += len;
    1584                 :          0 :         input_buffer_in_use = 1;
    1585                 :            :     }
    1586                 :            :     else {
    1587                 :          0 :         self->zst.next_in = data;
    1588                 :          0 :         self->avail_in_real = len;
    1589                 :          0 :         input_buffer_in_use = 0;
    1590                 :            :     }
    1591                 :            : 
    1592                 :          0 :     result = decompress_buf(self, max_length);
    1593         [ #  # ]:          0 :     if(result == NULL) {
    1594                 :          0 :         self->zst.next_in = NULL;
    1595                 :          0 :         return NULL;
    1596                 :            :     }
    1597                 :            : 
    1598         [ #  # ]:          0 :     if (self->eof) {
    1599                 :          0 :         self->needs_input = 0;
    1600                 :            : 
    1601         [ #  # ]:          0 :         if (self->avail_in_real > 0) {
    1602                 :          0 :             PyObject *unused_data = PyBytes_FromStringAndSize(
    1603                 :          0 :                 (char *)self->zst.next_in, self->avail_in_real);
    1604         [ #  # ]:          0 :             if (unused_data == NULL) {
    1605                 :          0 :                 goto error;
    1606                 :            :             }
    1607                 :          0 :             Py_XSETREF(self->unused_data, unused_data);
    1608                 :            :         }
    1609                 :            :     }
    1610         [ #  # ]:          0 :     else if (self->avail_in_real == 0) {
    1611                 :          0 :         self->zst.next_in = NULL;
    1612                 :          0 :         self->needs_input = 1;
    1613                 :            :     }
    1614                 :            :     else {
    1615                 :          0 :         self->needs_input = 0;
    1616                 :            : 
    1617                 :            :         /* If we did not use the input buffer, we now have
    1618                 :            :            to copy the tail from the caller's buffer into the
    1619                 :            :            input buffer */
    1620         [ #  # ]:          0 :         if (!input_buffer_in_use) {
    1621                 :            : 
    1622                 :            :             /* Discard buffer if it's too small
    1623                 :            :                (resizing it may needlessly copy the current contents) */
    1624         [ #  # ]:          0 :             if (self->input_buffer != NULL &&
    1625         [ #  # ]:          0 :                 self->input_buffer_size < self->avail_in_real) {
    1626                 :          0 :                 PyMem_Free(self->input_buffer);
    1627                 :          0 :                 self->input_buffer = NULL;
    1628                 :            :             }
    1629                 :            : 
    1630                 :            :             /* Allocate if necessary */
    1631         [ #  # ]:          0 :             if (self->input_buffer == NULL) {
    1632                 :          0 :                 self->input_buffer = PyMem_Malloc(self->avail_in_real);
    1633         [ #  # ]:          0 :                 if (self->input_buffer == NULL) {
    1634                 :          0 :                     PyErr_SetNone(PyExc_MemoryError);
    1635                 :          0 :                     goto error;
    1636                 :            :                 }
    1637                 :          0 :                 self->input_buffer_size = self->avail_in_real;
    1638                 :            :             }
    1639                 :            : 
    1640                 :            :             /* Copy tail */
    1641                 :          0 :             memcpy(self->input_buffer, self->zst.next_in, self->avail_in_real);
    1642                 :          0 :             self->zst.next_in = self->input_buffer;
    1643                 :            :         }
    1644                 :            :     }
    1645                 :          0 :     return result;
    1646                 :            : 
    1647                 :          0 : error:
    1648                 :          0 :     Py_XDECREF(result);
    1649                 :          0 :     return NULL;
    1650                 :            : }
    1651                 :            : 
    1652                 :            : /*[clinic input]
    1653                 :            : zlib.ZlibDecompressor.decompress
    1654                 :            : 
    1655                 :            :     data: Py_buffer
    1656                 :            :     max_length: Py_ssize_t=-1
    1657                 :            : 
    1658                 :            : Decompress *data*, returning uncompressed data as bytes.
    1659                 :            : 
    1660                 :            : If *max_length* is nonnegative, returns at most *max_length* bytes of
    1661                 :            : decompressed data. If this limit is reached and further output can be
    1662                 :            : produced, *self.needs_input* will be set to ``False``. In this case, the next
    1663                 :            : call to *decompress()* may provide *data* as b'' to obtain more of the output.
    1664                 :            : 
    1665                 :            : If all of the input data was decompressed and returned (either because this
    1666                 :            : was less than *max_length* bytes, or because *max_length* was negative),
    1667                 :            : *self.needs_input* will be set to True.
    1668                 :            : 
    1669                 :            : Attempting to decompress data after the end of stream is reached raises an
    1670                 :            : EOFError.  Any data found after the end of the stream is ignored and saved in
    1671                 :            : the unused_data attribute.
    1672                 :            : [clinic start generated code]*/
    1673                 :            : 
    1674                 :            : static PyObject *
    1675                 :          0 : zlib_ZlibDecompressor_decompress_impl(ZlibDecompressor *self,
    1676                 :            :                                       Py_buffer *data, Py_ssize_t max_length)
    1677                 :            : /*[clinic end generated code: output=990d32787b775f85 input=0b29d99715250b96]*/
    1678                 :            : 
    1679                 :            : {
    1680                 :          0 :     PyObject *result = NULL;
    1681                 :            : 
    1682         [ #  # ]:          0 :     ENTER_ZLIB(self);
    1683         [ #  # ]:          0 :     if (self->eof) {
    1684                 :          0 :         PyErr_SetString(PyExc_EOFError, "End of stream already reached");
    1685                 :            :     }
    1686                 :            :     else {
    1687                 :          0 :         result = decompress(self, data->buf, data->len, max_length);
    1688                 :            :     }
    1689                 :          0 :     LEAVE_ZLIB(self);
    1690                 :          0 :     return result;
    1691                 :            : }
    1692                 :            : 
    1693                 :            : PyDoc_STRVAR(ZlibDecompressor__new____doc__,
    1694                 :            : "_ZlibDecompressor(wbits=15, zdict=b\'\')\n"
    1695                 :            : "--\n"
    1696                 :            : "\n"
    1697                 :            : "Create a decompressor object for decompressing data incrementally.\n"
    1698                 :            : "\n"
    1699                 :            : "  wbits = 15\n"
    1700                 :            : "  zdict\n"
    1701                 :            : "     The predefined compression dictionary. This is a sequence of bytes\n"
    1702                 :            : "     (such as a bytes object) containing subsequences that are expected\n"
    1703                 :            : "     to occur frequently in the data that is to be compressed. Those\n"
    1704                 :            : "     subsequences that are expected to be most common should come at the\n"
    1705                 :            : "     end of the dictionary. This must be the same dictionary as used by the\n"
    1706                 :            : "     compressor that produced the input data.\n"
    1707                 :            : "\n");
    1708                 :            : 
    1709                 :            : static PyObject *
    1710                 :          0 : ZlibDecompressor__new__(PyTypeObject *cls,
    1711                 :            :                         PyObject *args,
    1712                 :            :                         PyObject *kwargs)
    1713                 :            : {
    1714                 :            :     static char *keywords[] = {"wbits", "zdict", NULL};
    1715                 :            :     static const char * const format = "|iO:_ZlibDecompressor";
    1716                 :          0 :     int wbits = MAX_WBITS;
    1717                 :          0 :     PyObject *zdict = NULL;
    1718                 :          0 :     zlibstate *state = PyType_GetModuleState(cls);
    1719                 :            : 
    1720         [ #  # ]:          0 :     if (!PyArg_ParseTupleAndKeywords(
    1721                 :            :             args, kwargs, format, keywords, &wbits, &zdict)) {
    1722                 :          0 :         return NULL;
    1723                 :            :     }
    1724                 :          0 :     ZlibDecompressor *self = PyObject_New(ZlibDecompressor, cls);
    1725                 :          0 :     self->eof = 0;
    1726                 :          0 :     self->needs_input = 1;
    1727                 :          0 :     self->avail_in_real = 0;
    1728                 :          0 :     self->input_buffer = NULL;
    1729                 :          0 :     self->input_buffer_size = 0;
    1730                 :          0 :     self->zdict = Py_XNewRef(zdict);
    1731                 :          0 :     self->zst.opaque = NULL;
    1732                 :          0 :     self->zst.zalloc = PyZlib_Malloc;
    1733                 :          0 :     self->zst.zfree = PyZlib_Free;
    1734                 :          0 :     self->zst.next_in = NULL;
    1735                 :          0 :     self->zst.avail_in = 0;
    1736                 :          0 :     self->unused_data = PyBytes_FromStringAndSize(NULL, 0);
    1737         [ #  # ]:          0 :     if (self->unused_data == NULL) {
    1738         [ #  # ]:          0 :         Py_CLEAR(self);
    1739                 :          0 :         return NULL;
    1740                 :            :     }
    1741                 :          0 :     self->lock = PyThread_allocate_lock();
    1742         [ #  # ]:          0 :     if (self->lock == NULL) {
    1743                 :          0 :         Py_DECREF(self);
    1744                 :          0 :         PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
    1745                 :          0 :         return NULL;
    1746                 :            :     }
    1747                 :          0 :     int err = inflateInit2(&(self->zst), wbits);
    1748   [ #  #  #  # ]:          0 :     switch (err) {
    1749                 :          0 :         case Z_OK:
    1750                 :          0 :         self->is_initialised = 1;
    1751   [ #  #  #  # ]:          0 :         if (self->zdict != NULL && wbits < 0) {
    1752         [ #  # ]:          0 :             if (set_inflate_zdict_ZlibDecompressor(state, self) < 0) {
    1753                 :          0 :                 Py_DECREF(self);
    1754                 :          0 :                 return NULL;
    1755                 :            :             }
    1756                 :            :         }
    1757                 :          0 :         return (PyObject *)self;
    1758                 :          0 :     case Z_STREAM_ERROR:
    1759                 :          0 :         Py_DECREF(self);
    1760                 :          0 :         PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
    1761                 :          0 :         return NULL;
    1762                 :          0 :     case Z_MEM_ERROR:
    1763                 :          0 :         Py_DECREF(self);
    1764                 :          0 :         PyErr_SetString(PyExc_MemoryError,
    1765                 :            :                         "Can't allocate memory for decompression object");
    1766                 :          0 :         return NULL;
    1767                 :          0 :     default:
    1768                 :          0 :         zlib_error(state, self->zst, err, "while creating decompression object");
    1769                 :          0 :         Py_DECREF(self);
    1770                 :          0 :         return NULL;
    1771                 :            :     }
    1772                 :            : }
    1773                 :            : 
    1774                 :            : #include "clinic/zlibmodule.c.h"
    1775                 :            : 
    1776                 :            : static PyMethodDef comp_methods[] =
    1777                 :            : {
    1778                 :            :     ZLIB_COMPRESS_COMPRESS_METHODDEF
    1779                 :            :     ZLIB_COMPRESS_FLUSH_METHODDEF
    1780                 :            :     ZLIB_COMPRESS_COPY_METHODDEF
    1781                 :            :     ZLIB_COMPRESS___COPY___METHODDEF
    1782                 :            :     ZLIB_COMPRESS___DEEPCOPY___METHODDEF
    1783                 :            :     {NULL, NULL}
    1784                 :            : };
    1785                 :            : 
    1786                 :            : static PyMethodDef Decomp_methods[] =
    1787                 :            : {
    1788                 :            :     ZLIB_DECOMPRESS_DECOMPRESS_METHODDEF
    1789                 :            :     ZLIB_DECOMPRESS_FLUSH_METHODDEF
    1790                 :            :     ZLIB_DECOMPRESS_COPY_METHODDEF
    1791                 :            :     ZLIB_DECOMPRESS___COPY___METHODDEF
    1792                 :            :     ZLIB_DECOMPRESS___DEEPCOPY___METHODDEF
    1793                 :            :     {NULL, NULL}
    1794                 :            : };
    1795                 :            : 
    1796                 :            : static PyMethodDef ZlibDecompressor_methods[] = {
    1797                 :            :     ZLIB_ZLIBDECOMPRESSOR_DECOMPRESS_METHODDEF
    1798                 :            :     {NULL}
    1799                 :            : };
    1800                 :            : 
    1801                 :            : #define COMP_OFF(x) offsetof(compobject, x)
    1802                 :            : static PyMemberDef Decomp_members[] = {
    1803                 :            :     {"unused_data",     T_OBJECT, COMP_OFF(unused_data), READONLY},
    1804                 :            :     {"unconsumed_tail", T_OBJECT, COMP_OFF(unconsumed_tail), READONLY},
    1805                 :            :     {"eof",             T_BOOL,   COMP_OFF(eof), READONLY},
    1806                 :            :     {NULL},
    1807                 :            : };
    1808                 :            : 
    1809                 :            : PyDoc_STRVAR(ZlibDecompressor_eof__doc__,
    1810                 :            : "True if the end-of-stream marker has been reached.");
    1811                 :            : 
    1812                 :            : PyDoc_STRVAR(ZlibDecompressor_unused_data__doc__,
    1813                 :            : "Data found after the end of the compressed stream.");
    1814                 :            : 
    1815                 :            : PyDoc_STRVAR(ZlibDecompressor_needs_input_doc,
    1816                 :            : "True if more input is needed before more decompressed data can be produced.");
    1817                 :            : 
    1818                 :            : static PyMemberDef ZlibDecompressor_members[] = {
    1819                 :            :     {"eof", T_BOOL, offsetof(ZlibDecompressor, eof),
    1820                 :            :      READONLY, ZlibDecompressor_eof__doc__},
    1821                 :            :     {"unused_data", T_OBJECT_EX, offsetof(ZlibDecompressor, unused_data),
    1822                 :            :      READONLY, ZlibDecompressor_unused_data__doc__},
    1823                 :            :     {"needs_input", T_BOOL, offsetof(ZlibDecompressor, needs_input), READONLY,
    1824                 :            :      ZlibDecompressor_needs_input_doc},
    1825                 :            :     {NULL},
    1826                 :            : };
    1827                 :            : 
    1828                 :            : 
    1829                 :            : /*[clinic input]
    1830                 :            : zlib.adler32
    1831                 :            : 
    1832                 :            :     data: Py_buffer
    1833                 :            :     value: unsigned_int(bitwise=True) = 1
    1834                 :            :         Starting value of the checksum.
    1835                 :            :     /
    1836                 :            : 
    1837                 :            : Compute an Adler-32 checksum of data.
    1838                 :            : 
    1839                 :            : The returned checksum is an integer.
    1840                 :            : [clinic start generated code]*/
    1841                 :            : 
    1842                 :            : static PyObject *
    1843                 :          0 : zlib_adler32_impl(PyObject *module, Py_buffer *data, unsigned int value)
    1844                 :            : /*[clinic end generated code: output=422106f5ca8c92c0 input=6ff4557872160e88]*/
    1845                 :            : {
    1846                 :            :     /* Releasing the GIL for very small buffers is inefficient
    1847                 :            :        and may lower performance */
    1848         [ #  # ]:          0 :     if (data->len > 1024*5) {
    1849                 :          0 :         unsigned char *buf = data->buf;
    1850                 :          0 :         Py_ssize_t len = data->len;
    1851                 :            : 
    1852                 :          0 :         Py_BEGIN_ALLOW_THREADS
    1853                 :            :         /* Avoid truncation of length for very large buffers. adler32() takes
    1854                 :            :            length as an unsigned int, which may be narrower than Py_ssize_t. */
    1855         [ #  # ]:          0 :         while ((size_t)len > UINT_MAX) {
    1856                 :          0 :             value = adler32(value, buf, UINT_MAX);
    1857                 :          0 :             buf += (size_t) UINT_MAX;
    1858                 :          0 :             len -= (size_t) UINT_MAX;
    1859                 :            :         }
    1860                 :          0 :         value = adler32(value, buf, (unsigned int)len);
    1861                 :          0 :         Py_END_ALLOW_THREADS
    1862                 :            :     } else {
    1863                 :          0 :         value = adler32(value, data->buf, (unsigned int)data->len);
    1864                 :            :     }
    1865                 :          0 :     return PyLong_FromUnsignedLong(value & 0xffffffffU);
    1866                 :            : }
    1867                 :            : 
    1868                 :            : /*[clinic input]
    1869                 :            : zlib.crc32 -> unsigned_int
    1870                 :            : 
    1871                 :            :     data: Py_buffer
    1872                 :            :     value: unsigned_int(bitwise=True) = 0
    1873                 :            :         Starting value of the checksum.
    1874                 :            :     /
    1875                 :            : 
    1876                 :            : Compute a CRC-32 checksum of data.
    1877                 :            : 
    1878                 :            : The returned checksum is an integer.
    1879                 :            : [clinic start generated code]*/
    1880                 :            : 
    1881                 :            : static unsigned int
    1882                 :          0 : zlib_crc32_impl(PyObject *module, Py_buffer *data, unsigned int value)
    1883                 :            : /*[clinic end generated code: output=b217562e4fe6d6a6 input=1229cb2fb5ea948a]*/
    1884                 :            : {
    1885                 :            :     /* Releasing the GIL for very small buffers is inefficient
    1886                 :            :        and may lower performance */
    1887         [ #  # ]:          0 :     if (data->len > 1024*5) {
    1888                 :          0 :         unsigned char *buf = data->buf;
    1889                 :          0 :         Py_ssize_t len = data->len;
    1890                 :            : 
    1891                 :          0 :         Py_BEGIN_ALLOW_THREADS
    1892                 :            :         /* Avoid truncation of length for very large buffers. crc32() takes
    1893                 :            :            length as an unsigned int, which may be narrower than Py_ssize_t. */
    1894         [ #  # ]:          0 :         while ((size_t)len > UINT_MAX) {
    1895                 :          0 :             value = crc32(value, buf, UINT_MAX);
    1896                 :          0 :             buf += (size_t) UINT_MAX;
    1897                 :          0 :             len -= (size_t) UINT_MAX;
    1898                 :            :         }
    1899                 :          0 :         value = crc32(value, buf, (unsigned int)len);
    1900                 :          0 :         Py_END_ALLOW_THREADS
    1901                 :            :     } else {
    1902                 :          0 :         value = crc32(value, data->buf, (unsigned int)data->len);
    1903                 :            :     }
    1904                 :          0 :     return value;
    1905                 :            : }
    1906                 :            : 
    1907                 :            : 
    1908                 :            : static PyMethodDef zlib_methods[] =
    1909                 :            : {
    1910                 :            :     ZLIB_ADLER32_METHODDEF
    1911                 :            :     ZLIB_COMPRESS_METHODDEF
    1912                 :            :     ZLIB_COMPRESSOBJ_METHODDEF
    1913                 :            :     ZLIB_CRC32_METHODDEF
    1914                 :            :     ZLIB_DECOMPRESS_METHODDEF
    1915                 :            :     ZLIB_DECOMPRESSOBJ_METHODDEF
    1916                 :            :     {NULL, NULL}
    1917                 :            : };
    1918                 :            : 
    1919                 :            : static PyType_Slot Comptype_slots[] = {
    1920                 :            :     {Py_tp_dealloc, Comp_dealloc},
    1921                 :            :     {Py_tp_methods, comp_methods},
    1922                 :            :     {0, 0},
    1923                 :            : };
    1924                 :            : 
    1925                 :            : static PyType_Spec Comptype_spec = {
    1926                 :            :     .name = "zlib.Compress",
    1927                 :            :     .basicsize = sizeof(compobject),
    1928                 :            :     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    1929                 :            :     .slots= Comptype_slots,
    1930                 :            : };
    1931                 :            : 
    1932                 :            : static PyType_Slot Decomptype_slots[] = {
    1933                 :            :     {Py_tp_dealloc, Decomp_dealloc},
    1934                 :            :     {Py_tp_methods, Decomp_methods},
    1935                 :            :     {Py_tp_members, Decomp_members},
    1936                 :            :     {0, 0},
    1937                 :            : };
    1938                 :            : 
    1939                 :            : static PyType_Spec Decomptype_spec = {
    1940                 :            :     .name = "zlib.Decompress",
    1941                 :            :     .basicsize = sizeof(compobject),
    1942                 :            :     .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    1943                 :            :     .slots = Decomptype_slots,
    1944                 :            : };
    1945                 :            : 
    1946                 :            : static PyType_Slot ZlibDecompressor_type_slots[] = {
    1947                 :            :     {Py_tp_dealloc, ZlibDecompressor_dealloc},
    1948                 :            :     {Py_tp_members, ZlibDecompressor_members},
    1949                 :            :     {Py_tp_new, ZlibDecompressor__new__},
    1950                 :            :     {Py_tp_doc, (char *)ZlibDecompressor__new____doc__},
    1951                 :            :     {Py_tp_methods, ZlibDecompressor_methods},
    1952                 :            :     {0, 0},
    1953                 :            : };
    1954                 :            : 
    1955                 :            : static PyType_Spec ZlibDecompressor_type_spec = {
    1956                 :            :     .name = "zlib._ZlibDecompressor",
    1957                 :            :     .basicsize = sizeof(ZlibDecompressor),
    1958                 :            :     // Calling PyType_GetModuleState() on a subclass is not safe.
    1959                 :            :     // ZlibDecompressor_type_spec does not have Py_TPFLAGS_BASETYPE flag
    1960                 :            :     // which prevents to create a subclass.
    1961                 :            :     // So calling PyType_GetModuleState() in this file is always safe.
    1962                 :            :     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE),
    1963                 :            :     .slots = ZlibDecompressor_type_slots,
    1964                 :            : };
    1965                 :            : PyDoc_STRVAR(zlib_module_documentation,
    1966                 :            : "The functions in this module allow compression and decompression using the\n"
    1967                 :            : "zlib library, which is based on GNU zip.\n"
    1968                 :            : "\n"
    1969                 :            : "adler32(string[, start]) -- Compute an Adler-32 checksum.\n"
    1970                 :            : "compress(data[, level]) -- Compress data, with compression level 0-9 or -1.\n"
    1971                 :            : "compressobj([level[, ...]]) -- Return a compressor object.\n"
    1972                 :            : "crc32(string[, start]) -- Compute a CRC-32 checksum.\n"
    1973                 :            : "decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string.\n"
    1974                 :            : "decompressobj([wbits[, zdict]]) -- Return a decompressor object.\n"
    1975                 :            : "\n"
    1976                 :            : "'wbits' is window buffer size and container format.\n"
    1977                 :            : "Compressor objects support compress() and flush() methods; decompressor\n"
    1978                 :            : "objects support decompress() and flush().");
    1979                 :            : 
    1980                 :            : static int
    1981                 :          6 : zlib_clear(PyObject *mod)
    1982                 :            : {
    1983                 :          6 :     zlibstate *state = get_zlib_state(mod);
    1984         [ +  + ]:          6 :     Py_CLEAR(state->Comptype);
    1985         [ +  + ]:          6 :     Py_CLEAR(state->Decomptype);
    1986         [ +  + ]:          6 :     Py_CLEAR(state->ZlibDecompressorType);
    1987         [ +  + ]:          6 :     Py_CLEAR(state->ZlibError);
    1988                 :          6 :     return 0;
    1989                 :            : }
    1990                 :            : 
    1991                 :            : static int
    1992                 :         42 : zlib_traverse(PyObject *mod, visitproc visit, void *arg)
    1993                 :            : {
    1994                 :         42 :     zlibstate *state = get_zlib_state(mod);
    1995   [ +  -  -  + ]:         42 :     Py_VISIT(state->Comptype);
    1996   [ +  -  -  + ]:         42 :     Py_VISIT(state->Decomptype);
    1997   [ +  -  -  + ]:         42 :     Py_VISIT(state->ZlibDecompressorType);
    1998   [ +  -  -  + ]:         42 :     Py_VISIT(state->ZlibError);
    1999                 :         42 :     return 0;
    2000                 :            : }
    2001                 :            : 
    2002                 :            : static void
    2003                 :          3 : zlib_free(void *mod)
    2004                 :            : {
    2005                 :          3 :     zlib_clear((PyObject *)mod);
    2006                 :          3 : }
    2007                 :            : 
    2008                 :            : static int
    2009                 :          3 : zlib_exec(PyObject *mod)
    2010                 :            : {
    2011                 :          3 :     zlibstate *state = get_zlib_state(mod);
    2012                 :            : 
    2013                 :          3 :     state->Comptype = (PyTypeObject *)PyType_FromModuleAndSpec(
    2014                 :            :         mod, &Comptype_spec, NULL);
    2015         [ -  + ]:          3 :     if (state->Comptype == NULL) {
    2016                 :          0 :         return -1;
    2017                 :            :     }
    2018                 :            : 
    2019                 :          3 :     state->Decomptype = (PyTypeObject *)PyType_FromModuleAndSpec(
    2020                 :            :         mod, &Decomptype_spec, NULL);
    2021         [ -  + ]:          3 :     if (state->Decomptype == NULL) {
    2022                 :          0 :         return -1;
    2023                 :            :     }
    2024                 :            : 
    2025                 :          3 :     state->ZlibDecompressorType = (PyTypeObject *)PyType_FromModuleAndSpec(
    2026                 :            :         mod, &ZlibDecompressor_type_spec, NULL);
    2027         [ -  + ]:          3 :     if (state->ZlibDecompressorType == NULL) {
    2028                 :          0 :         return -1;
    2029                 :            :     }
    2030                 :            : 
    2031                 :          3 :     state->ZlibError = PyErr_NewException("zlib.error", NULL, NULL);
    2032         [ -  + ]:          3 :     if (state->ZlibError == NULL) {
    2033                 :          0 :         return -1;
    2034                 :            :     }
    2035                 :            : 
    2036         [ -  + ]:          3 :     if (PyModule_AddObject(mod, "error", Py_NewRef(state->ZlibError)) < 0) {
    2037                 :          0 :         Py_DECREF(state->ZlibError);
    2038                 :          0 :         return -1;
    2039                 :            :     }
    2040         [ -  + ]:          3 :     if (PyModule_AddObject(mod, "_ZlibDecompressor",
    2041                 :          3 :                            Py_NewRef(state->ZlibDecompressorType)) < 0) {
    2042                 :          0 :         Py_DECREF(state->ZlibDecompressorType);
    2043                 :          0 :         return -1;
    2044                 :            :     }
    2045                 :            : 
    2046                 :            : #define ZLIB_ADD_INT_MACRO(c)                           \
    2047                 :            :     do {                                                \
    2048                 :            :         if ((PyModule_AddIntConstant(mod, #c, c)) < 0) {  \
    2049                 :            :             return -1;                                  \
    2050                 :            :         }                                               \
    2051                 :            :     } while(0)
    2052                 :            : 
    2053         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(MAX_WBITS);
    2054         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(DEFLATED);
    2055         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(DEF_MEM_LEVEL);
    2056         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(DEF_BUF_SIZE);
    2057                 :            :     // compression levels
    2058         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_NO_COMPRESSION);
    2059         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_BEST_SPEED);
    2060         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_BEST_COMPRESSION);
    2061         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_DEFAULT_COMPRESSION);
    2062                 :            :     // compression strategies
    2063         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_FILTERED);
    2064         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_HUFFMAN_ONLY);
    2065                 :            : #ifdef Z_RLE // 1.2.0.1
    2066         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_RLE);
    2067                 :            : #endif
    2068                 :            : #ifdef Z_FIXED // 1.2.2.2
    2069         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_FIXED);
    2070                 :            : #endif
    2071         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_DEFAULT_STRATEGY);
    2072                 :            :     // allowed flush values
    2073         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_NO_FLUSH);
    2074         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_PARTIAL_FLUSH);
    2075         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_SYNC_FLUSH);
    2076         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_FULL_FLUSH);
    2077         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_FINISH);
    2078                 :            : #ifdef Z_BLOCK // 1.2.0.5 for inflate, 1.2.3.4 for deflate
    2079         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_BLOCK);
    2080                 :            : #endif
    2081                 :            : #ifdef Z_TREES // 1.2.3.4, only for inflate
    2082         [ -  + ]:          3 :     ZLIB_ADD_INT_MACRO(Z_TREES);
    2083                 :            : #endif
    2084                 :          3 :     PyObject *ver = PyUnicode_FromString(ZLIB_VERSION);
    2085         [ -  + ]:          3 :     if (ver == NULL) {
    2086                 :          0 :         return -1;
    2087                 :            :     }
    2088                 :            : 
    2089         [ -  + ]:          3 :     if (PyModule_AddObject(mod, "ZLIB_VERSION", ver) < 0) {
    2090                 :          0 :         Py_DECREF(ver);
    2091                 :          0 :         return -1;
    2092                 :            :     }
    2093                 :            : 
    2094                 :          3 :     ver = PyUnicode_FromString(zlibVersion());
    2095         [ -  + ]:          3 :     if (ver == NULL) {
    2096                 :          0 :         return -1;
    2097                 :            :     }
    2098                 :            : 
    2099         [ -  + ]:          3 :     if (PyModule_AddObject(mod, "ZLIB_RUNTIME_VERSION", ver) < 0) {
    2100                 :          0 :         Py_DECREF(ver);
    2101                 :          0 :         return -1;
    2102                 :            :     }
    2103                 :            : 
    2104         [ -  + ]:          3 :     if (PyModule_AddStringConstant(mod, "__version__", "1.0") < 0) {
    2105                 :          0 :         return -1;
    2106                 :            :     }
    2107                 :          3 :     return 0;
    2108                 :            : }
    2109                 :            : 
    2110                 :            : static PyModuleDef_Slot zlib_slots[] = {
    2111                 :            :     {Py_mod_exec, zlib_exec},
    2112                 :            :     {0, NULL}
    2113                 :            : };
    2114                 :            : 
    2115                 :            : static struct PyModuleDef zlibmodule = {
    2116                 :            :     PyModuleDef_HEAD_INIT,
    2117                 :            :     .m_name = "zlib",
    2118                 :            :     .m_doc = zlib_module_documentation,
    2119                 :            :     .m_size = sizeof(zlibstate),
    2120                 :            :     .m_methods = zlib_methods,
    2121                 :            :     .m_slots = zlib_slots,
    2122                 :            :     .m_traverse = zlib_traverse,
    2123                 :            :     .m_clear = zlib_clear,
    2124                 :            :     .m_free = zlib_free,
    2125                 :            : };
    2126                 :            : 
    2127                 :            : PyMODINIT_FUNC
    2128                 :          3 : PyInit_zlib(void)
    2129                 :            : {
    2130                 :          3 :     return PyModuleDef_Init(&zlibmodule);
    2131                 :            : }

Generated by: LCOV version 1.14