blob: c3075073f0ed786cdfd8be4211e4bfa629e275f9 [file] [log] [blame]
Antoine Pitrou37dc5f82011-04-03 17:05:46 +02001"""Interface to the libbzip2 compression library.
2
3This module provides a file interface, classes for incremental
4(de)compression, and functions for one-shot (de)compression.
5"""
6
Nadeem Vawdaaf518c12012-06-04 23:32:38 +02007__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
8 "open", "compress", "decompress"]
Antoine Pitrou37dc5f82011-04-03 17:05:46 +02009
10__author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
11
Nadeem Vawdaaf518c12012-06-04 23:32:38 +020012import builtins
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020013import io
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020014import warnings
15
Nadeem Vawda72750a82012-01-18 01:57:14 +020016try:
17 from threading import RLock
18except ImportError:
19 from dummy_threading import RLock
20
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020021from _bz2 import BZ2Compressor, BZ2Decompressor
22
23
24_MODE_CLOSED = 0
25_MODE_READ = 1
26_MODE_READ_EOF = 2
27_MODE_WRITE = 3
28
29_BUFFER_SIZE = 8192
30
31
32class BZ2File(io.BufferedIOBase):
33
34 """A file object providing transparent bzip2 (de)compression.
35
36 A BZ2File can act as a wrapper for an existing file object, or refer
37 directly to a named file on disk.
38
39 Note that BZ2File provides a *binary* file interface - data read is
40 returned as bytes, and data to be written should be given as bytes.
41 """
42
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +020043 def __init__(self, filename, mode="r", buffering=None, compresslevel=9):
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020044 """Open a bzip2-compressed file.
45
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +020046 If filename is a str or bytes object, is gives the name of the file to
47 be opened. Otherwise, it should be a file object, which will be used to
48 read or write the compressed data.
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020049
Nadeem Vawda50cb9362012-06-04 23:31:22 +020050 mode can be 'r' for reading (default), 'w' for (over)writing, or 'a' for
51 appending. These can equivalently be given as 'rb', 'wb', and 'ab'.
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020052
53 buffering is ignored. Its use is deprecated.
54
Nadeem Vawdacac89092012-02-04 13:08:11 +020055 If mode is 'w' or 'a', compresslevel can be a number between 1
56 and 9 specifying the level of compression: 1 produces the least
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020057 compression, and 9 (default) produces the most compression.
Nadeem Vawdacac89092012-02-04 13:08:11 +020058
59 If mode is 'r', the input file may be the concatenation of
60 multiple compressed streams.
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020061 """
62 # This lock must be recursive, so that BufferedIOBase's
63 # readline(), readlines() and writelines() don't deadlock.
Nadeem Vawda72750a82012-01-18 01:57:14 +020064 self._lock = RLock()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020065 self._fp = None
66 self._closefp = False
67 self._mode = _MODE_CLOSED
68 self._pos = 0
69 self._size = -1
70
71 if buffering is not None:
72 warnings.warn("Use of 'buffering' argument is deprecated",
73 DeprecationWarning)
74
75 if not (1 <= compresslevel <= 9):
76 raise ValueError("compresslevel must be between 1 and 9")
77
78 if mode in ("", "r", "rb"):
79 mode = "rb"
80 mode_code = _MODE_READ
81 self._decompressor = BZ2Decompressor()
Nadeem Vawda6c573182012-09-30 03:57:33 +020082 self._buffer = b""
83 self._buffer_offset = 0
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020084 elif mode in ("w", "wb"):
85 mode = "wb"
86 mode_code = _MODE_WRITE
Nadeem Vawda249ab5e2011-09-11 22:38:11 +020087 self._compressor = BZ2Compressor(compresslevel)
Nadeem Vawda55b43382011-05-27 01:52:15 +020088 elif mode in ("a", "ab"):
89 mode = "ab"
90 mode_code = _MODE_WRITE
Nadeem Vawda249ab5e2011-09-11 22:38:11 +020091 self._compressor = BZ2Compressor(compresslevel)
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020092 else:
93 raise ValueError("Invalid mode: {!r}".format(mode))
94
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +020095 if isinstance(filename, (str, bytes)):
Nadeem Vawdaaf518c12012-06-04 23:32:38 +020096 self._fp = builtins.open(filename, mode)
Antoine Pitrou37dc5f82011-04-03 17:05:46 +020097 self._closefp = True
98 self._mode = mode_code
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +020099 elif hasattr(filename, "read") or hasattr(filename, "write"):
100 self._fp = filename
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200101 self._mode = mode_code
102 else:
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +0200103 raise TypeError("filename must be a str or bytes object, or a file")
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200104
105 def close(self):
106 """Flush and close the file.
107
108 May be called more than once without error. Once the file is
109 closed, any other operation on it will raise a ValueError.
110 """
111 with self._lock:
112 if self._mode == _MODE_CLOSED:
113 return
114 try:
115 if self._mode in (_MODE_READ, _MODE_READ_EOF):
116 self._decompressor = None
117 elif self._mode == _MODE_WRITE:
118 self._fp.write(self._compressor.flush())
119 self._compressor = None
120 finally:
Antoine Pitrou24ce3862011-04-03 17:08:49 +0200121 try:
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200122 if self._closefp:
123 self._fp.close()
124 finally:
125 self._fp = None
126 self._closefp = False
127 self._mode = _MODE_CLOSED
Nadeem Vawda6c573182012-09-30 03:57:33 +0200128 self._buffer = b""
129 self._buffer_offset = 0
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200130
131 @property
132 def closed(self):
133 """True if this file is closed."""
134 return self._mode == _MODE_CLOSED
135
136 def fileno(self):
137 """Return the file descriptor for the underlying file."""
Nadeem Vawda44ae4a22011-11-30 17:39:30 +0200138 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200139 return self._fp.fileno()
140
141 def seekable(self):
142 """Return whether the file supports seeking."""
Nadeem Vawdaae557d72012-02-12 01:51:38 +0200143 return self.readable() and self._fp.seekable()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200144
145 def readable(self):
146 """Return whether the file was opened for reading."""
Nadeem Vawda44ae4a22011-11-30 17:39:30 +0200147 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200148 return self._mode in (_MODE_READ, _MODE_READ_EOF)
149
150 def writable(self):
151 """Return whether the file was opened for writing."""
Nadeem Vawda44ae4a22011-11-30 17:39:30 +0200152 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200153 return self._mode == _MODE_WRITE
154
155 # Mode-checking helper functions.
156
157 def _check_not_closed(self):
158 if self.closed:
159 raise ValueError("I/O operation on closed file")
160
161 def _check_can_read(self):
Nadeem Vawdab7a0bfe2012-09-30 23:58:01 +0200162 if self._mode not in (_MODE_READ, _MODE_READ_EOF):
Nadeem Vawda452add02012-10-01 23:02:50 +0200163 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200164 raise io.UnsupportedOperation("File not open for reading")
165
166 def _check_can_write(self):
Nadeem Vawdab7a0bfe2012-09-30 23:58:01 +0200167 if self._mode != _MODE_WRITE:
Nadeem Vawda452add02012-10-01 23:02:50 +0200168 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200169 raise io.UnsupportedOperation("File not open for writing")
170
171 def _check_can_seek(self):
Nadeem Vawdab7a0bfe2012-09-30 23:58:01 +0200172 if self._mode not in (_MODE_READ, _MODE_READ_EOF):
Nadeem Vawda452add02012-10-01 23:02:50 +0200173 self._check_not_closed()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200174 raise io.UnsupportedOperation("Seeking is only supported "
Nadeem Vawdaf1a1af22011-05-25 00:32:08 +0200175 "on files open for reading")
Nadeem Vawdaae557d72012-02-12 01:51:38 +0200176 if not self._fp.seekable():
177 raise io.UnsupportedOperation("The underlying file object "
178 "does not support seeking")
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200179
180 # Fill the readahead buffer if it is empty. Returns False on EOF.
181 def _fill_buffer(self):
Nadeem Vawda6c573182012-09-30 03:57:33 +0200182 if self._mode == _MODE_READ_EOF:
183 return False
Nadeem Vawda8280b4b2012-08-04 15:29:28 +0200184 # Depending on the input data, our call to the decompressor may not
185 # return any data. In this case, try again after reading another block.
Nadeem Vawda6c573182012-09-30 03:57:33 +0200186 while self._buffer_offset == len(self._buffer):
187 rawblock = (self._decompressor.unused_data or
188 self._fp.read(_BUFFER_SIZE))
Nadeem Vawda55b43382011-05-27 01:52:15 +0200189
Nadeem Vawda8280b4b2012-08-04 15:29:28 +0200190 if not rawblock:
191 if self._decompressor.eof:
192 self._mode = _MODE_READ_EOF
193 self._size = self._pos
194 return False
195 else:
196 raise EOFError("Compressed file ended before the "
197 "end-of-stream marker was reached")
Nadeem Vawda55b43382011-05-27 01:52:15 +0200198
Nadeem Vawda8280b4b2012-08-04 15:29:28 +0200199 # Continue to next stream.
200 if self._decompressor.eof:
201 self._decompressor = BZ2Decompressor()
202
203 self._buffer = self._decompressor.decompress(rawblock)
Nadeem Vawda6c573182012-09-30 03:57:33 +0200204 self._buffer_offset = 0
205 return True
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200206
207 # Read data until EOF.
208 # If return_data is false, consume the data without returning it.
209 def _read_all(self, return_data=True):
Nadeem Vawda6c573182012-09-30 03:57:33 +0200210 # The loop assumes that _buffer_offset is 0. Ensure that this is true.
211 self._buffer = self._buffer[self._buffer_offset:]
212 self._buffer_offset = 0
213
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200214 blocks = []
215 while self._fill_buffer():
216 if return_data:
217 blocks.append(self._buffer)
218 self._pos += len(self._buffer)
Nadeem Vawda6c573182012-09-30 03:57:33 +0200219 self._buffer = b""
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200220 if return_data:
221 return b"".join(blocks)
222
223 # Read a block of up to n bytes.
224 # If return_data is false, consume the data without returning it.
225 def _read_block(self, n, return_data=True):
Nadeem Vawda6c573182012-09-30 03:57:33 +0200226 # If we have enough data buffered, return immediately.
227 end = self._buffer_offset + n
228 if end <= len(self._buffer):
229 data = self._buffer[self._buffer_offset : end]
230 self._buffer_offset = end
231 self._pos += len(data)
Nadeem Vawda9e2a28e2012-09-30 13:41:29 +0200232 return data if return_data else None
Nadeem Vawda6c573182012-09-30 03:57:33 +0200233
234 # The loop assumes that _buffer_offset is 0. Ensure that this is true.
235 self._buffer = self._buffer[self._buffer_offset:]
236 self._buffer_offset = 0
237
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200238 blocks = []
239 while n > 0 and self._fill_buffer():
240 if n < len(self._buffer):
241 data = self._buffer[:n]
Nadeem Vawda6c573182012-09-30 03:57:33 +0200242 self._buffer_offset = n
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200243 else:
244 data = self._buffer
Nadeem Vawda6c573182012-09-30 03:57:33 +0200245 self._buffer = b""
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200246 if return_data:
247 blocks.append(data)
248 self._pos += len(data)
249 n -= len(data)
250 if return_data:
251 return b"".join(blocks)
252
253 def peek(self, n=0):
254 """Return buffered data without advancing the file position.
255
256 Always returns at least one byte of data, unless at EOF.
257 The exact number of bytes returned is unspecified.
258 """
259 with self._lock:
260 self._check_can_read()
Nadeem Vawda6c573182012-09-30 03:57:33 +0200261 if not self._fill_buffer():
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200262 return b""
Nadeem Vawda6c573182012-09-30 03:57:33 +0200263 return self._buffer[self._buffer_offset:]
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200264
265 def read(self, size=-1):
266 """Read up to size uncompressed bytes from the file.
267
268 If size is negative or omitted, read until EOF is reached.
269 Returns b'' if the file is already at EOF.
270 """
271 with self._lock:
272 self._check_can_read()
Nadeem Vawda6c573182012-09-30 03:57:33 +0200273 if size == 0:
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200274 return b""
275 elif size < 0:
276 return self._read_all()
277 else:
278 return self._read_block(size)
279
280 def read1(self, size=-1):
Nadeem Vawda8280b4b2012-08-04 15:29:28 +0200281 """Read up to size uncompressed bytes, while trying to avoid
282 making multiple reads from the underlying stream.
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200283
284 Returns b'' if the file is at EOF.
285 """
Nadeem Vawda8280b4b2012-08-04 15:29:28 +0200286 # Usually, read1() calls _fp.read() at most once. However, sometimes
287 # this does not give enough data for the decompressor to make progress.
288 # In this case we make multiple reads, to avoid returning b"".
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200289 with self._lock:
290 self._check_can_read()
Nadeem Vawda6c573182012-09-30 03:57:33 +0200291 if (size == 0 or
292 # Only call _fill_buffer() if the buffer is actually empty.
293 # This gives a significant speedup if *size* is small.
294 (self._buffer_offset == len(self._buffer) and not self._fill_buffer())):
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200295 return b""
Nadeem Vawda6c573182012-09-30 03:57:33 +0200296 if size > 0:
297 data = self._buffer[self._buffer_offset :
298 self._buffer_offset + size]
299 self._buffer_offset += len(data)
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200300 else:
Nadeem Vawda6c573182012-09-30 03:57:33 +0200301 data = self._buffer[self._buffer_offset:]
302 self._buffer = b""
303 self._buffer_offset = 0
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200304 self._pos += len(data)
305 return data
306
307 def readinto(self, b):
308 """Read up to len(b) bytes into b.
Antoine Pitrou24ce3862011-04-03 17:08:49 +0200309
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200310 Returns the number of bytes read (0 for EOF).
311 """
312 with self._lock:
313 return io.BufferedIOBase.readinto(self, b)
314
315 def readline(self, size=-1):
316 """Read a line of uncompressed bytes from the file.
317
318 The terminating newline (if present) is retained. If size is
319 non-negative, no more than size bytes will be read (in which
320 case the line may be incomplete). Returns b'' if already at EOF.
321 """
Nadeem Vawdaeb70be22012-10-01 23:05:32 +0200322 if not isinstance(size, int):
323 if not hasattr(size, "__index__"):
324 raise TypeError("Integer argument expected")
325 size = size.__index__()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200326 with self._lock:
Nadeem Vawda138ad502012-10-01 23:04:11 +0200327 self._check_can_read()
Nadeem Vawda6c573182012-09-30 03:57:33 +0200328 # Shortcut for the common case - the whole line is in the buffer.
329 if size < 0:
330 end = self._buffer.find(b"\n", self._buffer_offset) + 1
331 if end > 0:
332 line = self._buffer[self._buffer_offset : end]
333 self._buffer_offset = end
334 self._pos += len(line)
335 return line
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200336 return io.BufferedIOBase.readline(self, size)
337
338 def readlines(self, size=-1):
339 """Read a list of lines of uncompressed bytes from the file.
340
341 size can be specified to control the number of lines read: no
342 further lines will be read once the total size of the lines read
343 so far equals or exceeds size.
344 """
Nadeem Vawdaeb70be22012-10-01 23:05:32 +0200345 if not isinstance(size, int):
346 if not hasattr(size, "__index__"):
347 raise TypeError("Integer argument expected")
348 size = size.__index__()
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200349 with self._lock:
350 return io.BufferedIOBase.readlines(self, size)
351
352 def write(self, data):
353 """Write a byte string to the file.
354
355 Returns the number of uncompressed bytes written, which is
356 always len(data). Note that due to buffering, the file on disk
357 may not reflect the data written until close() is called.
358 """
359 with self._lock:
360 self._check_can_write()
361 compressed = self._compressor.compress(data)
362 self._fp.write(compressed)
363 self._pos += len(data)
364 return len(data)
365
366 def writelines(self, seq):
367 """Write a sequence of byte strings to the file.
368
369 Returns the number of uncompressed bytes written.
370 seq can be any iterable yielding byte strings.
371
372 Line separators are not added between the written byte strings.
373 """
374 with self._lock:
375 return io.BufferedIOBase.writelines(self, seq)
376
377 # Rewind the file to the beginning of the data stream.
378 def _rewind(self):
379 self._fp.seek(0, 0)
380 self._mode = _MODE_READ
381 self._pos = 0
382 self._decompressor = BZ2Decompressor()
Nadeem Vawda6c573182012-09-30 03:57:33 +0200383 self._buffer = b""
384 self._buffer_offset = 0
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200385
386 def seek(self, offset, whence=0):
387 """Change the file position.
388
389 The new position is specified by offset, relative to the
390 position indicated by whence. Values for whence are:
391
392 0: start of stream (default); offset must not be negative
393 1: current stream position
394 2: end of stream; offset must not be positive
395
396 Returns the new file position.
397
398 Note that seeking is emulated, so depending on the parameters,
399 this operation may be extremely slow.
400 """
401 with self._lock:
402 self._check_can_seek()
403
404 # Recalculate offset as an absolute file position.
405 if whence == 0:
406 pass
407 elif whence == 1:
408 offset = self._pos + offset
409 elif whence == 2:
410 # Seeking relative to EOF - we need to know the file's size.
411 if self._size < 0:
412 self._read_all(return_data=False)
413 offset = self._size + offset
414 else:
415 raise ValueError("Invalid value for whence: {}".format(whence))
416
417 # Make it so that offset is the number of bytes to skip forward.
418 if offset < self._pos:
419 self._rewind()
420 else:
421 offset -= self._pos
422
423 # Read and discard data until we reach the desired position.
Nadeem Vawda6c573182012-09-30 03:57:33 +0200424 self._read_block(offset, return_data=False)
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200425
426 return self._pos
427
428 def tell(self):
429 """Return the current file position."""
430 with self._lock:
431 self._check_not_closed()
432 return self._pos
433
434
Nadeem Vawdaaf518c12012-06-04 23:32:38 +0200435def open(filename, mode="rb", compresslevel=9,
436 encoding=None, errors=None, newline=None):
437 """Open a bzip2-compressed file in binary or text mode.
438
439 The filename argument can be an actual filename (a str or bytes object), or
440 an existing file object to read from or write to.
441
442 The mode argument can be "r", "rb", "w", "wb", "a" or "ab" for binary mode,
443 or "rt", "wt" or "at" for text mode. The default mode is "rb", and the
444 default compresslevel is 9.
445
446 For binary mode, this function is equivalent to the BZ2File constructor:
447 BZ2File(filename, mode, compresslevel). In this case, the encoding, errors
448 and newline arguments must not be provided.
449
450 For text mode, a BZ2File object is created, and wrapped in an
451 io.TextIOWrapper instance with the specified encoding, error handling
452 behavior, and line ending(s).
453
454 """
455 if "t" in mode:
456 if "b" in mode:
457 raise ValueError("Invalid mode: %r" % (mode,))
458 else:
459 if encoding is not None:
460 raise ValueError("Argument 'encoding' not supported in binary mode")
461 if errors is not None:
462 raise ValueError("Argument 'errors' not supported in binary mode")
463 if newline is not None:
464 raise ValueError("Argument 'newline' not supported in binary mode")
465
466 bz_mode = mode.replace("t", "")
467 binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
468
469 if "t" in mode:
470 return io.TextIOWrapper(binary_file, encoding, errors, newline)
471 else:
472 return binary_file
473
474
Antoine Pitrou37dc5f82011-04-03 17:05:46 +0200475def compress(data, compresslevel=9):
476 """Compress a block of data.
477
478 compresslevel, if given, must be a number between 1 and 9.
479
480 For incremental compression, use a BZ2Compressor object instead.
481 """
482 comp = BZ2Compressor(compresslevel)
483 return comp.compress(data) + comp.flush()
484
485
486def decompress(data):
487 """Decompress a block of data.
488
489 For incremental decompression, use a BZ2Decompressor object instead.
490 """
491 if len(data) == 0:
492 return b""
Nadeem Vawda55b43382011-05-27 01:52:15 +0200493
Nadeem Vawda98838ba2011-05-30 01:12:24 +0200494 results = []
Nadeem Vawda55b43382011-05-27 01:52:15 +0200495 while True:
496 decomp = BZ2Decompressor()
Nadeem Vawda98838ba2011-05-30 01:12:24 +0200497 results.append(decomp.decompress(data))
Nadeem Vawda55b43382011-05-27 01:52:15 +0200498 if not decomp.eof:
499 raise ValueError("Compressed data ended before the "
500 "end-of-stream marker was reached")
501 if not decomp.unused_data:
Nadeem Vawda98838ba2011-05-30 01:12:24 +0200502 return b"".join(results)
Nadeem Vawda55b43382011-05-27 01:52:15 +0200503 # There is unused data left over. Proceed to next stream.
504 data = decomp.unused_data