bz2module.c 50.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*

python-bz2 - python bz2 library interface

Copyright (c) 2002  Gustavo Niemeyer <niemeyer@conectiva.com>
Copyright (c) 2002  Python Software Foundation; All Rights Reserved

*/

10
#include "Python.h"
11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <stdio.h>
#include <bzlib.h>
#include "structmember.h"

#ifdef WITH_THREAD
#include "pythread.h"
#endif

static char __author__[] =
"The bz2 python module was written by:\n\
\n\
    Gustavo Niemeyer <niemeyer@conectiva.com>\n\
";

25 26 27 28 29 30 31 32 33 34 35 36
/* Our very own off_t-like type, 64-bit if possible */
/* copied from Objects/fileobject.c */
#if !defined(HAVE_LARGEFILE_SUPPORT)
typedef off_t Py_off_t;
#elif SIZEOF_OFF_T >= 8
typedef off_t Py_off_t;
#elif SIZEOF_FPOS_T >= 8
typedef fpos_t Py_off_t;
#else
#error "Large file support, but neither off_t nor fpos_t is large enough."
#endif

37
#define BUF(v) PyBytes_AS_STRING(v)
38 39 40 41 42 43

#define MODE_CLOSED   0
#define MODE_READ     1
#define MODE_READ_EOF 2
#define MODE_WRITE    3

44
#define BZ2FileObject_Check(v)	(Py_TYPE(v) == &BZ2File_Type)
45

46 47 48

#ifdef BZ_CONFIG_ERROR

49 50 51 52 53
#if SIZEOF_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
	(((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
#elif SIZEOF_LONG_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
54
	(((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
55 56
#else
#define BZS_TOTAL_OUT(bzs) \
57
	bzs->total_out_lo32
58 59
#endif

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#else /* ! BZ_CONFIG_ERROR */

#define BZ2_bzRead bzRead
#define BZ2_bzReadOpen bzReadOpen
#define BZ2_bzReadClose bzReadClose
#define BZ2_bzWrite bzWrite
#define BZ2_bzWriteOpen bzWriteOpen
#define BZ2_bzWriteClose bzWriteClose
#define BZ2_bzCompress bzCompress
#define BZ2_bzCompressInit bzCompressInit
#define BZ2_bzCompressEnd bzCompressEnd
#define BZ2_bzDecompress bzDecompress
#define BZ2_bzDecompressInit bzDecompressInit
#define BZ2_bzDecompressEnd bzDecompressEnd

#define BZS_TOTAL_OUT(bzs) bzs->total_out

#endif /* ! BZ_CONFIG_ERROR */


80
#ifdef WITH_THREAD
81 82 83 84 85 86
#define ACQUIRE_LOCK(obj) do { \
	if (!PyThread_acquire_lock(obj->lock, 0)) { \
		Py_BEGIN_ALLOW_THREADS \
		PyThread_acquire_lock(obj->lock, 1); \
		Py_END_ALLOW_THREADS \
	} } while(0)
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock)
#else
#define ACQUIRE_LOCK(obj)
#define RELEASE_LOCK(obj)
#endif

/* Bits in f_newlinetypes */
#define NEWLINE_UNKNOWN	0	/* No newline seen, yet */
#define NEWLINE_CR 1		/* \r newline seen */
#define NEWLINE_LF 2		/* \n newline seen */
#define NEWLINE_CRLF 4		/* \r\n newline seen */

/* ===================================================================== */
/* Structure definitions. */

typedef struct {
103
	PyObject_HEAD
104
	FILE *rawfp;
105 106 107 108 109

	char* f_buf;		/* Allocated readahead buffer */
	char* f_bufend;		/* Points after last occupied position */
	char* f_bufptr;		/* Current buffer position */

110 111
	BZFILE *fp;
	int mode;
112 113
	Py_off_t pos;
	Py_off_t size;
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
#ifdef WITH_THREAD
	PyThread_type_lock lock;
#endif
} BZ2FileObject;

typedef struct {
	PyObject_HEAD
	bz_stream bzs;
	int running;
#ifdef WITH_THREAD
	PyThread_type_lock lock;
#endif
} BZ2CompObject;

typedef struct {
	PyObject_HEAD
	bz_stream bzs;
	int running;
	PyObject *unused_data;
#ifdef WITH_THREAD
	PyThread_type_lock lock;
#endif
} BZ2DecompObject;

/* ===================================================================== */
/* Utility functions. */

static int
Util_CatchBZ2Error(int bzerror)
{
	int ret = 0;
	switch(bzerror) {
		case BZ_OK:
		case BZ_STREAM_END:
			break;

150
#ifdef BZ_CONFIG_ERROR
151 152 153 154 155 156
		case BZ_CONFIG_ERROR:
			PyErr_SetString(PyExc_SystemError,
					"the bz2 library was not compiled "
					"correctly");
			ret = 1;
			break;
157
#endif
158

159 160 161 162 163 164
		case BZ_PARAM_ERROR:
			PyErr_SetString(PyExc_ValueError,
					"the bz2 library has received wrong "
					"parameters");
			ret = 1;
			break;
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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
		case BZ_MEM_ERROR:
			PyErr_NoMemory();
			ret = 1;
			break;

		case BZ_DATA_ERROR:
		case BZ_DATA_ERROR_MAGIC:
			PyErr_SetString(PyExc_IOError, "invalid data stream");
			ret = 1;
			break;

		case BZ_IO_ERROR:
			PyErr_SetString(PyExc_IOError, "unknown IO error");
			ret = 1;
			break;

		case BZ_UNEXPECTED_EOF:
			PyErr_SetString(PyExc_EOFError,
					"compressed file ended before the "
					"logical end-of-stream was detected");
			ret = 1;
			break;

		case BZ_SEQUENCE_ERROR:
			PyErr_SetString(PyExc_RuntimeError,
					"wrong sequence of bz2 library "
					"commands used");
			ret = 1;
			break;
	}
	return ret;
}

#if BUFSIZ < 8192
#define SMALLCHUNK 8192
#else
#define SMALLCHUNK BUFSIZ
#endif

#if SIZEOF_INT < 4
#define BIGCHUNK  (512 * 32)
#else
#define BIGCHUNK  (512 * 1024)
#endif

/* This is a hacked version of Python's fileobject.c:new_buffersize(). */
static size_t
Util_NewBufferSize(size_t currentsize)
{
	if (currentsize > SMALLCHUNK) {
		/* Keep doubling until we reach BIGCHUNK;
		   then keep adding BIGCHUNK. */
		if (currentsize <= BIGCHUNK)
			return currentsize + currentsize;
		else
			return currentsize + BIGCHUNK;
	}
	return currentsize + SMALLCHUNK;
}

/* This is a hacked version of Python's fileobject.c:get_line(). */
static PyObject *
228
Util_GetLine(BZ2FileObject *f, int n)
229 230 231 232 233 234 235 236
{
	char c;
	char *buf, *end;
	size_t total_v_size;	/* total # of slots in buffer */
	size_t used_v_size;	/* # used slots in buffer */
	size_t increment;       /* amount to increment the buffer */
	PyObject *v;
	int bzerror;
237
	int bytes_read;
238 239

	total_v_size = n > 0 ? n : 100;
240
	v = PyBytes_FromStringAndSize((char *)NULL, total_v_size);
241 242 243 244 245 246 247 248
	if (v == NULL)
		return NULL;

	buf = BUF(v);
	end = buf + total_v_size;

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
249
		do {
250
			bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
251
			f->pos++;
252 253
			if (bytes_read == 0)
				break;
254 255
			*buf++ = c;
		} while (bzerror == BZ_OK && c != '\n' && buf != end);
256 257
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
258 259
			f->size = f->pos;
			f->mode = MODE_READ_EOF;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
			break;
		} else if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			Py_DECREF(v);
			return NULL;
		}
		if (c == '\n')
			break;
		/* Must be because buf == end */
		if (n > 0)
			break;
		used_v_size = total_v_size;
		increment = total_v_size >> 2; /* mild exponential growth */
		total_v_size += increment;
		if (total_v_size > INT_MAX) {
			PyErr_SetString(PyExc_OverflowError,
			    "line is longer than a Python string can hold");
			Py_DECREF(v);
			return NULL;
		}
280
		if (_PyBytes_Resize(&v, total_v_size) < 0) {
281
			return NULL;
282
		}
283 284 285 286 287
		buf = BUF(v) + used_v_size;
		end = BUF(v) + total_v_size;
	}

	used_v_size = buf - BUF(v);
288
	if (used_v_size != total_v_size) {
289
		if (_PyBytes_Resize(&v, used_v_size) < 0) {
290 291 292
			v = NULL;
		}
	}
293 294 295 296 297
	return v;
}

/* This is a hacked version of Python's fileobject.c:drop_readahead(). */
static void
298
Util_DropReadAhead(BZ2FileObject *f)
299 300 301 302 303 304 305 306 307
{
	if (f->f_buf != NULL) {
		PyMem_Free(f->f_buf);
		f->f_buf = NULL;
	}
}

/* This is a hacked version of Python's fileobject.c:readahead(). */
static int
308
Util_ReadAhead(BZ2FileObject *f, int bufsize)
309 310 311 312 313
{
	int chunksize;
	int bzerror;

	if (f->f_buf != NULL) {
314
		if((f->f_bufend - f->f_bufptr) >= 1)
315 316
			return 0;
		else
317
			Util_DropReadAhead(f);
318
	}
319
	if (f->mode == MODE_READ_EOF) {
320 321 322
		f->f_bufptr = f->f_buf;
		f->f_bufend = f->f_buf;
		return 0;
323 324
	}
	if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
Georg Brandl's avatar
Georg Brandl committed
325
		PyErr_NoMemory();
326 327 328
		return -1;
	}
	Py_BEGIN_ALLOW_THREADS
329
	chunksize = BZ2_bzRead(&bzerror, f->fp, f->f_buf, bufsize);
330
	Py_END_ALLOW_THREADS
331
	f->pos += chunksize;
332
	if (bzerror == BZ_STREAM_END) {
333 334
		f->size = f->pos;
		f->mode = MODE_READ_EOF;
335 336
	} else if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
337
		Util_DropReadAhead(f);
338 339 340 341 342 343 344 345 346
		return -1;
	}
	f->f_bufptr = f->f_buf;
	f->f_bufend = f->f_buf + chunksize;
	return 0;
}

/* This is a hacked version of Python's
 * fileobject.c:readahead_get_line_skip(). */
347
static PyBytesObject *
348
Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize)
349
{
350
	PyBytesObject* s;
351 352 353 354 355
	char *bufptr;
	char *buf;
	int len;

	if (f->f_buf == NULL)
356
		if (Util_ReadAhead(f, bufsize) < 0)
357 358 359
			return NULL;

	len = f->f_bufend - f->f_bufptr;
360
	if (len == 0)
361 362
		return (PyBytesObject *)
			PyBytes_FromStringAndSize(NULL, skip);
363 364 365 366
	bufptr = memchr(f->f_bufptr, '\n', len);
	if (bufptr != NULL) {
		bufptr++;			/* Count the '\n' */
		len = bufptr - f->f_bufptr;
367 368
		s = (PyBytesObject *)
			PyBytes_FromStringAndSize(NULL, skip+len);
369
		if (s == NULL)
370
			return NULL;
371
		memcpy(PyBytes_AS_STRING(s)+skip, f->f_bufptr, len);
372 373
		f->f_bufptr = bufptr;
		if (bufptr == f->f_bufend)
374
			Util_DropReadAhead(f);
375 376 377 378
	} else {
		bufptr = f->f_bufptr;
		buf = f->f_buf;
		f->f_buf = NULL; 	/* Force new readahead buffer */
379 380
                s = Util_ReadAheadGetLineSkip(f, skip+len,
					      bufsize + (bufsize>>2));
381 382 383 384
		if (s == NULL) {
		        PyMem_Free(buf);
			return NULL;
		}
385
		memcpy(PyBytes_AS_STRING(s)+skip, bufptr, len);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
		PyMem_Free(buf);
	}
	return s;
}

/* ===================================================================== */
/* Methods of BZ2File. */

PyDoc_STRVAR(BZ2File_read__doc__,
"read([size]) -> string\n\
\n\
Read at most size uncompressed bytes, returned as a string. If the size\n\
argument is negative or omitted, read until EOF is reached.\n\
");

/* This is a hacked version of Python's fileobject.c:file_read(). */
static PyObject *
BZ2File_read(BZ2FileObject *self, PyObject *args)
{
	long bytesrequested = -1;
	size_t bytesread, buffersize, chunksize;
	int bzerror;
	PyObject *ret = NULL;
409

410 411
	if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
		return NULL;
412

413 414 415 416 417
	ACQUIRE_LOCK(self);
	switch (self->mode) {
		case MODE_READ:
			break;
		case MODE_READ_EOF:
418
			ret = PyBytes_FromStringAndSize("", 0);
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
			goto cleanup;
		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
			goto cleanup;
		default:
			PyErr_SetString(PyExc_IOError,
					"file is not ready for reading");
			goto cleanup;
	}

	if (bytesrequested < 0)
		buffersize = Util_NewBufferSize((size_t)0);
	else
		buffersize = bytesrequested;
	if (buffersize > INT_MAX) {
		PyErr_SetString(PyExc_OverflowError,
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
436 437
				"requested number of bytes is "
				"more than a Python string can hold");
438 439
		goto cleanup;
	}
440
	ret = PyBytes_FromStringAndSize((char *)NULL, buffersize);
441
	if (ret == NULL || buffersize == 0)
442 443 444 445 446
		goto cleanup;
	bytesread = 0;

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
447 448 449
		chunksize = BZ2_bzRead(&bzerror, self->fp,
				       BUF(ret)+bytesread,
				       buffersize-bytesread);
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
		self->pos += chunksize;
		Py_END_ALLOW_THREADS
		bytesread += chunksize;
		if (bzerror == BZ_STREAM_END) {
			self->size = self->pos;
			self->mode = MODE_READ_EOF;
			break;
		} else if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			Py_DECREF(ret);
			ret = NULL;
			goto cleanup;
		}
		if (bytesrequested < 0) {
			buffersize = Util_NewBufferSize(buffersize);
465
			if (_PyBytes_Resize(&ret, buffersize) < 0) {
466
				ret = NULL;
467
				goto cleanup;
468
			}
469 470 471 472
		} else {
			break;
		}
	}
473
	if (bytesread != buffersize) {
474
		if (_PyBytes_Resize(&ret, bytesread) < 0) {
475 476 477
			ret = NULL;
		}
	}
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

cleanup:
	RELEASE_LOCK(self);
	return ret;
}

PyDoc_STRVAR(BZ2File_readline__doc__,
"readline([size]) -> string\n\
\n\
Return the next line from the file, as a string, retaining newline.\n\
A non-negative size argument will limit the maximum number of bytes to\n\
return (an incomplete line may be returned then). Return an empty\n\
string at EOF.\n\
");

static PyObject *
BZ2File_readline(BZ2FileObject *self, PyObject *args)
{
	PyObject *ret = NULL;
	int sizehint = -1;

	if (!PyArg_ParseTuple(args, "|i:readline", &sizehint))
		return NULL;

	ACQUIRE_LOCK(self);
	switch (self->mode) {
		case MODE_READ:
			break;
		case MODE_READ_EOF:
507
			ret = PyBytes_FromStringAndSize("", 0);
508 509 510 511 512 513 514 515 516 517 518 519
			goto cleanup;
		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
			goto cleanup;
		default:
			PyErr_SetString(PyExc_IOError,
					"file is not ready for reading");
			goto cleanup;
	}

	if (sizehint == 0)
520
		ret = PyBytes_FromStringAndSize("", 0);
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
	else
		ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);

cleanup:
	RELEASE_LOCK(self);
	return ret;
}

PyDoc_STRVAR(BZ2File_readlines__doc__,
"readlines([size]) -> list\n\
\n\
Call readline() repeatedly and return a list of lines read.\n\
The optional size argument, if given, is an approximate bound on the\n\
total number of bytes in the lines returned.\n\
");

/* This is a hacked version of Python's fileobject.c:file_readlines(). */
static PyObject *
BZ2File_readlines(BZ2FileObject *self, PyObject *args)
{
	long sizehint = 0;
	PyObject *list = NULL;
	PyObject *line;
	char small_buffer[SMALLCHUNK];
	char *buffer = small_buffer;
	size_t buffersize = SMALLCHUNK;
	PyObject *big_buffer = NULL;
	size_t nfilled = 0;
	size_t nread;
	size_t totalread = 0;
	char *p, *q, *end;
	int err;
	int shortread = 0;
	int bzerror;

	if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
		return NULL;

	ACQUIRE_LOCK(self);
	switch (self->mode) {
		case MODE_READ:
			break;
		case MODE_READ_EOF:
			list = PyList_New(0);
			goto cleanup;
		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
			goto cleanup;
		default:
			PyErr_SetString(PyExc_IOError,
					"file is not ready for reading");
			goto cleanup;
	}

	if ((list = PyList_New(0)) == NULL)
		goto cleanup;

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
581 582
		nread = BZ2_bzRead(&bzerror, self->fp,
				   buffer+nfilled, buffersize-nfilled);
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
		self->pos += nread;
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
			self->size = self->pos;
			self->mode = MODE_READ_EOF;
			if (nread == 0) {
				sizehint = 0;
				break;
			}
			shortread = 1;
		} else if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
		  error:
			Py_DECREF(list);
			list = NULL;
			goto cleanup;
		}
		totalread += nread;
		p = memchr(buffer+nfilled, '\n', nread);
602
		if (!shortread && p == NULL) {
603 604 605 606 607
			/* Need a larger buffer to fit this line */
			nfilled += nread;
			buffersize *= 2;
			if (buffersize > INT_MAX) {
				PyErr_SetString(PyExc_OverflowError,
608
				"line is longer than a Python string can hold");
609 610 611 612
				goto error;
			}
			if (big_buffer == NULL) {
				/* Create the big buffer */
613
				big_buffer = PyBytes_FromStringAndSize(
614 615 616
					NULL, buffersize);
				if (big_buffer == NULL)
					goto error;
617
				buffer = PyBytes_AS_STRING(big_buffer);
618 619 620 621
				memcpy(buffer, small_buffer, nfilled);
			}
			else {
				/* Grow the big buffer */
622
				if (_PyBytes_Resize(&big_buffer, buffersize) < 0){
623 624 625
					big_buffer = NULL;
					goto error;
				}
626
				buffer = PyBytes_AS_STRING(big_buffer);
627
			}
628
			continue;
629 630 631
		}
		end = buffer+nfilled+nread;
		q = buffer;
632
		while (p != NULL) {
633 634
			/* Process complete lines */
			p++;
635
			line = PyBytes_FromStringAndSize(q, p-q);
636 637 638 639 640 641 642 643
			if (line == NULL)
				goto error;
			err = PyList_Append(list, line);
			Py_DECREF(line);
			if (err != 0)
				goto error;
			q = p;
			p = memchr(q, '\n', end-q);
644
		}
645 646 647 648 649 650 651 652 653 654 655 656 657
		/* Move the remaining incomplete line to the start */
		nfilled = end-q;
		memmove(buffer, q, nfilled);
		if (sizehint > 0)
			if (totalread >= (size_t)sizehint)
				break;
		if (shortread) {
			sizehint = 0;
			break;
		}
	}
	if (nfilled != 0) {
		/* Partial last line */
658
		line = PyBytes_FromStringAndSize(buffer, nfilled);
659 660 661 662 663 664 665 666 667
		if (line == NULL)
			goto error;
		if (sizehint > 0) {
			/* Need to complete the last line */
			PyObject *rest = Util_GetLine(self, 0);
			if (rest == NULL) {
				Py_DECREF(line);
				goto error;
			}
668
			PyBytes_Concat(&line, rest);
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
			Py_DECREF(rest);
			if (line == NULL)
				goto error;
		}
		err = PyList_Append(list, line);
		Py_DECREF(line);
		if (err != 0)
			goto error;
	}

  cleanup:
	RELEASE_LOCK(self);
	if (big_buffer) {
		Py_DECREF(big_buffer);
	}
	return list;
}

PyDoc_STRVAR(BZ2File_write__doc__,
"write(data) -> None\n\
\n\
Write the 'data' string to file. Note that due to buffering, close() may\n\
be needed before the file on disk reflects the data written.\n\
");

/* This is a hacked version of Python's fileobject.c:file_write(). */
static PyObject *
BZ2File_write(BZ2FileObject *self, PyObject *args)
{
	PyObject *ret = NULL;
699
	Py_buffer pbuf;
700 701 702 703
	char *buf;
	int len;
	int bzerror;

704
	if (!PyArg_ParseTuple(args, "y*:write", &pbuf))
705
		return NULL;
706 707
	buf = pbuf.buf;
	len = pbuf.len;
708

709 710 711 712
	ACQUIRE_LOCK(self);
	switch (self->mode) {
		case MODE_WRITE:
			break;
713

714 715 716
		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
717
			goto cleanup;
718

719 720 721
		default:
			PyErr_SetString(PyExc_IOError,
					"file is not ready for writing");
722
			goto cleanup;
723 724 725 726 727 728
	}

	Py_BEGIN_ALLOW_THREADS
	BZ2_bzWrite (&bzerror, self->fp, buf, len);
	self->pos += len;
	Py_END_ALLOW_THREADS
729

730 731 732 733
	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
		goto cleanup;
	}
734

735 736 737 738
	Py_INCREF(Py_None);
	ret = Py_None;

cleanup:
739
	PyBuffer_Release(&pbuf);
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	RELEASE_LOCK(self);
	return ret;
}

PyDoc_STRVAR(BZ2File_writelines__doc__,
"writelines(sequence_of_strings) -> None\n\
\n\
Write the sequence of strings to the file. Note that newlines are not\n\
added. The sequence can be any iterable object producing strings. This is\n\
equivalent to calling write() for each string.\n\
");

/* This is a hacked version of Python's fileobject.c:file_writelines(). */
static PyObject *
BZ2File_writelines(BZ2FileObject *self, PyObject *seq)
{
#define CHUNKSIZE 1000
	PyObject *list = NULL;
	PyObject *iter = NULL;
	PyObject *ret = NULL;
	PyObject *line;
	int i, j, index, len, islist;
	int bzerror;

	ACQUIRE_LOCK(self);
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
	switch (self->mode) {
		case MODE_WRITE:
			break;

		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
			goto error;

		default:
			PyErr_SetString(PyExc_IOError,
					"file is not ready for writing");
			goto error;
	}

780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
	islist = PyList_Check(seq);
	if  (!islist) {
		iter = PyObject_GetIter(seq);
		if (iter == NULL) {
			PyErr_SetString(PyExc_TypeError,
				"writelines() requires an iterable argument");
			goto error;
		}
		list = PyList_New(CHUNKSIZE);
		if (list == NULL)
			goto error;
	}

	/* Strategy: slurp CHUNKSIZE lines into a private list,
	   checking that they are all strings, then write that list
	   without holding the interpreter lock, then come back for more. */
	for (index = 0; ; index += CHUNKSIZE) {
		if (islist) {
			Py_XDECREF(list);
			list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
			if (list == NULL)
				goto error;
			j = PyList_GET_SIZE(list);
		}
		else {
			for (j = 0; j < CHUNKSIZE; j++) {
				line = PyIter_Next(iter);
				if (line == NULL) {
					if (PyErr_Occurred())
						goto error;
					break;
				}
				PyList_SetItem(list, j, line);
			}
		}
		if (j == 0)
			break;

818
		/* Check that all entries are indeed byte strings. If not,
819 820 821 822 823 824
		   apply the same rules as for file.write() and
		   convert the rets to strings. This is slow, but
		   seems to be the only way since all conversion APIs
		   could potentially execute Python code. */
		for (i = 0; i < j; i++) {
			PyObject *v = PyList_GET_ITEM(list, i);
825
			if (!PyBytes_Check(v)) {
826
			    	const char *buffer;
Martin v. Löwis's avatar
Martin v. Löwis committed
827
			    	Py_ssize_t len;
828 829 830 831 832
				if (PyObject_AsCharBuffer(v, &buffer, &len)) {
					PyErr_SetString(PyExc_TypeError,
							"writelines() "
							"argument must be "
							"a sequence of "
833
							"bytes objects");
834 835
					goto error;
				}
836
				line = PyBytes_FromStringAndSize(buffer,
837 838 839 840 841 842 843 844 845 846 847 848 849
								  len);
				if (line == NULL)
					goto error;
				Py_DECREF(v);
				PyList_SET_ITEM(list, i, line);
			}
		}

		/* Since we are releasing the global lock, the
		   following code may *not* execute Python code. */
		Py_BEGIN_ALLOW_THREADS
		for (i = 0; i < j; i++) {
		    	line = PyList_GET_ITEM(list, i);
850
			len = PyBytes_GET_SIZE(line);
851
			BZ2_bzWrite (&bzerror, self->fp,
852
				     PyBytes_AS_STRING(line), len);
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
			if (bzerror != BZ_OK) {
				Py_BLOCK_THREADS
				Util_CatchBZ2Error(bzerror);
				goto error;
			}
		}
		Py_END_ALLOW_THREADS

		if (j < CHUNKSIZE)
			break;
	}

	Py_INCREF(Py_None);
	ret = Py_None;

  error:
	RELEASE_LOCK(self);
	Py_XDECREF(list);
  	Py_XDECREF(iter);
	return ret;
#undef CHUNKSIZE
}

PyDoc_STRVAR(BZ2File_seek__doc__,
"seek(offset [, whence]) -> None\n\
\n\
Move to new file position. Argument offset is a byte count. Optional\n\
argument whence defaults to 0 (offset from start of file, offset\n\
should be >= 0); other values are 1 (move relative to current position,\n\
positive or negative), and 2 (move relative to end of file, usually\n\
negative, although many platforms allow seeking beyond the end of a file).\n\
\n\
Note that seeking of bz2 files is emulated, and depending on the parameters\n\
the operation may be extremely slow.\n\
");

static PyObject *
BZ2File_seek(BZ2FileObject *self, PyObject *args)
{
	int where = 0;
893 894
	PyObject *offobj;
	Py_off_t offset;
895 896 897
	char small_buffer[SMALLCHUNK];
	char *buffer = small_buffer;
	size_t buffersize = SMALLCHUNK;
898
	Py_off_t bytesread = 0;
899
	size_t readsize;
900 901 902
	int chunksize;
	int bzerror;
	PyObject *ret = NULL;
903

904 905 906
	if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where))
		return NULL;
#if !defined(HAVE_LARGEFILE_SUPPORT)
907
	offset = PyLong_AsLong(offobj);
908 909
#else
	offset = PyLong_Check(offobj) ?
910
		PyLong_AsLongLong(offobj) : PyLong_AsLong(offobj);
911 912
#endif
	if (PyErr_Occurred())
913 914 915 916 917 918 919 920
		return NULL;

	ACQUIRE_LOCK(self);
	Util_DropReadAhead(self);
	switch (self->mode) {
		case MODE_READ:
		case MODE_READ_EOF:
			break;
921

922 923 924
		case MODE_CLOSED:
			PyErr_SetString(PyExc_ValueError,
					"I/O operation on closed file");
925
			goto cleanup;
926

927 928 929
		default:
			PyErr_SetString(PyExc_IOError,
					"seek works only while reading");
930
			goto cleanup;
931 932
	}

933 934 935 936 937
	if (where == 2) {
		if (self->size == -1) {
			assert(self->mode != MODE_READ_EOF);
			for (;;) {
				Py_BEGIN_ALLOW_THREADS
938 939
				chunksize = BZ2_bzRead(&bzerror, self->fp,
						       buffer, buffersize);
940 941 942 943 944 945 946 947 948
				self->pos += chunksize;
				Py_END_ALLOW_THREADS

				bytesread += chunksize;
				if (bzerror == BZ_STREAM_END) {
					break;
				} else if (bzerror != BZ_OK) {
					Util_CatchBZ2Error(bzerror);
					goto cleanup;
949 950
				}
			}
951 952 953
			self->mode = MODE_READ_EOF;
			self->size = self->pos;
			bytesread = 0;
954
		}
955 956 957
		offset = self->size + offset;
	} else if (where == 1) {
		offset = self->pos + offset;
958 959
	}

960
	/* Before getting here, offset must be the absolute position the file
961 962 963 964 965 966 967
	 * pointer should be set to. */

	if (offset >= self->pos) {
		/* we can move forward */
		offset -= self->pos;
	} else {
		/* we cannot move back, so rewind the stream */
968 969 970 971 972
		BZ2_bzReadClose(&bzerror, self->fp);
		if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			goto cleanup;
		}
973
		rewind(self->rawfp);
974
		self->pos = 0;
975
		self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
976 977 978 979 980 981 982 983
					  0, 0, NULL, 0);
		if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			goto cleanup;
		}
		self->mode = MODE_READ;
	}

984
	if (offset <= 0 || self->mode == MODE_READ_EOF)
985 986 987 988 989
		goto exit;

	/* Before getting here, offset must be set to the number of bytes
	 * to walk forward. */
	for (;;) {
990
		if (offset-bytesread > buffersize)
991 992
			readsize = buffersize;
		else
993 994 995 996
			/* offset might be wider that readsize, but the result
			 * of the subtraction is bound by buffersize (see the
			 * condition above). buffersize is 8192. */
			readsize = (size_t)(offset-bytesread);
997
		Py_BEGIN_ALLOW_THREADS
998
		chunksize = BZ2_bzRead(&bzerror, self->fp, buffer, readsize);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
		self->pos += chunksize;
		Py_END_ALLOW_THREADS
		bytesread += chunksize;
		if (bzerror == BZ_STREAM_END) {
			self->size = self->pos;
			self->mode = MODE_READ_EOF;
			break;
		} else if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			goto cleanup;
		}
		if (bytesread == offset)
			break;
	}

exit:
	Py_INCREF(Py_None);
	ret = Py_None;

cleanup:
	RELEASE_LOCK(self);
	return ret;
}

PyDoc_STRVAR(BZ2File_tell__doc__,
"tell() -> int\n\
\n\
Return the current file position, an integer (may be a long integer).\n\
");

static PyObject *
BZ2File_tell(BZ2FileObject *self, PyObject *args)
{
	PyObject *ret = NULL;

	if (self->mode == MODE_CLOSED) {
		PyErr_SetString(PyExc_ValueError,
				"I/O operation on closed file");
		goto cleanup;
	}

1040
#if !defined(HAVE_LARGEFILE_SUPPORT)
1041
	ret = PyLong_FromLong(self->pos);
1042 1043 1044
#else
	ret = PyLong_FromLongLong(self->pos);
#endif
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

cleanup:
	return ret;
}

PyDoc_STRVAR(BZ2File_close__doc__,
"close() -> None or (perhaps) an integer\n\
\n\
Close the file. Sets data attribute .closed to true. A closed file\n\
cannot be used for further I/O operations. close() may be called more\n\
than once without error.\n\
");

static PyObject *
BZ2File_close(BZ2FileObject *self)
{
	PyObject *ret = NULL;
	int bzerror = BZ_OK;

1064 1065 1066 1067
	if (self->mode == MODE_CLOSED) {
		Py_RETURN_NONE;
	}

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
	ACQUIRE_LOCK(self);
	switch (self->mode) {
		case MODE_READ:
		case MODE_READ_EOF:
			BZ2_bzReadClose(&bzerror, self->fp);
			break;
		case MODE_WRITE:
			BZ2_bzWriteClose(&bzerror, self->fp,
					 0, NULL, NULL);
			break;
	}
	self->mode = MODE_CLOSED;
1080 1081 1082 1083 1084 1085 1086
	fclose(self->rawfp);
	self->rawfp = NULL;
	if (bzerror == BZ_OK) {
		Py_INCREF(Py_None);
		ret = Py_None;
	}
	else {
1087 1088 1089 1090 1091 1092 1093
		Util_CatchBZ2Error(bzerror);
	}

	RELEASE_LOCK(self);
	return ret;
}

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 1122 1123
PyDoc_STRVAR(BZ2File_enter_doc,
"__enter__() -> self.");

static PyObject *
BZ2File_enter(BZ2FileObject *self)
{
	if (self->mode == MODE_CLOSED) {
		PyErr_SetString(PyExc_ValueError,
			"I/O operation on closed file");
		return NULL;
	}
	Py_INCREF(self);
	return (PyObject *) self;
}

PyDoc_STRVAR(BZ2File_exit_doc,
"__exit__(*excinfo) -> None.  Closes the file.");

static PyObject *
BZ2File_exit(BZ2FileObject *self, PyObject *args)
{
	PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
	if (!ret)
		/* If error occurred, pass through */
		return NULL;
	Py_DECREF(ret);
	Py_RETURN_NONE;
}


1124 1125
static PyObject *BZ2File_getiter(BZ2FileObject *self);

1126 1127 1128 1129 1130 1131 1132 1133 1134
static PyMethodDef BZ2File_methods[] = {
	{"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__},
	{"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__},
	{"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__},
	{"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__},
	{"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__},
	{"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
	{"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
	{"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
1135 1136
	{"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
	{"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
1137 1138 1139 1140
	{NULL,		NULL}		/* sentinel */
};


1141 1142 1143 1144 1145 1146
/* ===================================================================== */
/* Getters and setters of BZ2File. */

static PyObject *
BZ2File_get_closed(BZ2FileObject *self, void *closure)
{
1147
	return PyLong_FromLong(self->mode == MODE_CLOSED);
1148 1149 1150 1151 1152 1153 1154 1155 1156
}

static PyGetSetDef BZ2File_getset[] = {
	{"closed", (getter)BZ2File_get_closed, NULL,
			"True if the file is closed"},
	{NULL}	/* Sentinel */
};


1157 1158 1159 1160 1161 1162
/* ===================================================================== */
/* Slot definitions for BZ2File_Type. */

static int
BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs)
{
1163
	static char *kwlist[] = {"filename", "mode", "buffering",
1164 1165
				 "compresslevel", 0};
	char *name;
1166 1167 1168 1169 1170 1171 1172
	char *mode = "r";
	int buffering = -1;
	int compresslevel = 9;
	int bzerror;
	int mode_char = 0;

	self->size = -1;
1173

1174
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|sii:BZ2File",
1175
					 kwlist, &name, &mode, &buffering,
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
					 &compresslevel))
		return -1;

	if (compresslevel < 1 || compresslevel > 9) {
		PyErr_SetString(PyExc_ValueError,
				"compresslevel must be between 1 and 9");
		return -1;
	}

	for (;;) {
		int error = 0;
		switch (*mode) {
			case 'r':
			case 'w':
				if (mode_char)
					error = 1;
				mode_char = *mode;
				break;

			case 'b':
				break;

			default:
				error = 1;
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1200
				break;
1201 1202
		}
		if (error) {
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1203 1204
			PyErr_Format(PyExc_ValueError,
				     "invalid mode char %c", *mode);
1205 1206 1207
			return -1;
		}
		mode++;
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1208
		if (*mode == '\0')
1209 1210 1211
			break;
	}

1212 1213 1214 1215
	if (mode_char == 0) {
		mode_char = 'r';
	}

1216
	mode = (mode_char == 'r') ? "rb" : "wb";
1217

1218 1219 1220
	self->rawfp = fopen(name, mode);
	if (self->rawfp == NULL) {
		PyErr_SetFromErrno(PyExc_IOError);
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1221
		return -1;
1222 1223
	}
	/* XXX Ignore buffering */
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1224 1225 1226

	/* From now on, we have stuff to dealloc, so jump to error label
	 * instead of returning */
1227 1228 1229

#ifdef WITH_THREAD
	self->lock = PyThread_allocate_lock();
1230 1231
	if (!self->lock) {
		PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
1232
		goto error;
1233
	}
1234 1235 1236
#endif

	if (mode_char == 'r')
1237
		self->fp = BZ2_bzReadOpen(&bzerror, self->rawfp,
1238 1239
					  0, 0, NULL, 0);
	else
1240
		self->fp = BZ2_bzWriteOpen(&bzerror, self->rawfp,
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
					   compresslevel, 0, 0);

	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
		goto error;
	}

	self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;

	return 0;

error:
1253 1254
	fclose(self->rawfp);
	self->rawfp = NULL;
1255
#ifdef WITH_THREAD
1256
	if (self->lock) {
1257
		PyThread_free_lock(self->lock);
1258 1259
		self->lock = NULL;
	}
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
#endif
	return -1;
}

static void
BZ2File_dealloc(BZ2FileObject *self)
{
	int bzerror;
#ifdef WITH_THREAD
	if (self->lock)
		PyThread_free_lock(self->lock);
#endif
	switch (self->mode) {
		case MODE_READ:
		case MODE_READ_EOF:
			BZ2_bzReadClose(&bzerror, self->fp);
			break;
		case MODE_WRITE:
			BZ2_bzWriteClose(&bzerror, self->fp,
					 0, NULL, NULL);
			break;
	}
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1282
	Util_DropReadAhead(self);
1283 1284
	if (self->rawfp != NULL)
		fclose(self->rawfp);
1285
	Py_TYPE(self)->tp_free((PyObject *)self);
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
}

/* This is a hacked version of Python's fileobject.c:file_getiter(). */
static PyObject *
BZ2File_getiter(BZ2FileObject *self)
{
	if (self->mode == MODE_CLOSED) {
		PyErr_SetString(PyExc_ValueError,
				"I/O operation on closed file");
		return NULL;
	}
	Py_INCREF((PyObject*)self);
	return (PyObject *)self;
}

/* This is a hacked version of Python's fileobject.c:file_iternext(). */
#define READAHEAD_BUFSIZE 8192
static PyObject *
BZ2File_iternext(BZ2FileObject *self)
{
1306
	PyBytesObject* ret;
1307 1308
	ACQUIRE_LOCK(self);
	if (self->mode == MODE_CLOSED) {
Georg Brandl's avatar
Georg Brandl committed
1309
                RELEASE_LOCK(self);
1310 1311 1312 1313 1314 1315
		PyErr_SetString(PyExc_ValueError,
				"I/O operation on closed file");
		return NULL;
	}
	ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
	RELEASE_LOCK(self);
1316
	if (ret == NULL || PyBytes_GET_SIZE(ret) == 0) {
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
		Py_XDECREF(ret);
		return NULL;
	}
	return (PyObject *)ret;
}

/* ===================================================================== */
/* BZ2File_Type definition. */

PyDoc_VAR(BZ2File__doc__) =
PyDoc_STR(
"BZ2File(name [, mode='r', buffering=0, compresslevel=9]) -> file object\n\
\n\
Open a bz2 file. The mode can be 'r' or 'w', for reading (default) or\n\
writing. When opened for writing, the file will be created if it doesn't\n\
exist, and truncated otherwise. If the buffering argument is given, 0 means\n\
unbuffered, and larger numbers specify the buffer size. If compresslevel\n\
is given, must be a number between 1 and 9.\n\
1335 1336
Data read is always returned in bytes; data written ought to be bytes.\n\
");
1337

Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1338
static PyTypeObject BZ2File_Type = {
1339
	PyVarObject_HEAD_INIT(NULL, 0)
1340 1341 1342 1343 1344 1345 1346
	"bz2.BZ2File",		/*tp_name*/
	sizeof(BZ2FileObject),	/*tp_basicsize*/
	0,			/*tp_itemsize*/
	(destructor)BZ2File_dealloc, /*tp_dealloc*/
	0,			/*tp_print*/
	0,			/*tp_getattr*/
	0,			/*tp_setattr*/
1347
	0,			/*tp_reserved*/
1348 1349 1350 1351 1352 1353 1354
	0,			/*tp_repr*/
	0,			/*tp_as_number*/
	0,			/*tp_as_sequence*/
	0,			/*tp_as_mapping*/
	0,			/*tp_hash*/
        0,                      /*tp_call*/
        0,                      /*tp_str*/
1355 1356
        PyObject_GenericGetAttr,/*tp_getattro*/
        PyObject_GenericSetAttr,/*tp_setattro*/
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        0,                      /*tp_as_buffer*/
        Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
        BZ2File__doc__,         /*tp_doc*/
        0,                      /*tp_traverse*/
        0,                      /*tp_clear*/
        0,                      /*tp_richcompare*/
        0,                      /*tp_weaklistoffset*/
        (getiterfunc)BZ2File_getiter, /*tp_iter*/
        (iternextfunc)BZ2File_iternext, /*tp_iternext*/
        BZ2File_methods,        /*tp_methods*/
1367
        0,		        /*tp_members*/
1368
        BZ2File_getset,         /*tp_getset*/
1369 1370 1371 1372 1373 1374
        0,                      /*tp_base*/
        0,                      /*tp_dict*/
        0,                      /*tp_descr_get*/
        0,                      /*tp_descr_set*/
        0,                      /*tp_dictoffset*/
        (initproc)BZ2File_init, /*tp_init*/
1375
        PyType_GenericAlloc,    /*tp_alloc*/
1376
        PyType_GenericNew,      /*tp_new*/
Neal Norwitz's avatar
Neal Norwitz committed
1377
      	PyObject_Free,          /*tp_free*/
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        0,                      /*tp_is_gc*/
};


/* ===================================================================== */
/* Methods of BZ2Comp. */

PyDoc_STRVAR(BZ2Comp_compress__doc__,
"compress(data) -> string\n\
\n\
Provide more data to the compressor object. It will return chunks of\n\
compressed data whenever possible. When you've finished providing data\n\
to compress, call the flush() method to finish the compression process,\n\
and return what is left in the internal buffers.\n\
");

static PyObject *
BZ2Comp_compress(BZ2CompObject *self, PyObject *args)
{
1397
	Py_buffer pdata;
1398 1399 1400
	char *data;
	int datasize;
	int bufsize = SMALLCHUNK;
1401
	PY_LONG_LONG totalout;
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1402
	PyObject *ret = NULL;
1403 1404 1405
	bz_stream *bzs = &self->bzs;
	int bzerror;

1406
	if (!PyArg_ParseTuple(args, "y*:compress", &pdata))
1407
		return NULL;
1408 1409
	data = pdata.buf;
	datasize = pdata.len;
1410

1411 1412
	if (datasize == 0) {
		PyBuffer_Release(&pdata);
1413
		return PyBytes_FromStringAndSize("", 0);
1414
	}
1415

1416 1417
	ACQUIRE_LOCK(self);
	if (!self->running) {
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1418 1419
		PyErr_SetString(PyExc_ValueError,
				"this object was already flushed");
1420 1421 1422
		goto error;
	}

1423
	ret = PyBytes_FromStringAndSize(NULL, bufsize);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
	if (!ret)
		goto error;

	bzs->next_in = data;
	bzs->avail_in = datasize;
	bzs->next_out = BUF(ret);
	bzs->avail_out = bufsize;

	totalout = BZS_TOTAL_OUT(bzs);

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
		bzerror = BZ2_bzCompress(bzs, BZ_RUN);
		Py_END_ALLOW_THREADS
		if (bzerror != BZ_RUN_OK) {
			Util_CatchBZ2Error(bzerror);
			goto error;
		}
1442 1443
		if (bzs->avail_in == 0)
			break; /* no more input data */
1444 1445
		if (bzs->avail_out == 0) {
			bufsize = Util_NewBufferSize(bufsize);
1446
			if (_PyBytes_Resize(&ret, bufsize) < 0) {
1447 1448 1449 1450 1451 1452 1453 1454 1455
				BZ2_bzCompressEnd(bzs);
				goto error;
			}
			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
						    - totalout);
			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
		}
	}

1456
	if (_PyBytes_Resize(&ret,
1457 1458
			   (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
		goto error;
1459 1460

	RELEASE_LOCK(self);
1461
	PyBuffer_Release(&pdata);
1462 1463 1464 1465
	return ret;

error:
	RELEASE_LOCK(self);
1466
	PyBuffer_Release(&pdata);
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
	Py_XDECREF(ret);
	return NULL;
}

PyDoc_STRVAR(BZ2Comp_flush__doc__,
"flush() -> string\n\
\n\
Finish the compression process and return what is left in internal buffers.\n\
You must not use the compressor object after calling this method.\n\
");

static PyObject *
BZ2Comp_flush(BZ2CompObject *self)
{
	int bufsize = SMALLCHUNK;
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1482
	PyObject *ret = NULL;
1483
	bz_stream *bzs = &self->bzs;
1484
	PY_LONG_LONG totalout;
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
	int bzerror;

	ACQUIRE_LOCK(self);
	if (!self->running) {
		PyErr_SetString(PyExc_ValueError, "object was already "
						  "flushed");
		goto error;
	}
	self->running = 0;

1495
	ret = PyBytes_FromStringAndSize(NULL, bufsize);
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
	if (!ret)
		goto error;

	bzs->next_out = BUF(ret);
	bzs->avail_out = bufsize;

	totalout = BZS_TOTAL_OUT(bzs);

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
		bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
			break;
		} else if (bzerror != BZ_FINISH_OK) {
			Util_CatchBZ2Error(bzerror);
			goto error;
		}
		if (bzs->avail_out == 0) {
			bufsize = Util_NewBufferSize(bufsize);
1516
			if (_PyBytes_Resize(&ret, bufsize) < 0)
1517 1518 1519 1520 1521 1522 1523 1524
				goto error;
			bzs->next_out = BUF(ret);
			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
						    - totalout);
			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
		}
	}

1525
	if (bzs->avail_out != 0) {
1526
		if (_PyBytes_Resize(&ret,
1527 1528 1529
			    (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
			goto error;
	}
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540

	RELEASE_LOCK(self);
	return ret;

error:
	RELEASE_LOCK(self);
	Py_XDECREF(ret);
	return NULL;
}

static PyMethodDef BZ2Comp_methods[] = {
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1541 1542 1543 1544
	{"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS,
	 BZ2Comp_compress__doc__},
	{"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS,
	 BZ2Comp_flush__doc__},
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
	{NULL,		NULL}		/* sentinel */
};


/* ===================================================================== */
/* Slot definitions for BZ2Comp_Type. */

static int
BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs)
{
	int compresslevel = 9;
	int bzerror;
1557
	static char *kwlist[] = {"compresslevel", 0};
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor",
					 kwlist, &compresslevel))
		return -1;

	if (compresslevel < 1 || compresslevel > 9) {
		PyErr_SetString(PyExc_ValueError,
				"compresslevel must be between 1 and 9");
		goto error;
	}

#ifdef WITH_THREAD
	self->lock = PyThread_allocate_lock();
1571 1572
	if (!self->lock) {
		PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
1573
		goto error;
1574
	}
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
#endif

	memset(&self->bzs, 0, sizeof(bz_stream));
	bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
		goto error;
	}

	self->running = 1;

	return 0;
error:
#ifdef WITH_THREAD
1589
	if (self->lock) {
1590
		PyThread_free_lock(self->lock);
1591 1592
		self->lock = NULL;
	}
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
#endif
	return -1;
}

static void
BZ2Comp_dealloc(BZ2CompObject *self)
{
#ifdef WITH_THREAD
	if (self->lock)
		PyThread_free_lock(self->lock);
#endif
	BZ2_bzCompressEnd(&self->bzs);
1605
	Py_TYPE(self)->tp_free((PyObject *)self);
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
}


/* ===================================================================== */
/* BZ2Comp_Type definition. */

PyDoc_STRVAR(BZ2Comp__doc__,
"BZ2Compressor([compresslevel=9]) -> compressor object\n\
\n\
Create a new compressor object. This object may be used to compress\n\
data sequentially. If you want to compress data in one shot, use the\n\
compress() function instead. The compresslevel parameter, if given,\n\
must be a number between 1 and 9.\n\
");

Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1621
static PyTypeObject BZ2Comp_Type = {
1622
	PyVarObject_HEAD_INIT(NULL, 0)
1623 1624 1625 1626 1627 1628 1629
	"bz2.BZ2Compressor",	/*tp_name*/
	sizeof(BZ2CompObject),	/*tp_basicsize*/
	0,			/*tp_itemsize*/
	(destructor)BZ2Comp_dealloc, /*tp_dealloc*/
	0,			/*tp_print*/
	0,			/*tp_getattr*/
	0,			/*tp_setattr*/
1630
	0,			/*tp_reserved*/
1631 1632 1633 1634 1635 1636 1637
	0,			/*tp_repr*/
	0,			/*tp_as_number*/
	0,			/*tp_as_sequence*/
	0,			/*tp_as_mapping*/
	0,			/*tp_hash*/
        0,                      /*tp_call*/
        0,                      /*tp_str*/
1638 1639
        PyObject_GenericGetAttr,/*tp_getattro*/
        PyObject_GenericSetAttr,/*tp_setattro*/
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
        0,                      /*tp_as_buffer*/
        Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
        BZ2Comp__doc__,         /*tp_doc*/
        0,                      /*tp_traverse*/
        0,                      /*tp_clear*/
        0,                      /*tp_richcompare*/
        0,                      /*tp_weaklistoffset*/
        0,                      /*tp_iter*/
        0,                      /*tp_iternext*/
        BZ2Comp_methods,        /*tp_methods*/
        0,                      /*tp_members*/
        0,                      /*tp_getset*/
        0,                      /*tp_base*/
        0,                      /*tp_dict*/
        0,                      /*tp_descr_get*/
        0,                      /*tp_descr_set*/
        0,                      /*tp_dictoffset*/
        (initproc)BZ2Comp_init, /*tp_init*/
1658 1659
        PyType_GenericAlloc,    /*tp_alloc*/
        PyType_GenericNew,      /*tp_new*/
Neal Norwitz's avatar
Neal Norwitz committed
1660
      	PyObject_Free,          /*tp_free*/
1661 1662 1663 1664 1665 1666 1667
        0,                      /*tp_is_gc*/
};


/* ===================================================================== */
/* Members of BZ2Decomp. */

1668
#undef OFF
1669 1670 1671
#define OFF(x) offsetof(BZ2DecompObject, x)

static PyMemberDef BZ2Decomp_members[] = {
1672
	{"unused_data", T_OBJECT, OFF(unused_data), READONLY},
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
	{NULL}	/* Sentinel */
};


/* ===================================================================== */
/* Methods of BZ2Decomp. */

PyDoc_STRVAR(BZ2Decomp_decompress__doc__,
"decompress(data) -> string\n\
\n\
Provide more data to the decompressor object. It will return chunks\n\
of decompressed data whenever possible. If you try to decompress data\n\
after the end of stream is found, EOFError will be raised. If any data\n\
was found after the end of stream, it'll be ignored and saved in\n\
unused_data attribute.\n\
");

static PyObject *
BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args)
{
1693
	Py_buffer pdata;
1694 1695 1696
	char *data;
	int datasize;
	int bufsize = SMALLCHUNK;
1697
	PY_LONG_LONG totalout;
1698
	PyObject *ret = NULL;
1699 1700 1701
	bz_stream *bzs = &self->bzs;
	int bzerror;

1702
	if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
1703
		return NULL;
1704 1705
	data = pdata.buf;
	datasize = pdata.len;
1706 1707 1708 1709 1710 1711 1712 1713

	ACQUIRE_LOCK(self);
	if (!self->running) {
		PyErr_SetString(PyExc_EOFError, "end of stream was "
						"already found");
		goto error;
	}

1714
	ret = PyBytes_FromStringAndSize(NULL, bufsize);
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
	if (!ret)
		goto error;

	bzs->next_in = data;
	bzs->avail_in = datasize;
	bzs->next_out = BUF(ret);
	bzs->avail_out = bufsize;

	totalout = BZS_TOTAL_OUT(bzs);

	for (;;) {
		Py_BEGIN_ALLOW_THREADS
		bzerror = BZ2_bzDecompress(bzs);
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
			if (bzs->avail_in != 0) {
				Py_DECREF(self->unused_data);
				self->unused_data =
1733
				    PyBytes_FromStringAndSize(bzs->next_in,
1734 1735 1736 1737 1738 1739 1740 1741 1742
							       bzs->avail_in);
			}
			self->running = 0;
			break;
		}
		if (bzerror != BZ_OK) {
			Util_CatchBZ2Error(bzerror);
			goto error;
		}
1743 1744
		if (bzs->avail_in == 0)
			break; /* no more input data */
1745 1746
		if (bzs->avail_out == 0) {
			bufsize = Util_NewBufferSize(bufsize);
1747
			if (_PyBytes_Resize(&ret, bufsize) < 0) {
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
				BZ2_bzDecompressEnd(bzs);
				goto error;
			}
			bzs->next_out = BUF(ret);
			bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
						    - totalout);
			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
		}
	}

1758
	if (bzs->avail_out != 0) {
1759
		if (_PyBytes_Resize(&ret,
1760 1761 1762
			    (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
			goto error;
	}
1763 1764

	RELEASE_LOCK(self);
1765
	PyBuffer_Release(&pdata);
1766 1767 1768 1769
	return ret;

error:
	RELEASE_LOCK(self);
1770
	PyBuffer_Release(&pdata);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
	Py_XDECREF(ret);
	return NULL;
}

static PyMethodDef BZ2Decomp_methods[] = {
	{"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__},
	{NULL,		NULL}		/* sentinel */
};


/* ===================================================================== */
/* Slot definitions for BZ2Decomp_Type. */

static int
BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs)
{
	int bzerror;

	if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
		return -1;

#ifdef WITH_THREAD
	self->lock = PyThread_allocate_lock();
1794 1795
	if (!self->lock) {
		PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
1796
		goto error;
1797
	}
1798 1799
#endif

1800
	self->unused_data = PyBytes_FromStringAndSize("", 0);
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
	if (!self->unused_data)
		goto error;

	memset(&self->bzs, 0, sizeof(bz_stream));
	bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
		goto error;
	}

	self->running = 1;

	return 0;

error:
#ifdef WITH_THREAD
1817
	if (self->lock) {
1818
		PyThread_free_lock(self->lock);
1819 1820
		self->lock = NULL;
	}
1821
#endif
1822
	Py_CLEAR(self->unused_data);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
	return -1;
}

static void
BZ2Decomp_dealloc(BZ2DecompObject *self)
{
#ifdef WITH_THREAD
	if (self->lock)
		PyThread_free_lock(self->lock);
#endif
	Py_XDECREF(self->unused_data);
	BZ2_bzDecompressEnd(&self->bzs);
1835
	Py_TYPE(self)->tp_free((PyObject *)self);
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
}


/* ===================================================================== */
/* BZ2Decomp_Type definition. */

PyDoc_STRVAR(BZ2Decomp__doc__,
"BZ2Decompressor() -> decompressor object\n\
\n\
Create a new decompressor object. This object may be used to decompress\n\
data sequentially. If you want to decompress data in one shot, use the\n\
decompress() function instead.\n\
");

Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1850
static PyTypeObject BZ2Decomp_Type = {
1851
	PyVarObject_HEAD_INIT(NULL, 0)
1852 1853 1854 1855 1856 1857 1858
	"bz2.BZ2Decompressor",	/*tp_name*/
	sizeof(BZ2DecompObject), /*tp_basicsize*/
	0,			/*tp_itemsize*/
	(destructor)BZ2Decomp_dealloc, /*tp_dealloc*/
	0,			/*tp_print*/
	0,			/*tp_getattr*/
	0,			/*tp_setattr*/
1859
	0,			/*tp_reserved*/
1860 1861 1862 1863 1864 1865 1866
	0,			/*tp_repr*/
	0,			/*tp_as_number*/
	0,			/*tp_as_sequence*/
	0,			/*tp_as_mapping*/
	0,			/*tp_hash*/
        0,                      /*tp_call*/
        0,                      /*tp_str*/
1867 1868
        PyObject_GenericGetAttr,/*tp_getattro*/
        PyObject_GenericSetAttr,/*tp_setattro*/
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
        0,                      /*tp_as_buffer*/
        Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
        BZ2Decomp__doc__,       /*tp_doc*/
        0,                      /*tp_traverse*/
        0,                      /*tp_clear*/
        0,                      /*tp_richcompare*/
        0,                      /*tp_weaklistoffset*/
        0,                      /*tp_iter*/
        0,                      /*tp_iternext*/
        BZ2Decomp_methods,      /*tp_methods*/
        BZ2Decomp_members,      /*tp_members*/
        0,                      /*tp_getset*/
        0,                      /*tp_base*/
        0,                      /*tp_dict*/
        0,                      /*tp_descr_get*/
        0,                      /*tp_descr_set*/
        0,                      /*tp_dictoffset*/
        (initproc)BZ2Decomp_init, /*tp_init*/
1887 1888
        PyType_GenericAlloc,    /*tp_alloc*/
        PyType_GenericNew,      /*tp_new*/
Neal Norwitz's avatar
Neal Norwitz committed
1889
      	PyObject_Free,          /*tp_free*/
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
        0,                      /*tp_is_gc*/
};


/* ===================================================================== */
/* Module functions. */

PyDoc_STRVAR(bz2_compress__doc__,
"compress(data [, compresslevel=9]) -> string\n\
\n\
Compress data in one shot. If you want to compress data sequentially,\n\
use an instance of BZ2Compressor instead. The compresslevel parameter, if\n\
given, must be a number between 1 and 9.\n\
");

static PyObject *
bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
	int compresslevel=9;
1909
	Py_buffer pdata;
1910 1911 1912
	char *data;
	int datasize;
	int bufsize;
Gustavo Niemeyer's avatar
Gustavo Niemeyer committed
1913
	PyObject *ret = NULL;
1914 1915 1916
	bz_stream _bzs;
	bz_stream *bzs = &_bzs;
	int bzerror;
1917
	static char *kwlist[] = {"data", "compresslevel", 0};
1918

1919 1920
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|i",
					 kwlist, &pdata,
1921 1922
					 &compresslevel))
		return NULL;
1923 1924
	data = pdata.buf;
	datasize = pdata.len;
1925 1926 1927 1928

	if (compresslevel < 1 || compresslevel > 9) {
		PyErr_SetString(PyExc_ValueError,
				"compresslevel must be between 1 and 9");
1929
		PyBuffer_Release(&pdata);
1930 1931 1932 1933 1934 1935 1936
		return NULL;
	}

	/* Conforming to bz2 manual, this is large enough to fit compressed
	 * data in one shot. We will check it later anyway. */
	bufsize = datasize + (datasize/100+1) + 600;

1937
	ret = PyBytes_FromStringAndSize(NULL, bufsize);
1938 1939
	if (!ret) {
		PyBuffer_Release(&pdata);
1940
		return NULL;
1941
	}
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952

	memset(bzs, 0, sizeof(bz_stream));

	bzs->next_in = data;
	bzs->avail_in = datasize;
	bzs->next_out = BUF(ret);
	bzs->avail_out = bufsize;

	bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
1953
		PyBuffer_Release(&pdata);
1954 1955 1956
		Py_DECREF(ret);
		return NULL;
	}
1957

1958 1959 1960 1961 1962 1963 1964 1965 1966
	for (;;) {
		Py_BEGIN_ALLOW_THREADS
		bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
			break;
		} else if (bzerror != BZ_FINISH_OK) {
			BZ2_bzCompressEnd(bzs);
			Util_CatchBZ2Error(bzerror);
1967
			PyBuffer_Release(&pdata);
1968 1969 1970 1971 1972
			Py_DECREF(ret);
			return NULL;
		}
		if (bzs->avail_out == 0) {
			bufsize = Util_NewBufferSize(bufsize);
1973
			if (_PyBytes_Resize(&ret, bufsize) < 0) {
1974
				BZ2_bzCompressEnd(bzs);
1975
				PyBuffer_Release(&pdata);
1976 1977 1978 1979 1980 1981 1982
				return NULL;
			}
			bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
		}
	}

1983
	if (bzs->avail_out != 0) {
1984
		if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
1985 1986 1987
			ret = NULL;
		}
	}
1988 1989
	BZ2_bzCompressEnd(bzs);

1990
	PyBuffer_Release(&pdata);
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
	return ret;
}

PyDoc_STRVAR(bz2_decompress__doc__,
"decompress(data) -> decompressed data\n\
\n\
Decompress data in one shot. If you want to decompress data sequentially,\n\
use an instance of BZ2Decompressor instead.\n\
");

static PyObject *
bz2_decompress(PyObject *self, PyObject *args)
{
2004
	Py_buffer pdata;
2005 2006 2007 2008 2009 2010 2011 2012
	char *data;
	int datasize;
	int bufsize = SMALLCHUNK;
	PyObject *ret;
	bz_stream _bzs;
	bz_stream *bzs = &_bzs;
	int bzerror;

2013
	if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
2014
		return NULL;
2015 2016
	data = pdata.buf;
	datasize = pdata.len;
2017

2018 2019
	if (datasize == 0) {
		PyBuffer_Release(&pdata);
2020
		return PyBytes_FromStringAndSize("", 0);
2021
	}
2022

2023
	ret = PyBytes_FromStringAndSize(NULL, bufsize);
2024 2025
	if (!ret) {
		PyBuffer_Release(&pdata);
2026
		return NULL;
2027
	}
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039

	memset(bzs, 0, sizeof(bz_stream));

	bzs->next_in = data;
	bzs->avail_in = datasize;
	bzs->next_out = BUF(ret);
	bzs->avail_out = bufsize;

	bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
	if (bzerror != BZ_OK) {
		Util_CatchBZ2Error(bzerror);
		Py_DECREF(ret);
2040
		PyBuffer_Release(&pdata);
2041 2042
		return NULL;
	}
2043

2044 2045 2046 2047 2048 2049 2050 2051 2052
	for (;;) {
		Py_BEGIN_ALLOW_THREADS
		bzerror = BZ2_bzDecompress(bzs);
		Py_END_ALLOW_THREADS
		if (bzerror == BZ_STREAM_END) {
			break;
		} else if (bzerror != BZ_OK) {
			BZ2_bzDecompressEnd(bzs);
			Util_CatchBZ2Error(bzerror);
2053
			PyBuffer_Release(&pdata);
2054 2055 2056
			Py_DECREF(ret);
			return NULL;
		}
2057 2058 2059 2060
		if (bzs->avail_in == 0) {
			BZ2_bzDecompressEnd(bzs);
			PyErr_SetString(PyExc_ValueError,
					"couldn't find end of stream");
2061
			PyBuffer_Release(&pdata);
2062 2063 2064
			Py_DECREF(ret);
			return NULL;
		}
2065 2066
		if (bzs->avail_out == 0) {
			bufsize = Util_NewBufferSize(bufsize);
2067
			if (_PyBytes_Resize(&ret, bufsize) < 0) {
2068
				BZ2_bzDecompressEnd(bzs);
2069
				PyBuffer_Release(&pdata);
2070 2071 2072 2073 2074 2075 2076
				return NULL;
			}
			bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
			bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
		}
	}

2077
	if (bzs->avail_out != 0) {
2078
		if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
2079 2080 2081
			ret = NULL;
		}
	}
2082
	BZ2_bzDecompressEnd(bzs);
2083
	PyBuffer_Release(&pdata);
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105

	return ret;
}

static PyMethodDef bz2_methods[] = {
	{"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS,
		bz2_compress__doc__},
	{"decompress", (PyCFunction) bz2_decompress, METH_VARARGS,
		bz2_decompress__doc__},
	{NULL,		NULL}		/* sentinel */
};

/* ===================================================================== */
/* Initialization function. */

PyDoc_STRVAR(bz2__doc__,
"The python bz2 module provides a comprehensive interface for\n\
the bz2 compression library. It implements a complete file\n\
interface, one shot (de)compression functions, and types for\n\
sequential (de)compression.\n\
");

2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118

static struct PyModuleDef bz2module = {
	PyModuleDef_HEAD_INIT,
	"bz2",
	bz2__doc__,
	-1,
	bz2_methods,
	NULL,
	NULL,
	NULL,
	NULL
};

2119
PyMODINIT_FUNC
2120
PyInit_bz2(void)
2121 2122 2123
{
	PyObject *m;

2124 2125 2126
	Py_TYPE(&BZ2File_Type) = &PyType_Type;
	Py_TYPE(&BZ2Comp_Type) = &PyType_Type;
	Py_TYPE(&BZ2Decomp_Type) = &PyType_Type;
2127

2128
	m = PyModule_Create(&bz2module);
2129
	if (m == NULL)
2130
		return NULL;
2131

2132
	PyModule_AddObject(m, "__author__", PyUnicode_FromString(__author__));
2133 2134 2135 2136 2137 2138 2139 2140 2141

	Py_INCREF(&BZ2File_Type);
	PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);

	Py_INCREF(&BZ2Comp_Type);
	PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type);

	Py_INCREF(&BZ2Decomp_Type);
	PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
2142
	return m;
2143
}