Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 1 | """Interface to the libbzip2 compression library. |
| 2 | |
| 3 | This module provides a file interface, classes for incremental |
| 4 | (de)compression, and functions for one-shot (de)compression. |
| 5 | """ |
| 6 | |
Nadeem Vawda | af518c1 | 2012-06-04 23:32:38 +0200 | [diff] [blame] | 7 | __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", |
| 8 | "open", "compress", "decompress"] |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 9 | |
| 10 | __author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>" |
| 11 | |
Nadeem Vawda | af518c1 | 2012-06-04 23:32:38 +0200 | [diff] [blame] | 12 | import builtins |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 13 | import io |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 14 | import warnings |
| 15 | |
Nadeem Vawda | 72750a8 | 2012-01-18 01:57:14 +0200 | [diff] [blame] | 16 | try: |
| 17 | from threading import RLock |
| 18 | except ImportError: |
| 19 | from dummy_threading import RLock |
| 20 | |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 21 | from _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 | |
| 32 | class 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 Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 43 | def __init__(self, filename, mode="r", buffering=None, compresslevel=9): |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 44 | """Open a bzip2-compressed file. |
| 45 | |
Nadeem Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 46 | 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 49 | |
Nadeem Vawda | 50cb936 | 2012-06-04 23:31:22 +0200 | [diff] [blame] | 50 | 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 52 | |
| 53 | buffering is ignored. Its use is deprecated. |
| 54 | |
Nadeem Vawda | cac8909 | 2012-02-04 13:08:11 +0200 | [diff] [blame] | 55 | 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 57 | compression, and 9 (default) produces the most compression. |
Nadeem Vawda | cac8909 | 2012-02-04 13:08:11 +0200 | [diff] [blame] | 58 | |
| 59 | If mode is 'r', the input file may be the concatenation of |
| 60 | multiple compressed streams. |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 61 | """ |
| 62 | # This lock must be recursive, so that BufferedIOBase's |
| 63 | # readline(), readlines() and writelines() don't deadlock. |
Nadeem Vawda | 72750a8 | 2012-01-18 01:57:14 +0200 | [diff] [blame] | 64 | self._lock = RLock() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 65 | 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 82 | self._buffer = b"" |
| 83 | self._buffer_offset = 0 |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 84 | elif mode in ("w", "wb"): |
| 85 | mode = "wb" |
| 86 | mode_code = _MODE_WRITE |
Nadeem Vawda | 249ab5e | 2011-09-11 22:38:11 +0200 | [diff] [blame] | 87 | self._compressor = BZ2Compressor(compresslevel) |
Nadeem Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 88 | elif mode in ("a", "ab"): |
| 89 | mode = "ab" |
| 90 | mode_code = _MODE_WRITE |
Nadeem Vawda | 249ab5e | 2011-09-11 22:38:11 +0200 | [diff] [blame] | 91 | self._compressor = BZ2Compressor(compresslevel) |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 92 | else: |
| 93 | raise ValueError("Invalid mode: {!r}".format(mode)) |
| 94 | |
Nadeem Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 95 | if isinstance(filename, (str, bytes)): |
Nadeem Vawda | af518c1 | 2012-06-04 23:32:38 +0200 | [diff] [blame] | 96 | self._fp = builtins.open(filename, mode) |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 97 | self._closefp = True |
| 98 | self._mode = mode_code |
Nadeem Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 99 | elif hasattr(filename, "read") or hasattr(filename, "write"): |
| 100 | self._fp = filename |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 101 | self._mode = mode_code |
| 102 | else: |
Nadeem Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 103 | raise TypeError("filename must be a str or bytes object, or a file") |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 104 | |
| 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 Pitrou | 24ce386 | 2011-04-03 17:08:49 +0200 | [diff] [blame] | 121 | try: |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 122 | if self._closefp: |
| 123 | self._fp.close() |
| 124 | finally: |
| 125 | self._fp = None |
| 126 | self._closefp = False |
| 127 | self._mode = _MODE_CLOSED |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 128 | self._buffer = b"" |
| 129 | self._buffer_offset = 0 |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 130 | |
| 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 Vawda | 44ae4a2 | 2011-11-30 17:39:30 +0200 | [diff] [blame] | 138 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 139 | return self._fp.fileno() |
| 140 | |
| 141 | def seekable(self): |
| 142 | """Return whether the file supports seeking.""" |
Nadeem Vawda | ae557d7 | 2012-02-12 01:51:38 +0200 | [diff] [blame] | 143 | return self.readable() and self._fp.seekable() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 144 | |
| 145 | def readable(self): |
| 146 | """Return whether the file was opened for reading.""" |
Nadeem Vawda | 44ae4a2 | 2011-11-30 17:39:30 +0200 | [diff] [blame] | 147 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 148 | return self._mode in (_MODE_READ, _MODE_READ_EOF) |
| 149 | |
| 150 | def writable(self): |
| 151 | """Return whether the file was opened for writing.""" |
Nadeem Vawda | 44ae4a2 | 2011-11-30 17:39:30 +0200 | [diff] [blame] | 152 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 153 | 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 Vawda | b7a0bfe | 2012-09-30 23:58:01 +0200 | [diff] [blame] | 162 | if self._mode not in (_MODE_READ, _MODE_READ_EOF): |
Nadeem Vawda | 452add0 | 2012-10-01 23:02:50 +0200 | [diff] [blame] | 163 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 164 | raise io.UnsupportedOperation("File not open for reading") |
| 165 | |
| 166 | def _check_can_write(self): |
Nadeem Vawda | b7a0bfe | 2012-09-30 23:58:01 +0200 | [diff] [blame] | 167 | if self._mode != _MODE_WRITE: |
Nadeem Vawda | 452add0 | 2012-10-01 23:02:50 +0200 | [diff] [blame] | 168 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 169 | raise io.UnsupportedOperation("File not open for writing") |
| 170 | |
| 171 | def _check_can_seek(self): |
Nadeem Vawda | b7a0bfe | 2012-09-30 23:58:01 +0200 | [diff] [blame] | 172 | if self._mode not in (_MODE_READ, _MODE_READ_EOF): |
Nadeem Vawda | 452add0 | 2012-10-01 23:02:50 +0200 | [diff] [blame] | 173 | self._check_not_closed() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 174 | raise io.UnsupportedOperation("Seeking is only supported " |
Nadeem Vawda | f1a1af2 | 2011-05-25 00:32:08 +0200 | [diff] [blame] | 175 | "on files open for reading") |
Nadeem Vawda | ae557d7 | 2012-02-12 01:51:38 +0200 | [diff] [blame] | 176 | if not self._fp.seekable(): |
| 177 | raise io.UnsupportedOperation("The underlying file object " |
| 178 | "does not support seeking") |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 179 | |
| 180 | # Fill the readahead buffer if it is empty. Returns False on EOF. |
| 181 | def _fill_buffer(self): |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 182 | if self._mode == _MODE_READ_EOF: |
| 183 | return False |
Nadeem Vawda | 8280b4b | 2012-08-04 15:29:28 +0200 | [diff] [blame] | 184 | # 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 186 | while self._buffer_offset == len(self._buffer): |
| 187 | rawblock = (self._decompressor.unused_data or |
| 188 | self._fp.read(_BUFFER_SIZE)) |
Nadeem Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 189 | |
Nadeem Vawda | 8280b4b | 2012-08-04 15:29:28 +0200 | [diff] [blame] | 190 | 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 Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 198 | |
Nadeem Vawda | 8280b4b | 2012-08-04 15:29:28 +0200 | [diff] [blame] | 199 | # Continue to next stream. |
| 200 | if self._decompressor.eof: |
| 201 | self._decompressor = BZ2Decompressor() |
| 202 | |
| 203 | self._buffer = self._decompressor.decompress(rawblock) |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 204 | self._buffer_offset = 0 |
| 205 | return True |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 206 | |
| 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 210 | # 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 214 | blocks = [] |
| 215 | while self._fill_buffer(): |
| 216 | if return_data: |
| 217 | blocks.append(self._buffer) |
| 218 | self._pos += len(self._buffer) |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 219 | self._buffer = b"" |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 220 | 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 226 | # 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 Vawda | 9e2a28e | 2012-09-30 13:41:29 +0200 | [diff] [blame] | 232 | return data if return_data else None |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 233 | |
| 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 238 | blocks = [] |
| 239 | while n > 0 and self._fill_buffer(): |
| 240 | if n < len(self._buffer): |
| 241 | data = self._buffer[:n] |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 242 | self._buffer_offset = n |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 243 | else: |
| 244 | data = self._buffer |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 245 | self._buffer = b"" |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 246 | 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 261 | if not self._fill_buffer(): |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 262 | return b"" |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 263 | return self._buffer[self._buffer_offset:] |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 264 | |
| 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 273 | if size == 0: |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 274 | 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 Vawda | 8280b4b | 2012-08-04 15:29:28 +0200 | [diff] [blame] | 281 | """Read up to size uncompressed bytes, while trying to avoid |
| 282 | making multiple reads from the underlying stream. |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 283 | |
| 284 | Returns b'' if the file is at EOF. |
| 285 | """ |
Nadeem Vawda | 8280b4b | 2012-08-04 15:29:28 +0200 | [diff] [blame] | 286 | # 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 289 | with self._lock: |
| 290 | self._check_can_read() |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 291 | 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 295 | return b"" |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 296 | if size > 0: |
| 297 | data = self._buffer[self._buffer_offset : |
| 298 | self._buffer_offset + size] |
| 299 | self._buffer_offset += len(data) |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 300 | else: |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 301 | data = self._buffer[self._buffer_offset:] |
| 302 | self._buffer = b"" |
| 303 | self._buffer_offset = 0 |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 304 | self._pos += len(data) |
| 305 | return data |
| 306 | |
| 307 | def readinto(self, b): |
| 308 | """Read up to len(b) bytes into b. |
Antoine Pitrou | 24ce386 | 2011-04-03 17:08:49 +0200 | [diff] [blame] | 309 | |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 310 | 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 Vawda | eb70be2 | 2012-10-01 23:05:32 +0200 | [diff] [blame] | 322 | if not isinstance(size, int): |
| 323 | if not hasattr(size, "__index__"): |
| 324 | raise TypeError("Integer argument expected") |
| 325 | size = size.__index__() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 326 | with self._lock: |
Nadeem Vawda | 138ad50 | 2012-10-01 23:04:11 +0200 | [diff] [blame] | 327 | self._check_can_read() |
Nadeem Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 328 | # 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 336 | 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 Vawda | eb70be2 | 2012-10-01 23:05:32 +0200 | [diff] [blame] | 345 | if not isinstance(size, int): |
| 346 | if not hasattr(size, "__index__"): |
| 347 | raise TypeError("Integer argument expected") |
| 348 | size = size.__index__() |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 349 | 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 383 | self._buffer = b"" |
| 384 | self._buffer_offset = 0 |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 385 | |
| 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 Vawda | 6c57318 | 2012-09-30 03:57:33 +0200 | [diff] [blame] | 424 | self._read_block(offset, return_data=False) |
Antoine Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 425 | |
| 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 Vawda | af518c1 | 2012-06-04 23:32:38 +0200 | [diff] [blame] | 435 | def 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 Pitrou | 37dc5f8 | 2011-04-03 17:05:46 +0200 | [diff] [blame] | 475 | def 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 | |
| 486 | def 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 Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 493 | |
Nadeem Vawda | 98838ba | 2011-05-30 01:12:24 +0200 | [diff] [blame] | 494 | results = [] |
Nadeem Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 495 | while True: |
| 496 | decomp = BZ2Decompressor() |
Nadeem Vawda | 98838ba | 2011-05-30 01:12:24 +0200 | [diff] [blame] | 497 | results.append(decomp.decompress(data)) |
Nadeem Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 498 | 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 Vawda | 98838ba | 2011-05-30 01:12:24 +0200 | [diff] [blame] | 502 | return b"".join(results) |
Nadeem Vawda | 55b4338 | 2011-05-27 01:52:15 +0200 | [diff] [blame] | 503 | # There is unused data left over. Proceed to next stream. |
| 504 | data = decomp.unused_data |