zlibmodule.c 39.9 KB
Newer Older
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"
10
#include "zlib.h"
11

12

13
#ifdef WITH_THREAD
14 15 16 17 18 19
    #include "pythread.h"
    #define ENTER_ZLIB(obj) \
        Py_BEGIN_ALLOW_THREADS; \
        PyThread_acquire_lock((obj)->lock, 1); \
        Py_END_ALLOW_THREADS;
    #define LEAVE_ZLIB(obj) PyThread_release_lock((obj)->lock);
20
#else
21 22
    #define ENTER_ZLIB(obj)
    #define LEAVE_ZLIB(obj)
23 24
#endif

25
#if defined(ZLIB_VERNUM) && ZLIB_VERNUM >= 0x1221
26
#  define AT_LEAST_ZLIB_1_2_2_1
27 28
#endif

29 30 31 32 33 34 35 36
/* The following parameters are copied from zutil.h, version 0.95 */
#define DEFLATED   8
#if MAX_MEM_LEVEL >= 8
#  define DEF_MEM_LEVEL 8
#else
#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
#endif

37 38
/* Initial buffer size. */
#define DEF_BUF_SIZE (16*1024)
39

40 41
static PyTypeObject Comptype;
static PyTypeObject Decomptype;
42 43 44

static PyObject *ZlibError;

45
typedef struct
46
{
Jeremy Hylton's avatar
Jeremy Hylton committed
47 48 49 50
    PyObject_HEAD
    z_stream zst;
    PyObject *unused_data;
    PyObject *unconsumed_tail;
51
    char eof;
Jeremy Hylton's avatar
Jeremy Hylton committed
52
    int is_initialised;
53
    PyObject *zdict;
54 55 56
    #ifdef WITH_THREAD
        PyThread_type_lock lock;
    #endif
57 58
} compobject;

Jeremy Hylton's avatar
Jeremy Hylton committed
59
static void
60
zlib_error(z_stream zst, int err, const char *msg)
Jeremy Hylton's avatar
Jeremy Hylton committed
61
{
62 63 64 65 66 67 68
    const char *zmsg = Z_NULL;
    /* In case of a version mismatch, zst.msg won't be initialized.
       Check for this case first, before looking at zst.msg. */
    if (err == Z_VERSION_ERROR)
        zmsg = "library version mismatch";
    if (zmsg == Z_NULL)
        zmsg = zst.msg;
69 70 71 72 73 74 75 76 77 78 79 80 81 82
    if (zmsg == Z_NULL) {
        switch (err) {
        case Z_BUF_ERROR:
            zmsg = "incomplete or truncated stream";
            break;
        case Z_STREAM_ERROR:
            zmsg = "inconsistent stream state";
            break;
        case Z_DATA_ERROR:
            zmsg = "invalid input data";
            break;
        }
    }
    if (zmsg == Z_NULL)
83
        PyErr_Format(ZlibError, "Error %d %s", err, msg);
Jeremy Hylton's avatar
Jeremy Hylton committed
84
    else
85
        PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zmsg);
Jeremy Hylton's avatar
Jeremy Hylton committed
86 87
}

88
/*[clinic input]
89
module zlib
90 91
class zlib.Compress "compobject *" "&Comptype"
class zlib.Decompress "compobject *" "&Decomptype"
92
[clinic start generated code]*/
93
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=093935115c3e3158]*/
94

95
static compobject *
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
96
newcompobject(PyTypeObject *type)
97
{
98
    compobject *self;
Jeremy Hylton's avatar
Jeremy Hylton committed
99 100
    self = PyObject_New(compobject, type);
    if (self == NULL)
101
        return NULL;
102
    self->eof = 0;
Jeremy Hylton's avatar
Jeremy Hylton committed
103
    self->is_initialised = 0;
104
    self->zdict = NULL;
105
    self->unused_data = PyBytes_FromStringAndSize("", 0);
Jeremy Hylton's avatar
Jeremy Hylton committed
106
    if (self->unused_data == NULL) {
107 108
        Py_DECREF(self);
        return NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
109
    }
110
    self->unconsumed_tail = PyBytes_FromStringAndSize("", 0);
Jeremy Hylton's avatar
Jeremy Hylton committed
111
    if (self->unconsumed_tail == NULL) {
112 113
        Py_DECREF(self);
        return NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
114
    }
115 116
#ifdef WITH_THREAD
    self->lock = PyThread_allocate_lock();
117
    if (self->lock == NULL) {
118
        Py_DECREF(self);
119 120 121
        PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
        return NULL;
    }
122
#endif
Jeremy Hylton's avatar
Jeremy Hylton committed
123
    return self;
124 125
}

126 127 128 129 130 131 132 133 134 135 136 137 138
static void*
PyZlib_Malloc(voidpf ctx, uInt items, uInt size)
{
    if (items > (size_t)PY_SSIZE_T_MAX / size)
        return NULL;
    /* PyMem_Malloc() cannot be used: the GIL is not held when
       inflate() and deflate() are called */
    return PyMem_RawMalloc(items * size);
}

static void
PyZlib_Free(voidpf ctx, void *ptr)
{
139
    PyMem_RawFree(ptr);
140 141
}

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
static void
arrange_input_buffer(z_stream *zst, Py_ssize_t *remains)
{
    zst->avail_in = Py_MIN((size_t)*remains, UINT_MAX);
    *remains -= zst->avail_in;
}

static Py_ssize_t
arrange_output_buffer_with_maximum(z_stream *zst, PyObject **buffer,
                                   Py_ssize_t length,
                                   Py_ssize_t max_length)
{
    Py_ssize_t occupied;

    if (*buffer == NULL) {
        if (!(*buffer = PyBytes_FromStringAndSize(NULL, length)))
            return -1;
        occupied = 0;
    }
    else {
        occupied = zst->next_out - (Byte *)PyBytes_AS_STRING(*buffer);

        if (length == occupied) {
            Py_ssize_t new_length;
            assert(length <= max_length);
            /* can not scale the buffer over max_length */
            if (length == max_length)
                return -2;
            if (length <= (max_length >> 1))
                new_length = length << 1;
            else
                new_length = max_length;
            if (_PyBytes_Resize(buffer, new_length) < 0)
                return -1;
            length = new_length;
        }
    }

    zst->avail_out = Py_MIN((size_t)(length - occupied), UINT_MAX);
    zst->next_out = (Byte *)PyBytes_AS_STRING(*buffer) + occupied;

    return length;
}

static Py_ssize_t
arrange_output_buffer(z_stream *zst, PyObject **buffer, Py_ssize_t length)
{
    Py_ssize_t ret;

    ret = arrange_output_buffer_with_maximum(zst, buffer, length,
                                             PY_SSIZE_T_MAX);
    if (ret == -2)
        PyErr_NoMemory();

    return ret;
}

199
/*[clinic input]
200
zlib.compress
201

202
    data: Py_buffer
203
        Binary data to be compressed.
204
    /
205
    level: int(c_default="Z_DEFAULT_COMPRESSION") = Z_DEFAULT_COMPRESSION
206
        Compression level, in 0-9 or -1.
207

208
Returns a bytes object containing compressed data.
209
[clinic start generated code]*/
210 211

static PyObject *
212 213
zlib_compress_impl(PyObject *module, Py_buffer *data, int level)
/*[clinic end generated code: output=d80906d73f6294c8 input=638d54b6315dbed3]*/
214
{
215 216 217 218
    PyObject *RetVal = NULL;
    Byte *ibuf;
    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE;
    int err, flush;
Jeremy Hylton's avatar
Jeremy Hylton committed
219
    z_stream zst;
220

221 222
    ibuf = data->buf;
    ibuflen = data->len;
223

224 225 226
    zst.opaque = NULL;
    zst.zalloc = PyZlib_Malloc;
    zst.zfree = PyZlib_Free;
227
    zst.next_in = ibuf;
228
    err = deflateInit(&zst, level);
229

230 231
    switch (err) {
    case Z_OK:
232
        break;
233
    case Z_MEM_ERROR:
234 235 236
        PyErr_SetString(PyExc_MemoryError,
                        "Out of memory while compressing data");
        goto error;
237 238
    case Z_STREAM_ERROR:
        PyErr_SetString(ZlibError, "Bad compression level");
239
        goto error;
Jeremy Hylton's avatar
Jeremy Hylton committed
240
    default:
241
        deflateEnd(&zst);
242 243
        zlib_error(zst, err, "while compressing data");
        goto error;
244
    }
245

246 247 248
    do {
        arrange_input_buffer(&zst, &ibuflen);
        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
249

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        do {
            obuflen = arrange_output_buffer(&zst, &RetVal, obuflen);
            if (obuflen < 0) {
                deflateEnd(&zst);
                goto error;
            }

            Py_BEGIN_ALLOW_THREADS
            err = deflate(&zst, flush);
            Py_END_ALLOW_THREADS

            if (err == Z_STREAM_ERROR) {
                deflateEnd(&zst);
                zlib_error(zst, err, "while compressing data");
                goto error;
            }
266

267 268 269 270 271 272 273 274 275 276 277 278 279
        } while (zst.avail_out == 0);
        assert(zst.avail_in == 0);

    } while (flush != Z_FINISH);
    assert(err == Z_STREAM_END);

    err = deflateEnd(&zst);
    if (err == Z_OK) {
        if (_PyBytes_Resize(&RetVal, zst.next_out -
                            (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
            goto error;
        return RetVal;
    }
280
    else
281
        zlib_error(zst, err, "while finishing compression");
282
 error:
283 284
    Py_XDECREF(RetVal);
    return NULL;
285 286
}

287
/*[python input]
288

289 290 291
class ssize_t_converter(CConverter):
    type = 'Py_ssize_t'
    converter = 'ssize_t_converter'
292
    c_ignored_default = "0"
293

294
[python start generated code]*/
295
/*[python end generated code: output=da39a3ee5e6b4b0d input=5f34ba1b394cb8e7]*/
296 297

static int
298
ssize_t_converter(PyObject *obj, void *ptr)
299
{
300 301
    PyObject *long_obj;
    Py_ssize_t val;
302

303 304 305
    long_obj = (PyObject *)_PyLong_FromNbInt(obj);
    if (long_obj == NULL) {
        return 0;
306
    }
307 308 309 310
    val = PyLong_AsSsize_t(long_obj);
    Py_DECREF(long_obj);
    if (val == -1 && PyErr_Occurred()) {
        return 0;
311
    }
312
    *(Py_ssize_t *)ptr = val;
313 314 315
    return 1;
}

316 317 318 319 320
/*[clinic input]
zlib.decompress

    data: Py_buffer
        Compressed data.
321
    /
322
    wbits: int(c_default="MAX_WBITS") = MAX_WBITS
323
        The window buffer size and container format.
324
    bufsize: ssize_t(c_default="DEF_BUF_SIZE") = DEF_BUF_SIZE
325 326 327 328
        The initial output buffer size.

Returns a bytes object containing the uncompressed data.
[clinic start generated code]*/
Guido van Rossum's avatar
Guido van Rossum committed
329

330
static PyObject *
331
zlib_decompress_impl(PyObject *module, Py_buffer *data, int wbits,
332
                     Py_ssize_t bufsize)
333
/*[clinic end generated code: output=77c7e35111dc8c42 input=21960936208e9a5b]*/
334
{
335 336 337 338
    PyObject *RetVal = NULL;
    Byte *ibuf;
    Py_ssize_t ibuflen;
    int err, flush;
Jeremy Hylton's avatar
Jeremy Hylton committed
339 340
    z_stream zst;

341 342 343 344
    if (bufsize < 0) {
        PyErr_SetString(PyExc_ValueError, "bufsize must be non-negative");
        return NULL;
    } else if (bufsize == 0) {
345
        bufsize = 1;
346
    }
347

348 349
    ibuf = data->buf;
    ibuflen = data->len;
350

351 352 353
    zst.opaque = NULL;
    zst.zalloc = PyZlib_Malloc;
    zst.zfree = PyZlib_Free;
354 355
    zst.avail_in = 0;
    zst.next_in = ibuf;
356
    err = inflateInit2(&zst, wbits);
Jeremy Hylton's avatar
Jeremy Hylton committed
357

358 359
    switch (err) {
    case Z_OK:
360
        break;
361
    case Z_MEM_ERROR:
362 363 364
        PyErr_SetString(PyExc_MemoryError,
                        "Out of memory while decompressing data");
        goto error;
Jeremy Hylton's avatar
Jeremy Hylton committed
365
    default:
366
        inflateEnd(&zst);
367 368
        zlib_error(zst, err, "while preparing to decompress data");
        goto error;
369
    }
370

Jeremy Hylton's avatar
Jeremy Hylton committed
371
    do {
372 373
        arrange_input_buffer(&zst, &ibuflen);
        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
374

375 376 377
        do {
            bufsize = arrange_output_buffer(&zst, &RetVal, bufsize);
            if (bufsize < 0) {
378 379 380
                inflateEnd(&zst);
                goto error;
            }
381 382 383 384 385 386 387 388 389 390 391

            Py_BEGIN_ALLOW_THREADS
            err = inflate(&zst, flush);
            Py_END_ALLOW_THREADS

            switch (err) {
            case Z_OK:            /* fall through */
            case Z_BUF_ERROR:     /* fall through */
            case Z_STREAM_END:
                break;
            case Z_MEM_ERROR:
392
                inflateEnd(&zst);
393 394 395 396 397 398
                PyErr_SetString(PyExc_MemoryError,
                                "Out of memory while decompressing data");
                goto error;
            default:
                inflateEnd(&zst);
                zlib_error(zst, err, "while decompressing data");
399 400
                goto error;
            }
401 402 403 404 405 406 407 408 409 410 411

        } while (zst.avail_out == 0);

    } while (err != Z_STREAM_END && ibuflen != 0);


    if (err != Z_STREAM_END) {
        inflateEnd(&zst);
        zlib_error(zst, err, "while decompressing data");
        goto error;
    }
412

413 414
    err = inflateEnd(&zst);
    if (err != Z_OK) {
415
        zlib_error(zst, err, "while finishing decompression");
416
        goto error;
417
    }
418

419 420
    if (_PyBytes_Resize(&RetVal, zst.next_out -
                        (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
421 422
        goto error;

423
    return RetVal;
424 425

 error:
426
    Py_XDECREF(RetVal);
427
    return NULL;
428 429
}

430 431 432 433
/*[clinic input]
zlib.compressobj

    level: int(c_default="Z_DEFAULT_COMPRESSION") = Z_DEFAULT_COMPRESSION
434 435 436
        The compression level (an integer in the range 0-9 or -1; default is
        currently equivalent to 6).  Higher compression levels are slower,
        but produce smaller results.
437 438 439
    method: int(c_default="DEFLATED") = DEFLATED
        The compression algorithm.  If given, this must be DEFLATED.
    wbits: int(c_default="MAX_WBITS") = MAX_WBITS
440 441 442 443
        +9 to +15: The base-two logarithm of the window size.  Include a zlib
            container.
        -9 to -15: Generate a raw stream.
        +25 to +31: Include a gzip container.
444 445 446 447 448 449 450 451 452 453 454 455 456 457
    memLevel: int(c_default="DEF_MEM_LEVEL") = DEF_MEM_LEVEL
        Controls the amount of memory used for internal compression state.
        Valid values range from 1 to 9.  Higher values result in higher memory
        usage, faster compression, and smaller output.
    strategy: int(c_default="Z_DEFAULT_STRATEGY") = Z_DEFAULT_STRATEGY
        Used to tune the compression algorithm.  Possible values are
        Z_DEFAULT_STRATEGY, Z_FILTERED, and Z_HUFFMAN_ONLY.
    zdict: Py_buffer = None
        The predefined compression dictionary - a sequence of bytes
        containing subsequences that are likely to occur in the input data.

Return a compressor object.
[clinic start generated code]*/

458
static PyObject *
459
zlib_compressobj_impl(PyObject *module, int level, int method, int wbits,
460
                      int memLevel, int strategy, Py_buffer *zdict)
461
/*[clinic end generated code: output=8b5bed9c8fc3814d input=2fa3d026f90ab8d5]*/
462
{
463
    compobject *self = NULL;
464
    int err;
Jeremy Hylton's avatar
Jeremy Hylton committed
465

466
    if (zdict->buf != NULL && (size_t)zdict->len > UINT_MAX) {
467 468 469 470 471
        PyErr_SetString(PyExc_OverflowError,
                        "zdict length does not fit in an unsigned int");
        goto error;
    }

Jeremy Hylton's avatar
Jeremy Hylton committed
472
    self = newcompobject(&Comptype);
473
    if (self == NULL)
474
        goto error;
475 476 477
    self->zst.opaque = NULL;
    self->zst.zalloc = PyZlib_Malloc;
    self->zst.zfree = PyZlib_Free;
478 479
    self->zst.next_in = NULL;
    self->zst.avail_in = 0;
Jeremy Hylton's avatar
Jeremy Hylton committed
480
    err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy);
481 482
    switch (err) {
    case Z_OK:
483
        self->is_initialised = 1;
484
        if (zdict->buf == NULL) {
485 486
            goto success;
        } else {
487
            err = deflateSetDictionary(&self->zst,
488
                                       zdict->buf, (unsigned int)zdict->len);
489
            switch (err) {
490
            case Z_OK:
491
                goto success;
492
            case Z_STREAM_ERROR:
493 494 495 496 497 498 499
                PyErr_SetString(PyExc_ValueError, "Invalid dictionary");
                goto error;
            default:
                PyErr_SetString(PyExc_ValueError, "deflateSetDictionary()");
                goto error;
            }
       }
500
    case Z_MEM_ERROR:
501 502
        PyErr_SetString(PyExc_MemoryError,
                        "Can't allocate memory for compression object");
503
        goto error;
504
    case Z_STREAM_ERROR:
505
        PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
506
        goto error;
507
    default:
508
        zlib_error(self->zst, err, "while creating compression object");
509
        goto error;
510
    }
511 512

 error:
513
    Py_CLEAR(self);
514
 success:
515
    return (PyObject *)self;
516 517
}

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
static int
set_inflate_zdict(compobject *self)
{
    Py_buffer zdict_buf;
    int err;

    if (PyObject_GetBuffer(self->zdict, &zdict_buf, PyBUF_SIMPLE) == -1) {
        return -1;
    }
    if ((size_t)zdict_buf.len > UINT_MAX) {
        PyErr_SetString(PyExc_OverflowError,
                        "zdict length does not fit in an unsigned int");
        PyBuffer_Release(&zdict_buf);
        return -1;
    }
533
    err = inflateSetDictionary(&self->zst,
534 535 536 537 538 539 540 541 542
                               zdict_buf.buf, (unsigned int)zdict_buf.len);
    PyBuffer_Release(&zdict_buf);
    if (err != Z_OK) {
        zlib_error(self->zst, err, "while setting zdict");
        return -1;
    }
    return 0;
}

543 544 545 546
/*[clinic input]
zlib.decompressobj

    wbits: int(c_default="MAX_WBITS") = MAX_WBITS
547
        The window buffer size and container format.
548 549 550 551 552 553 554
    zdict: object(c_default="NULL") = b''
        The predefined compression dictionary.  This must be the same
        dictionary as used by the compressor that produced the input data.

Return a decompressor object.
[clinic start generated code]*/

555
static PyObject *
556 557
zlib_decompressobj_impl(PyObject *module, int wbits, PyObject *zdict)
/*[clinic end generated code: output=3069b99994f36906 input=d3832b8511fc977b]*/
558
{
559
    int err;
Jeremy Hylton's avatar
Jeremy Hylton committed
560
    compobject *self;
561 562 563 564

    if (zdict != NULL && !PyObject_CheckBuffer(zdict)) {
        PyErr_SetString(PyExc_TypeError,
                        "zdict argument must support the buffer protocol");
565
        return NULL;
566
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
567 568

    self = newcompobject(&Decomptype);
569
    if (self == NULL)
570
        return NULL;
571 572 573
    self->zst.opaque = NULL;
    self->zst.zalloc = PyZlib_Malloc;
    self->zst.zfree = PyZlib_Free;
574 575
    self->zst.next_in = NULL;
    self->zst.avail_in = 0;
576 577 578 579
    if (zdict != NULL) {
        Py_INCREF(zdict);
        self->zdict = zdict;
    }
Jeremy Hylton's avatar
Jeremy Hylton committed
580
    err = inflateInit2(&self->zst, wbits);
581 582
    switch (err) {
    case Z_OK:
583
        self->is_initialised = 1;
584 585 586 587 588 589 590 591 592 593 594 595 596 597
        if (self->zdict != NULL && wbits < 0) {
#ifdef AT_LEAST_ZLIB_1_2_2_1
            if (set_inflate_zdict(self) < 0) {
                Py_DECREF(self);
                return NULL;
            }
#else
            PyErr_Format(ZlibError,
                         "zlib version %s does not allow raw inflate with dictionary",
                         ZLIB_VERSION);
            Py_DECREF(self);
            return NULL;
#endif
        }
598 599
        return (PyObject *)self;
    case Z_STREAM_ERROR:
600 601 602
        Py_DECREF(self);
        PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
        return NULL;
603
    case Z_MEM_ERROR:
604 605 606 607
        Py_DECREF(self);
        PyErr_SetString(PyExc_MemoryError,
                        "Can't allocate memory for decompression object");
        return NULL;
608
    default:
609
        zlib_error(self->zst, err, "while creating decompression object");
610
        Py_DECREF(self);
611
        return NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
612
    }
613 614 615
}

static void
616
Dealloc(compobject *self)
617
{
618 619 620
#ifdef WITH_THREAD
    PyThread_free_lock(self->lock);
#endif
621
    Py_XDECREF(self->unused_data);
622
    Py_XDECREF(self->unconsumed_tail);
623
    Py_XDECREF(self->zdict);
624
    PyObject_Del(self);
625 626
}

627 628 629 630 631 632 633 634
static void
Comp_dealloc(compobject *self)
{
    if (self->is_initialised)
        deflateEnd(&self->zst);
    Dealloc(self);
}

635
static void
Peter Schneider-Kamp's avatar
Peter Schneider-Kamp committed
636
Decomp_dealloc(compobject *self)
637
{
638
    if (self->is_initialised)
639 640
        inflateEnd(&self->zst);
    Dealloc(self);
641 642
}

643 644 645 646 647 648
/*[clinic input]
zlib.Compress.compress

    data: Py_buffer
        Binary data to be compressed.
    /
Guido van Rossum's avatar
Guido van Rossum committed
649

650 651 652 653 654 655
Returns a bytes object containing compressed data.

After calling this function, some of the input data may still
be stored in internal buffers for later processing.
Call the flush() method to clear these buffers.
[clinic start generated code]*/
Guido van Rossum's avatar
Guido van Rossum committed
656

657
static PyObject *
658
zlib_Compress_compress_impl(compobject *self, Py_buffer *data)
659
/*[clinic end generated code: output=5d5cd791cbc6a7f4 input=0d95908d6e64fab8]*/
660
{
661 662
    PyObject *RetVal = NULL;
    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE;
663
    int err;
Jeremy Hylton's avatar
Jeremy Hylton committed
664

665 666
    self->zst.next_in = data->buf;
    ibuflen = data->len;
667

668
    ENTER_ZLIB(self);
669

670 671
    do {
        arrange_input_buffer(&self->zst, &ibuflen);
672

673 674 675 676
        do {
            obuflen = arrange_output_buffer(&self->zst, &RetVal, obuflen);
            if (obuflen < 0)
                goto error;
677

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
            Py_BEGIN_ALLOW_THREADS
            err = deflate(&self->zst, Z_NO_FLUSH);
            Py_END_ALLOW_THREADS

            if (err == Z_STREAM_ERROR) {
                zlib_error(self->zst, err, "while compressing data");
                goto error;
            }

        } while (self->zst.avail_out == 0);
        assert(self->zst.avail_in == 0);

    } while (ibuflen != 0);

    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
        goto success;
Jeremy Hylton's avatar
Jeremy Hylton committed
695

696 697 698
 error:
    Py_CLEAR(RetVal);
 success:
699
    LEAVE_ZLIB(self);
Jeremy Hylton's avatar
Jeremy Hylton committed
700
    return RetVal;
701 702
}

703
/* Helper for objdecompress() and flush(). Saves any unconsumed input data in
704 705
   self->unused_data or self->unconsumed_tail, as appropriate. */
static int
706
save_unconsumed_input(compobject *self, Py_buffer *data, int err)
707 708 709 710 711 712
{
    if (err == Z_STREAM_END) {
        /* The end of the compressed data has been reached. Store the leftover
           input data in self->unused_data. */
        if (self->zst.avail_in > 0) {
            Py_ssize_t old_size = PyBytes_GET_SIZE(self->unused_data);
713
            Py_ssize_t new_size, left_size;
714
            PyObject *new_data;
715 716
            left_size = (Byte *)data->buf + data->len - self->zst.next_in;
            if (left_size > (PY_SSIZE_T_MAX - old_size)) {
717 718 719
                PyErr_NoMemory();
                return -1;
            }
720
            new_size = old_size + left_size;
721 722 723 724 725 726
            new_data = PyBytes_FromStringAndSize(NULL, new_size);
            if (new_data == NULL)
                return -1;
            Py_MEMCPY(PyBytes_AS_STRING(new_data),
                      PyBytes_AS_STRING(self->unused_data), old_size);
            Py_MEMCPY(PyBytes_AS_STRING(new_data) + old_size,
727
                      self->zst.next_in, left_size);
728
            Py_SETREF(self->unused_data, new_data);
729 730 731
            self->zst.avail_in = 0;
        }
    }
732

733 734 735 736
    if (self->zst.avail_in > 0 || PyBytes_GET_SIZE(self->unconsumed_tail)) {
        /* This code handles two distinct cases:
           1. Output limit was reached. Save leftover input in unconsumed_tail.
           2. All input data was consumed. Clear unconsumed_tail. */
737
        Py_ssize_t left_size = (Byte *)data->buf + data->len - self->zst.next_in;
738
        PyObject *new_data = PyBytes_FromStringAndSize(
739
                (char *)self->zst.next_in, left_size);
740 741
        if (new_data == NULL)
            return -1;
742
        Py_SETREF(self->unconsumed_tail, new_data);
743
    }
744

745 746 747
    return 0;
}

748
/*[clinic input]
749
zlib.Decompress.decompress
750 751 752

    data: Py_buffer
        The binary data to decompress.
753
    /
754
    max_length: ssize_t = 0
755 756 757 758
        The maximum allowable length of the decompressed data.
        Unconsumed input data will be stored in
        the unconsumed_tail attribute.

759
Return a bytes object containing the decompressed version of the data.
760 761 762 763

After calling this function, some of the input data may still be stored in
internal buffers for later processing.
Call the flush() method to clear these buffers.
764
[clinic start generated code]*/
765 766

static PyObject *
767
zlib_Decompress_decompress_impl(compobject *self, Py_buffer *data,
768
                                Py_ssize_t max_length)
769
/*[clinic end generated code: output=6e5173c74e710352 input=b85a212a012b770a]*/
770
{
771 772
    int err = Z_OK;
    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE, hard_limit;
773
    PyObject *RetVal = NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
774

775 776
    if (max_length < 0) {
        PyErr_SetString(PyExc_ValueError, "max_length must be non-negative");
777
        return NULL;
778 779 780 781
    } else if (max_length == 0)
        hard_limit = PY_SSIZE_T_MAX;
    else
        hard_limit = max_length;
782

783
    self->zst.next_in = data->buf;
784
    ibuflen = data->len;
785

786 787 788
    /* limit amount of data allocated to max_length */
    if (max_length && obuflen > max_length)
        obuflen = max_length;
789

790
    ENTER_ZLIB(self);
791

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    do {
        arrange_input_buffer(&self->zst, &ibuflen);

        do {
            obuflen = arrange_output_buffer_with_maximum(&self->zst, &RetVal,
                                                         obuflen, hard_limit);
            if (obuflen == -2) {
                if (max_length > 0) {
                    goto save;
                }
                PyErr_NoMemory();
            }
            if (obuflen < 0) {
                goto abort;
            }
807

808 809 810
            Py_BEGIN_ALLOW_THREADS
            err = inflate(&self->zst, Z_SYNC_FLUSH);
            Py_END_ALLOW_THREADS
811

812 813 814 815 816 817 818 819 820 821 822 823 824 825
            switch (err) {
            case Z_OK:            /* fall through */
            case Z_BUF_ERROR:     /* fall through */
            case Z_STREAM_END:
                break;
            default:
                if (err == Z_NEED_DICT && self->zdict != NULL) {
                    if (set_inflate_zdict(self) < 0)
                        goto abort;
                    else
                        break;
                }
                goto save;
            }
826

827
        } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);
828

829
    } while (err != Z_STREAM_END && ibuflen != 0);
830

831 832 833
 save:
    if (save_unconsumed_input(self, data, err) < 0)
        goto abort;
Jeremy Hylton's avatar
Jeremy Hylton committed
834

835
    if (err == Z_STREAM_END) {
836 837
        /* This is the logical place to call inflateEnd, but the old behaviour
           of only calling it on flush() is preserved. */
838
        self->eof = 1;
839
    } else if (err != Z_OK && err != Z_BUF_ERROR) {
840 841 842 843
        /* We will only get Z_BUF_ERROR if the output buffer was full
           but there wasn't more output when we tried again, so it is
           not an error condition.
        */
844
        zlib_error(self->zst, err, "while decompressing data");
845
        goto abort;
846
    }
847

848 849 850
    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
        goto success;
851

852 853 854
 abort:
    Py_CLEAR(RetVal);
 success:
855
    LEAVE_ZLIB(self);
Jeremy Hylton's avatar
Jeremy Hylton committed
856
    return RetVal;
857 858
}

859 860 861
/*[clinic input]
zlib.Compress.flush

862
    mode: int(c_default="Z_FINISH") = zlib.Z_FINISH
863 864 865 866 867 868 869 870
        One of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH.
        If mode == Z_FINISH, the compressor object can no longer be
        used after calling the flush() method.  Otherwise, more data
        can still be compressed.
    /

Return a bytes object containing any remaining compressed data.
[clinic start generated code]*/
Guido van Rossum's avatar
Guido van Rossum committed
871

872
static PyObject *
873
zlib_Compress_flush_impl(compobject *self, int mode)
874
/*[clinic end generated code: output=a203f4cefc9de727 input=73ed066794bd15bc]*/
875
{
876
    int err;
877 878
    Py_ssize_t length = DEF_BUF_SIZE;
    PyObject *RetVal = NULL;
879

Jeremy Hylton's avatar
Jeremy Hylton committed
880 881
    /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
       doing any work at all; just return an empty string. */
882
    if (mode == Z_NO_FLUSH) {
883
        return PyBytes_FromStringAndSize(NULL, 0);
Jeremy Hylton's avatar
Jeremy Hylton committed
884
    }
885

886
    ENTER_ZLIB(self);
887

Jeremy Hylton's avatar
Jeremy Hylton committed
888
    self->zst.avail_in = 0;
889 890 891 892

    do {
        length = arrange_output_buffer(&self->zst, &RetVal, length);
        if (length < 0) {
893
            Py_CLEAR(RetVal);
894
            goto error;
895
        }
Jeremy Hylton's avatar
Jeremy Hylton committed
896

897
        Py_BEGIN_ALLOW_THREADS
898
        err = deflate(&self->zst, mode);
899
        Py_END_ALLOW_THREADS
900 901 902 903 904 905 906 907

        if (err == Z_STREAM_ERROR) {
            zlib_error(self->zst, err, "while flushing");
            Py_CLEAR(RetVal);
            goto error;
        }
    } while (self->zst.avail_out == 0);
    assert(self->zst.avail_in == 0);
908

909
    /* If mode is Z_FINISH, we also have to call deflateEnd() to free
910
       various data structures. Note we should only get Z_STREAM_END when
911 912
       mode is Z_FINISH, but checking both for safety*/
    if (err == Z_STREAM_END && mode == Z_FINISH) {
913
        err = deflateEnd(&self->zst);
914
        if (err != Z_OK) {
915
            zlib_error(self->zst, err, "while finishing compression");
916
            Py_CLEAR(RetVal);
917 918 919 920 921 922 923 924 925
            goto error;
        }
        else
            self->is_initialised = 0;

        /* We will only get Z_BUF_ERROR if the output buffer was full
           but there wasn't more output when we tried again, so it is
           not an error condition.
        */
926
    } else if (err != Z_OK && err != Z_BUF_ERROR) {
927
        zlib_error(self->zst, err, "while flushing");
928
        Py_CLEAR(RetVal);
929
        goto error;
Jeremy Hylton's avatar
Jeremy Hylton committed
930
    }
931

932 933
    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
                        (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
934
        Py_CLEAR(RetVal);
935

936
 error:
937
    LEAVE_ZLIB(self);
938
    return RetVal;
939 940
}

941
#ifdef HAVE_ZLIB_COPY
942

943
/*[clinic input]
944
zlib.Compress.copy
945 946

Return a copy of the compression object.
947
[clinic start generated code]*/
948

949 950
static PyObject *
zlib_Compress_copy_impl(compobject *self)
951
/*[clinic end generated code: output=5144aa153c21e805 input=c656351f94b82718]*/
952 953 954 955 956 957 958 959 960 961
{
    compobject *retval = NULL;
    int err;

    retval = newcompobject(&Comptype);
    if (!retval) return NULL;

    /* Copy the zstream state
     * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe
     */
962 963
    ENTER_ZLIB(self);
    err = deflateCopy(&retval->zst, &self->zst);
964 965
    switch (err) {
    case Z_OK:
966
        break;
967
    case Z_STREAM_ERROR:
968 969
        PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
        goto error;
970
    case Z_MEM_ERROR:
971 972 973 974
        PyErr_SetString(PyExc_MemoryError,
                        "Can't allocate memory for compression object");
        goto error;
    default:
975
        zlib_error(self->zst, err, "while copying compression object");
976 977
        goto error;
    }
978
    Py_INCREF(self->unused_data);
979
    Py_XSETREF(retval->unused_data, self->unused_data);
980
    Py_INCREF(self->unconsumed_tail);
981
    Py_XSETREF(retval->unconsumed_tail, self->unconsumed_tail);
982
    Py_XINCREF(self->zdict);
983
    Py_XSETREF(retval->zdict, self->zdict);
984
    retval->eof = self->eof;
985 986 987 988

    /* Mark it as being initialized */
    retval->is_initialised = 1;

989
    LEAVE_ZLIB(self);
990 991 992
    return (PyObject *)retval;

error:
993
    LEAVE_ZLIB(self);
994 995 996 997
    Py_XDECREF(retval);
    return NULL;
}

998 999 1000 1001 1002
/*[clinic input]
zlib.Decompress.copy

Return a copy of the decompression object.
[clinic start generated code]*/
1003 1004

static PyObject *
1005
zlib_Decompress_copy_impl(compobject *self)
1006
/*[clinic end generated code: output=02a883a2a510c8cc input=ba6c3e96712a596b]*/
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
{
    compobject *retval = NULL;
    int err;

    retval = newcompobject(&Decomptype);
    if (!retval) return NULL;

    /* Copy the zstream state
     * We use ENTER_ZLIB / LEAVE_ZLIB to make this thread-safe
     */
1017
    ENTER_ZLIB(self);
1018
    err = inflateCopy(&retval->zst, &self->zst);
1019 1020
    switch (err) {
    case Z_OK:
1021
        break;
1022
    case Z_STREAM_ERROR:
1023 1024
        PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
        goto error;
1025
    case Z_MEM_ERROR:
1026 1027 1028 1029 1030 1031 1032 1033 1034
        PyErr_SetString(PyExc_MemoryError,
                        "Can't allocate memory for decompression object");
        goto error;
    default:
        zlib_error(self->zst, err, "while copying decompression object");
        goto error;
    }

    Py_INCREF(self->unused_data);
1035
    Py_XSETREF(retval->unused_data, self->unused_data);
1036
    Py_INCREF(self->unconsumed_tail);
1037
    Py_XSETREF(retval->unconsumed_tail, self->unconsumed_tail);
1038
    Py_XINCREF(self->zdict);
1039
    Py_XSETREF(retval->zdict, self->zdict);
1040
    retval->eof = self->eof;
1041 1042 1043 1044

    /* Mark it as being initialized */
    retval->is_initialised = 1;

1045
    LEAVE_ZLIB(self);
1046 1047 1048
    return (PyObject *)retval;

error:
1049
    LEAVE_ZLIB(self);
1050 1051 1052
    Py_XDECREF(retval);
    return NULL;
}
1053
#endif
1054

1055 1056 1057
/*[clinic input]
zlib.Decompress.flush

1058
    length: ssize_t(c_default="DEF_BUF_SIZE") = zlib.DEF_BUF_SIZE
1059 1060 1061 1062 1063
        the initial size of the output buffer.
    /

Return a bytes object containing any remaining decompressed data.
[clinic start generated code]*/
Guido van Rossum's avatar
Guido van Rossum committed
1064

1065
static PyObject *
1066 1067
zlib_Decompress_flush_impl(compobject *self, Py_ssize_t length)
/*[clinic end generated code: output=68c75ea127cbe654 input=aa4ec37f3aef4da0]*/
1068
{
1069 1070 1071 1072
    int err, flush;
    Py_buffer data;
    PyObject *RetVal = NULL;
    Py_ssize_t ibuflen;
1073

1074
    if (length <= 0) {
1075 1076
        PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
        return NULL;
Christian Heimes's avatar
Christian Heimes committed
1077
    }
1078

1079
    if (PyObject_GetBuffer(self->unconsumed_tail, &data, PyBUF_SIMPLE) == -1)
1080
        return NULL;
1081

1082
    ENTER_ZLIB(self);
1083

1084 1085
    self->zst.next_in = data.buf;
    ibuflen = data.len;
1086

1087 1088 1089
    do {
        arrange_input_buffer(&self->zst, &ibuflen);
        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
1090

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
        do {
            length = arrange_output_buffer(&self->zst, &RetVal, length);
            if (length < 0)
                goto abort;

            Py_BEGIN_ALLOW_THREADS
            err = inflate(&self->zst, flush);
            Py_END_ALLOW_THREADS

            switch (err) {
            case Z_OK:            /* fall through */
            case Z_BUF_ERROR:     /* fall through */
            case Z_STREAM_END:
                break;
            default:
                if (err == Z_NEED_DICT && self->zdict != NULL) {
                    if (set_inflate_zdict(self) < 0)
                        goto abort;
                    else
                        break;
                }
                goto save;
            }

        } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);

    } while (err != Z_STREAM_END && ibuflen != 0);

 save:
    if (save_unconsumed_input(self, &data, err) < 0)
        goto abort;
1122

1123
    /* If at end of stream, clean up any memory allocated by zlib. */
1124
    if (err == Z_STREAM_END) {
1125
        self->eof = 1;
1126
        self->is_initialised = 0;
1127
        err = inflateEnd(&self->zst);
1128
        if (err != Z_OK) {
1129
            zlib_error(self->zst, err, "while finishing decompression");
1130
            goto abort;
1131
        }
Jeremy Hylton's avatar
Jeremy Hylton committed
1132
    }
1133

1134 1135 1136
    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
        goto success;
1137

1138 1139 1140 1141
 abort:
    Py_CLEAR(RetVal);
 success:
    PyBuffer_Release(&data);
1142
    LEAVE_ZLIB(self);
1143
    return RetVal;
1144 1145
}

1146
#include "clinic/zlibmodule.c.h"
1147

1148 1149
static PyMethodDef comp_methods[] =
{
1150 1151
    ZLIB_COMPRESS_COMPRESS_METHODDEF
    ZLIB_COMPRESS_FLUSH_METHODDEF
1152
#ifdef HAVE_ZLIB_COPY
1153
    ZLIB_COMPRESS_COPY_METHODDEF
1154
#endif
Jeremy Hylton's avatar
Jeremy Hylton committed
1155
    {NULL, NULL}
1156 1157 1158 1159
};

static PyMethodDef Decomp_methods[] =
{
1160
    ZLIB_DECOMPRESS_DECOMPRESS_METHODDEF
1161
    ZLIB_DECOMPRESS_FLUSH_METHODDEF
1162
#ifdef HAVE_ZLIB_COPY
1163
    ZLIB_DECOMPRESS_COPY_METHODDEF
1164
#endif
Jeremy Hylton's avatar
Jeremy Hylton committed
1165
    {NULL, NULL}
1166 1167
};

1168 1169 1170 1171
#define COMP_OFF(x) offsetof(compobject, x)
static PyMemberDef Decomp_members[] = {
    {"unused_data",     T_OBJECT, COMP_OFF(unused_data), READONLY},
    {"unconsumed_tail", T_OBJECT, COMP_OFF(unconsumed_tail), READONLY},
1172
    {"eof",             T_BOOL,   COMP_OFF(eof), READONLY},
1173 1174
    {NULL},
};
1175

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
/*[clinic input]
zlib.adler32

    data: Py_buffer
    value: unsigned_int(bitwise=True) = 1
        Starting value of the checksum.
    /

Compute an Adler-32 checksum of data.

The returned checksum is an integer.
[clinic start generated code]*/
Guido van Rossum's avatar
Guido van Rossum committed
1188

1189
static PyObject *
1190 1191
zlib_adler32_impl(PyObject *module, Py_buffer *data, unsigned int value)
/*[clinic end generated code: output=422106f5ca8c92c0 input=6ff4557872160e88]*/
1192
{
1193 1194
    /* Releasing the GIL for very small buffers is inefficient
       and may lower performance */
1195 1196 1197
    if (data->len > 1024*5) {
        unsigned char *buf = data->buf;
        Py_ssize_t len = data->len;
1198

1199
        Py_BEGIN_ALLOW_THREADS
1200 1201
        /* Avoid truncation of length for very large buffers. adler32() takes
           length as an unsigned int, which may be narrower than Py_ssize_t. */
1202
        while ((size_t)len > UINT_MAX) {
1203
            value = adler32(value, buf, UINT_MAX);
1204 1205 1206
            buf += (size_t) UINT_MAX;
            len -= (size_t) UINT_MAX;
        }
1207
        value = adler32(value, buf, (unsigned int)len);
1208 1209
        Py_END_ALLOW_THREADS
    } else {
1210
        value = adler32(value, data->buf, (unsigned int)data->len);
1211
    }
1212
    return PyLong_FromUnsignedLong(value & 0xffffffffU);
1213
}
1214

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
/*[clinic input]
zlib.crc32

    data: Py_buffer
    value: unsigned_int(bitwise=True) = 0
        Starting value of the checksum.
    /

Compute a CRC-32 checksum of data.

The returned checksum is an integer.
[clinic start generated code]*/
1227 1228

static PyObject *
1229 1230
zlib_crc32_impl(PyObject *module, Py_buffer *data, unsigned int value)
/*[clinic end generated code: output=63499fa20af7ea25 input=26c3ed430fa00b4c]*/
1231
{
1232
    int signed_val;
Christian Heimes's avatar
Christian Heimes committed
1233

1234 1235
    /* Releasing the GIL for very small buffers is inefficient
       and may lower performance */
1236 1237 1238
    if (data->len > 1024*5) {
        unsigned char *buf = data->buf;
        Py_ssize_t len = data->len;
1239

1240
        Py_BEGIN_ALLOW_THREADS
1241 1242
        /* Avoid truncation of length for very large buffers. crc32() takes
           length as an unsigned int, which may be narrower than Py_ssize_t. */
1243
        while ((size_t)len > UINT_MAX) {
1244
            value = crc32(value, buf, UINT_MAX);
1245 1246 1247
            buf += (size_t) UINT_MAX;
            len -= (size_t) UINT_MAX;
        }
1248
        signed_val = crc32(value, buf, (unsigned int)len);
1249 1250
        Py_END_ALLOW_THREADS
    } else {
1251
        signed_val = crc32(value, data->buf, (unsigned int)data->len);
1252
    }
Christian Heimes's avatar
Christian Heimes committed
1253
    return PyLong_FromUnsignedLong(signed_val & 0xffffffffU);
1254
}
1255

1256 1257 1258

static PyMethodDef zlib_methods[] =
{
1259
    ZLIB_ADLER32_METHODDEF
1260
    ZLIB_COMPRESS_METHODDEF
1261 1262 1263 1264
    ZLIB_COMPRESSOBJ_METHODDEF
    ZLIB_CRC32_METHODDEF
    ZLIB_DECOMPRESS_METHODDEF
    ZLIB_DECOMPRESSOBJ_METHODDEF
Jeremy Hylton's avatar
Jeremy Hylton committed
1265
    {NULL, NULL}
1266 1267
};

1268
static PyTypeObject Comptype = {
1269
    PyVarObject_HEAD_INIT(0, 0)
1270
    "zlib.Compress",
Jeremy Hylton's avatar
Jeremy Hylton committed
1271 1272 1273 1274
    sizeof(compobject),
    0,
    (destructor)Comp_dealloc,       /*tp_dealloc*/
    0,                              /*tp_print*/
1275
    0,                              /*tp_getattr*/
Jeremy Hylton's avatar
Jeremy Hylton committed
1276
    0,                              /*tp_setattr*/
1277
    0,                              /*tp_reserved*/
Jeremy Hylton's avatar
Jeremy Hylton committed
1278 1279 1280 1281
    0,                              /*tp_repr*/
    0,                              /*tp_as_number*/
    0,                              /*tp_as_sequence*/
    0,                              /*tp_as_mapping*/
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    0,                              /*tp_hash*/
    0,                              /*tp_call*/
    0,                              /*tp_str*/
    0,                              /*tp_getattro*/
    0,                              /*tp_setattro*/
    0,                              /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT,             /*tp_flags*/
    0,                              /*tp_doc*/
    0,                              /*tp_traverse*/
    0,                              /*tp_clear*/
    0,                              /*tp_richcompare*/
    0,                              /*tp_weaklistoffset*/
    0,                              /*tp_iter*/
    0,                              /*tp_iternext*/
    comp_methods,                   /*tp_methods*/
1297 1298
};

1299
static PyTypeObject Decomptype = {
1300
    PyVarObject_HEAD_INIT(0, 0)
1301
    "zlib.Decompress",
Jeremy Hylton's avatar
Jeremy Hylton committed
1302 1303 1304 1305
    sizeof(compobject),
    0,
    (destructor)Decomp_dealloc,     /*tp_dealloc*/
    0,                              /*tp_print*/
1306
    0,                              /*tp_getattr*/
Jeremy Hylton's avatar
Jeremy Hylton committed
1307
    0,                              /*tp_setattr*/
1308
    0,                              /*tp_reserved*/
Jeremy Hylton's avatar
Jeremy Hylton committed
1309 1310 1311 1312
    0,                              /*tp_repr*/
    0,                              /*tp_as_number*/
    0,                              /*tp_as_sequence*/
    0,                              /*tp_as_mapping*/
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    0,                              /*tp_hash*/
    0,                              /*tp_call*/
    0,                              /*tp_str*/
    0,                              /*tp_getattro*/
    0,                              /*tp_setattro*/
    0,                              /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT,             /*tp_flags*/
    0,                              /*tp_doc*/
    0,                              /*tp_traverse*/
    0,                              /*tp_clear*/
    0,                              /*tp_richcompare*/
    0,                              /*tp_weaklistoffset*/
    0,                              /*tp_iter*/
    0,                              /*tp_iternext*/
    Decomp_methods,                 /*tp_methods*/
    Decomp_members,                 /*tp_members*/
1329 1330
};

1331
PyDoc_STRVAR(zlib_module_documentation,
1332 1333 1334 1335
"The functions in this module allow compression and decompression using the\n"
"zlib library, which is based on GNU zip.\n"
"\n"
"adler32(string[, start]) -- Compute an Adler-32 checksum.\n"
1336
"compress(data[, level]) -- Compress data, with compression level 0-9 or -1.\n"
1337
"compressobj([level[, ...]]) -- Return a compressor object.\n"
1338
"crc32(string[, start]) -- Compute a CRC-32 checksum.\n"
1339
"decompress(string,[wbits],[bufsize]) -- Decompresses a compressed string.\n"
1340
"decompressobj([wbits[, zdict]]]) -- Return a decompressor object.\n"
1341
"\n"
1342
"'wbits' is window buffer size and container format.\n"
1343
"Compressor objects support compress() and flush() methods; decompressor\n"
1344
"objects support decompress() and flush().");
Guido van Rossum's avatar
Guido van Rossum committed
1345

1346
static struct PyModuleDef zlibmodule = {
1347 1348 1349 1350 1351 1352 1353 1354 1355
        PyModuleDef_HEAD_INIT,
        "zlib",
        zlib_module_documentation,
        -1,
        zlib_methods,
        NULL,
        NULL,
        NULL,
        NULL
1356 1357
};

1358
PyMODINIT_FUNC
1359
PyInit_zlib(void)
1360
{
1361
    PyObject *m, *ver;
1362
    if (PyType_Ready(&Comptype) < 0)
1363
            return NULL;
1364
    if (PyType_Ready(&Decomptype) < 0)
1365
            return NULL;
1366
    m = PyModule_Create(&zlibmodule);
1367
    if (m == NULL)
1368
        return NULL;
Jeremy Hylton's avatar
Jeremy Hylton committed
1369

1370 1371 1372
    ZlibError = PyErr_NewException("zlib.error", NULL, NULL);
    if (ZlibError != NULL) {
        Py_INCREF(ZlibError);
1373
        PyModule_AddObject(m, "error", ZlibError);
1374
    }
1375 1376 1377
    PyModule_AddIntMacro(m, MAX_WBITS);
    PyModule_AddIntMacro(m, DEFLATED);
    PyModule_AddIntMacro(m, DEF_MEM_LEVEL);
1378
    PyModule_AddIntMacro(m, DEF_BUF_SIZE);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
    PyModule_AddIntMacro(m, Z_BEST_SPEED);
    PyModule_AddIntMacro(m, Z_BEST_COMPRESSION);
    PyModule_AddIntMacro(m, Z_DEFAULT_COMPRESSION);
    PyModule_AddIntMacro(m, Z_FILTERED);
    PyModule_AddIntMacro(m, Z_HUFFMAN_ONLY);
    PyModule_AddIntMacro(m, Z_DEFAULT_STRATEGY);

    PyModule_AddIntMacro(m, Z_FINISH);
    PyModule_AddIntMacro(m, Z_NO_FLUSH);
    PyModule_AddIntMacro(m, Z_SYNC_FLUSH);
    PyModule_AddIntMacro(m, Z_FULL_FLUSH);
1390

1391
    ver = PyUnicode_FromString(ZLIB_VERSION);
1392
    if (ver != NULL)
1393
        PyModule_AddObject(m, "ZLIB_VERSION", ver);
1394

1395 1396 1397 1398
    ver = PyUnicode_FromString(zlibVersion());
    if (ver != NULL)
        PyModule_AddObject(m, "ZLIB_RUNTIME_VERSION", ver);

1399 1400
    PyModule_AddStringConstant(m, "__version__", "1.0");

1401
    return m;
1402
}