interface to the libbzip2 compression library this module provides a file interface classes for incremental decompression and functions for oneshot decompression value 2 no longer used a file object providing transparent bzip2 decompression a bz2file can act as a wrapper for an existing file object or refer directly to a named file on disk note that bz2file provides a binary file interface data read is returned as bytes and data to be written should be given as bytes open a bzip2compressed file if filename is a str bytes or pathlike object it gives the name of the file to be opened otherwise it should be a file object which will be used to read or write the compressed data mode can be r for reading default w for overwriting x for creating exclusively or a for appending these can equivalently be given as rb wb xb and ab if mode is w x or a compresslevel can be a number between 1 and 9 specifying the level of compression 1 produces the least compression and 9 default produces the most compression if mode is r the input file may be the concatenation of multiple compressed streams flush and close the file may be called more than once without error once the file is closed any other operation on it will raise a valueerror true if this file is closed return self mode modeclosed def filenoself return whether the file supports seeking return self readable and self buffer seekable def readableself return whether the file was opened for writing self checknotclosed return self mode modewrite def peekself n0 self checkcanread relies on the undocumented fact that bufferedreader peek always returns at least one byte except at eof independent of the value of n return self buffer peekn def readself size1 self checkcanread return self buffer readsize def read1self size1 self checkcanread if size 0 size io defaultbuffersize return self buffer read1size def readintoself b self checkcanread return self buffer readintob def readlineself size1 if not isinstancesize int if not hasattrsize index raise typeerrorinteger argument expected size size index self checkcanread return self buffer readlinesize def readlinesself size1 if not isinstancesize int if not hasattrsize index raise typeerrorinteger argument expected size size index self checkcanread return self buffer readlinessize def writeself data self checkcanwrite if isinstancedata bytes bytearray length lendata else accept any data that supports the buffer protocol data memoryviewdata length data nbytes compressed self compressor compressdata self fp writecompressed self pos length return length def writelinesself seq return compression basestream writelinesself seq def seekself offset whenceio seekset self checkcanseek return self buffer seekoffset whence def tellself open a bzip2compressed file in binary or text mode the filename argument can be an actual filename a str bytes or pathlike object or an existing file object to read from or write to the mode argument can be r rb w wb x xb a or ab for binary mode or rt wt xt or at for text mode the default mode is rb and the default compresslevel is 9 for binary mode this function is equivalent to the bz2file constructor bz2filefilename mode compresslevel in this case the encoding errors and newline arguments must not be provided for text mode a bz2file object is created and wrapped in an io textiowrapper instance with the specified encoding error handling behavior and line endings compress a block of data compresslevel if given must be a number between 1 and 9 for incremental compression use a bz2compressor object instead decompress a block of data for incremental decompression use a bz2decompressor object instead value 2 no longer used a file object providing transparent bzip2 de compression a bz2file can act as a wrapper for an existing file object or refer directly to a named file on disk note that bz2file provides a binary file interface data read is returned as bytes and data to be written should be given as bytes open a bzip2 compressed file if filename is a str bytes or pathlike object it gives the name of the file to be opened otherwise it should be a file object which will be used to read or write the compressed data mode can be r for reading default w for over writing x for creating exclusively or a for appending these can equivalently be given as rb wb xb and ab if mode is w x or a compresslevel can be a number between 1 and 9 specifying the level of compression 1 produces the least compression and 9 default produces the most compression if mode is r the input file may be the concatenation of multiple compressed streams flush and close the file may be called more than once without error once the file is closed any other operation on it will raise a valueerror true if this file is closed return the file descriptor for the underlying file return whether the file supports seeking return whether the file was opened for reading return whether the file was opened for writing return buffered data without advancing the file position always returns at least one byte of data unless at eof the exact number of bytes returned is unspecified relies on the undocumented fact that bufferedreader peek always returns at least one byte except at eof independent of the value of n read up to size uncompressed bytes from the file if size is negative or omitted read until eof is reached returns b if the file is already at eof read up to size uncompressed bytes while trying to avoid making multiple reads from the underlying stream reads up to a buffer s worth of data if size is negative returns b if the file is at eof read bytes into b returns the number of bytes read 0 for eof read a line of uncompressed bytes from the file the terminating newline if present is retained if size is non negative no more than size bytes will be read in which case the line may be incomplete returns b if already at eof read a list of lines of uncompressed bytes from the file size can be specified to control the number of lines read no further lines will be read once the total size of the lines read so far equals or exceeds size write a byte string to the file returns the number of uncompressed bytes written which is always the length of data in bytes note that due to buffering the file on disk may not reflect the data written until close is called accept any data that supports the buffer protocol write a sequence of byte strings to the file returns the number of uncompressed bytes written seq can be any iterable yielding byte strings line separators are not added between the written byte strings change the file position the new position is specified by offset relative to the position indicated by whence values for whence are 0 start of stream default offset must not be negative 1 current stream position 2 end of stream offset must not be positive returns the new file position note that seeking is emulated so depending on the parameters this operation may be extremely slow return the current file position open a bzip2 compressed file in binary or text mode the filename argument can be an actual filename a str bytes or pathlike object or an existing file object to read from or write to the mode argument can be r rb w wb x xb a or ab for binary mode or rt wt xt or at for text mode the default mode is rb and the default compresslevel is 9 for binary mode this function is equivalent to the bz2file constructor bz2file filename mode compresslevel in this case the encoding errors and newline arguments must not be provided for text mode a bz2file object is created and wrapped in an io textiowrapper instance with the specified encoding error handling behavior and line ending s compress a block of data compresslevel if given must be a number between 1 and 9 for incremental compression use a bz2compressor object instead decompress a block of data for incremental decompression use a bz2decompressor object instead leftover data is not a valid bzip2 stream ignore it error on the first iteration bail out
__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
           "open", "compress", "decompress"]

__author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"

from builtins import open as _builtin_open
import io
import os
import _compression

from _bz2 import BZ2Compressor, BZ2Decompressor


_MODE_CLOSED   = 0
_MODE_READ     = 1

_MODE_WRITE    = 3


class BZ2File(_compression.BaseStream):

    

    def __init__(self, filename, mode="r", *, compresslevel=9):
        
        self._fp = None
        self._closefp = False
        self._mode = _MODE_CLOSED

        if not (1 <= compresslevel <= 9):
            raise ValueError("compresslevel must be between 1 and 9")

        if mode in ("", "r", "rb"):
            mode = "rb"
            mode_code = _MODE_READ
        elif mode in ("w", "wb"):
            mode = "wb"
            mode_code = _MODE_WRITE
            self._compressor = BZ2Compressor(compresslevel)
        elif mode in ("x", "xb"):
            mode = "xb"
            mode_code = _MODE_WRITE
            self._compressor = BZ2Compressor(compresslevel)
        elif mode in ("a", "ab"):
            mode = "ab"
            mode_code = _MODE_WRITE
            self._compressor = BZ2Compressor(compresslevel)
        else:
            raise ValueError("Invalid mode: %r" % (mode,))

        if isinstance(filename, (str, bytes, os.PathLike)):
            self._fp = _builtin_open(filename, mode)
            self._closefp = True
            self._mode = mode_code
        elif hasattr(filename, "read") or hasattr(filename, "write"):
            self._fp = filename
            self._mode = mode_code
        else:
            raise TypeError("filename must be a str, bytes, file or PathLike object")

        if self._mode == _MODE_READ:
            raw = _compression.DecompressReader(self._fp,
                BZ2Decompressor, trailing_error=OSError)
            self._buffer = io.BufferedReader(raw)
        else:
            self._pos = 0

    def close(self):
        
        if self._mode == _MODE_CLOSED:
            return
        try:
            if self._mode == _MODE_READ:
                self._buffer.close()
            elif self._mode == _MODE_WRITE:
                self._fp.write(self._compressor.flush())
                self._compressor = None
        finally:
            try:
                if self._closefp:
                    self._fp.close()
            finally:
                self._fp = None
                self._closefp = False
                self._mode = _MODE_CLOSED
                self._buffer = None

    @property
    def closed(self):
        
        return self._mode == _MODE_CLOSED

    def fileno(self):
        
        self._check_not_closed()
        return self._fp.fileno()

    def seekable(self):
        
        return self.readable() and self._buffer.seekable()

    def readable(self):
        
        self._check_not_closed()
        return self._mode == _MODE_READ

    def writable(self):
        
        self._check_not_closed()
        return self._mode == _MODE_WRITE

    def peek(self, n=0):
        
        self._check_can_read()
        
        
        
        return self._buffer.peek(n)

    def read(self, size=-1):
        
        self._check_can_read()
        return self._buffer.read(size)

    def read1(self, size=-1):
        
        self._check_can_read()
        if size < 0:
            size = io.DEFAULT_BUFFER_SIZE
        return self._buffer.read1(size)

    def readinto(self, b):
        
        self._check_can_read()
        return self._buffer.readinto(b)

    def readline(self, size=-1):
        
        if not isinstance(size, int):
            if not hasattr(size, "__index__"):
                raise TypeError("Integer argument expected")
            size = size.__index__()
        self._check_can_read()
        return self._buffer.readline(size)

    def readlines(self, size=-1):
        
        if not isinstance(size, int):
            if not hasattr(size, "__index__"):
                raise TypeError("Integer argument expected")
            size = size.__index__()
        self._check_can_read()
        return self._buffer.readlines(size)

    def write(self, data):
        
        self._check_can_write()
        if isinstance(data, (bytes, bytearray)):
            length = len(data)
        else:
            
            data = memoryview(data)
            length = data.nbytes

        compressed = self._compressor.compress(data)
        self._fp.write(compressed)
        self._pos += length
        return length

    def writelines(self, seq):
        
        return _compression.BaseStream.writelines(self, seq)

    def seek(self, offset, whence=io.SEEK_SET):
        
        self._check_can_seek()
        return self._buffer.seek(offset, whence)

    def tell(self):
        
        self._check_not_closed()
        if self._mode == _MODE_READ:
            return self._buffer.tell()
        return self._pos


def open(filename, mode="rb", compresslevel=9,
         encoding=None, errors=None, newline=None):
    
    if "t" in mode:
        if "b" in mode:
            raise ValueError("Invalid mode: %r" % (mode,))
    else:
        if encoding is not None:
            raise ValueError("Argument 'encoding' not supported in binary mode")
        if errors is not None:
            raise ValueError("Argument 'errors' not supported in binary mode")
        if newline is not None:
            raise ValueError("Argument 'newline' not supported in binary mode")

    bz_mode = mode.replace("t", "")
    binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)

    if "t" in mode:
        encoding = io.text_encoding(encoding)
        return io.TextIOWrapper(binary_file, encoding, errors, newline)
    else:
        return binary_file


def compress(data, compresslevel=9):
    
    comp = BZ2Compressor(compresslevel)
    return comp.compress(data) + comp.flush()


def decompress(data):
    
    results = []
    while data:
        decomp = BZ2Decompressor()
        try:
            res = decomp.decompress(data)
        except OSError:
            if results:
                break  
            else:
                raise  
        results.append(res)
        if not decomp.eof:
            raise ValueError("Compressed data ended before the "
                             "end-of-stream marker was reached")
        data = decomp.unused_data
    return b"".join(results)