| Copyright | (c) 2006-2008 Duncan Coutts |
|---|---|
| License | BSD-style |
| Maintainer | duncan@haskell.org |
| Stability | provisional |
| Portability | portable (H98 + FFI) |
| Safe Haskell | None |
| Language | Haskell2010 |
Codec.Compression.BZip.Internal
Description
Pure stream based interface to lower level bzlib wrapper
Synopsis
- compress :: CompressParams -> ByteString -> ByteString
- decompress :: DecompressParams -> ByteString -> ByteString
- data CompressStream (m :: Type -> Type)
- = CompressInputRequired {
- compressSupplyInput :: ByteString -> m (CompressStream m)
- | CompressOutputAvailable {
- compressOutput :: !ByteString
- compressNext :: m (CompressStream m)
- | CompressStreamEnd
- = CompressInputRequired {
- compressST :: CompressParams -> CompressStream (ST s)
- compressIO :: CompressParams -> CompressStream IO
- foldCompressStream :: Monad m => ((ByteString -> m a) -> m a) -> (ByteString -> m a -> m a) -> m a -> CompressStream m -> m a
- foldCompressStreamWithInput :: (ByteString -> a -> a) -> a -> (forall s. CompressStream (ST s)) -> ByteString -> a
- data DecompressStream (m :: Type -> Type)
- = DecompressInputRequired {
- decompressSupplyInput :: ByteString -> m (DecompressStream m)
- | DecompressOutputAvailable {
- decompressOutput :: !ByteString
- decompressNext :: m (DecompressStream m)
- | DecompressStreamEnd {
- decompressUnconsumedInput :: ByteString
- | DecompressStreamError { }
- = DecompressInputRequired {
- data DecompressError
- = TruncatedInput
- | DataFormatError String
- decompressST :: DecompressParams -> DecompressStream (ST s)
- decompressIO :: DecompressParams -> DecompressStream IO
- foldDecompressStream :: Monad m => ((ByteString -> m a) -> m a) -> (ByteString -> m a -> m a) -> (ByteString -> m a) -> (DecompressError -> m a) -> DecompressStream m -> m a
- foldDecompressStreamWithInput :: (ByteString -> a -> a) -> (ByteString -> a) -> (DecompressError -> a) -> (forall s. DecompressStream (ST s)) -> ByteString -> a
- data CompressParams = CompressParams {}
- defaultCompressParams :: CompressParams
- data DecompressParams = DecompressParams {}
- defaultDecompressParams :: DecompressParams
- data BlockSize
- = DefaultBlockSize
- | BlockSize Int
- data WorkFactor
- = DefaultWorkFactor
- | WorkFactor Int
- data MemoryLevel
Pure interface
compress :: CompressParams -> ByteString -> ByteString Source #
Compress a data stream provided as a lazy ByteString.
There are no expected error conditions. All input data streams are valid. It is possible for unexpected errors to occur, such as running out of memory, or finding the wrong version of the bz2 C library; these are thrown as exceptions.
decompress :: DecompressParams -> ByteString -> ByteString Source #
Decompress a data stream provided as a lazy ByteString.
It will throw an exception if any error is encountered in the input data.
If you need more control over error handling then use one of the incremental
versions, decompressST or decompressIO.
Monadic incremental interface
The pure compress and
decompress functions are streaming in the sense
that they can produce output without demanding all input, however they need
the input data stream as a lazy ByteString. Having the input data
stream as a lazy ByteString often requires using lazy I/O which is not
appropriate in all circumstances.
For these cases an incremental interface is more appropriate. This interface allows both incremental input and output. Chunks of input data are supplied one by one (e.g. as they are obtained from an input source like a file or network source). Output is also produced chunk by chunk.
The incremental input and output is managed via the CompressStream and
DecompressStream types. They represent the unfolding of the process of
compressing and decompressing. They operates in either the ST or IO
monads. They can be lifted into other incremental abstractions like pipes or
conduits, or they can be used directly in the following style.
Incremental compression
In a loop:
- Inspect the status of the stream
- When it is
CompressInputRequiredthen you should call the action, passing a chunk of input (oremptywhen no more input is available) to get the next state of the stream and continue the loop. - When it is
CompressOutputAvailablethen do something with the given chunk of output, and call the action to get the next state of the stream and continue the loop. - When it is
CompressStreamEndthen terminate the loop.
Note that you cannot stop as soon as you have no more input, you need to
carry on until all the output has been collected, i.e. until you get to
CompressStreamEnd.
Here is an example where we get input from one file handle and send the compressed output to another file handle.
go :: Handle -> Handle -> CompressStream IO -> IO () go inh outh (CompressInputRequired next) = do inchunk <- BS.hGet inh 4096 go inh outh =<< next inchunk go inh outh (CompressOutputAvailable outchunk next) = BS.hPut outh outchunk go inh outh =<< next go _ _ CompressStreamEnd = return ()
The same can be achieved with foldCompressStream:
foldCompressStream (\next -> do inchunk <- BS.hGet inh 4096; next inchunk) (\outchunk next -> do BS.hPut outh outchunk; next) (return ())
data CompressStream (m :: Type -> Type) Source #
The unfolding of the compression process, where you provide a sequence of uncompressed data chunks as input and receive a sequence of compressed data chunks as output. The process is incremental, in that the demand for input and provision of output are interleaved.
Constructors
| CompressInputRequired | |
Fields
| |
| CompressOutputAvailable | |
Fields
| |
| CompressStreamEnd | |
compressST :: CompressParams -> CompressStream (ST s) Source #
Incremental compression in the ST monad. Using ST makes it possible
to write pure lazy functions while making use of incremental compression.
Chunk size must fit into CUInt.
compressIO :: CompressParams -> CompressStream IO Source #
Incremental compression in the IO monad.
Chunk size must fit into CUInt.
Arguments
| :: Monad m | |
| => ((ByteString -> m a) -> m a) | How to obtain more input to be compressed. Typically, this is a lambda of the form \consume -> do { bs <- obtainData ; consume bs } |
| -> (ByteString -> m a -> m a) | The right-folding operation. Note that the second argument is already embedded in the monad. This is typically a lambda of the form \chunk next -> Data.ByteString.Lazy.chunk chunk <$> next or \chunk next -> do { writeData chunk ; next} |
| -> m a | The base value of the fold. If the output
is itself a |
| -> CompressStream m | The input stream. Typically, this is
( |
| -> m a |
A fold over the CompressStream in the given monad.
One way to look at this is that it runs the stream, using callback functions for the three stream events.
foldCompressStreamWithInput Source #
Arguments
| :: (ByteString -> a -> a) | The right-folding operation, used to create output.
In typical usage, this is |
| -> a | The base value of the fold. In typical usage,
this is just |
| -> (forall s. CompressStream (ST s)) | The compression stream. Typically, this is
( |
| -> ByteString | The input lazy |
| -> a |
A variant on foldCompressStream that is pure rather than operating in a
monad and where the input is provided by a lazy ByteString. So we only
have to deal with the output and end parts, making it just like a foldr on a
list of output chunks.
For example:
toChunks = foldCompressStreamWithInput (:) []
Incremental decompression
The use of DecompressStream is very similar to CompressStream but with
a few differences:
- There is the extra possibility of a
DecompressStreamError - There can be extra trailing data after a compressed stream, and the
DecompressStreamEndincludes that.
Otherwise the same loop style applies, and there are fold functions.
data DecompressStream (m :: Type -> Type) Source #
The unfolding of the decompression process, where you provide a sequence of compressed data chunks as input and receive a sequence of uncompressed data chunks as output. The process is incremental, in that the demand for input and provision of output are interleaved.
Constructors
| DecompressInputRequired | |
Fields
| |
| DecompressOutputAvailable | |
Fields
| |
| DecompressStreamEnd | Includes any trailing unconsumed input data. |
Fields
| |
| DecompressStreamError | An error code |
Fields | |
data DecompressError Source #
The possible error cases when decompressing a stream.
This can be shown to give a human readable error message.
Since: 0.5.3.0
Constructors
| TruncatedInput | The compressed data stream ended prematurely. This may happen if the input data stream was truncated. |
| DataFormatError String | If the compressed data stream is corrupted in any way then you will get this error. |
Instances
| Exception DecompressError Source # | |
Defined in Codec.Compression.BZip.Internal Methods toException :: DecompressError -> SomeException fromException :: SomeException -> Maybe DecompressError displayException :: DecompressError -> String backtraceDesired :: DecompressError -> Bool | |
| Show DecompressError Source # | |
Defined in Codec.Compression.BZip.Internal Methods showsPrec :: Int -> DecompressError -> ShowS show :: DecompressError -> String showList :: [DecompressError] -> ShowS | |
decompressST :: DecompressParams -> DecompressStream (ST s) Source #
Incremental decompression in the ST monad. Using ST makes it possible
to write pure lazy functions while making use of incremental decompression.
Chunk size must fit into CUInt.
decompressIO :: DecompressParams -> DecompressStream IO Source #
Incremental decompression in the IO monad.
Chunk size must fit into CUInt.
Arguments
| :: Monad m | |
| => ((ByteString -> m a) -> m a) | How to obtain more input for the decompression stream. Typically, this is a lambda of the form \consume -> do { bs <- obtainData ; consume bs } |
| -> (ByteString -> m a -> m a) | The right-folding operation. Note that the second argument is already embedded in the monad. This is typically a lambda of the form \chunk next -> Data.ByteString.Lazy.Internal.chunk chunk <$> next or \chunk next -> do { writeData chunk ; next} |
| -> (ByteString -> m a) | How to handle any trailing data after
decompression is completed. To ignore it,
just pass |
| -> (DecompressError -> m a) | How to handle errors. Typically, this is
|
| -> DecompressStream m | The input stream. Typically, this is
( |
| -> m a |
A fold over the DecompressStream in the given monad.
One way to look at this is that it runs the stream, using callback functions for the four stream events.
foldDecompressStreamWithInput Source #
Arguments
| :: (ByteString -> a -> a) | The right-folding operation, used to create output.
In typical usage, this is |
| -> (ByteString -> a) | How to handle any trailing data; typically, this is discarded. |
| -> (DecompressError -> a) | How to handle any errors. To raise this as an
error, just use |
| -> (forall s. DecompressStream (ST s)) | The decompression stream. Typically, this is
( |
| -> ByteString | The input lazy |
| -> a |
A variant on foldDecompressStream that is pure rather than operating in a
monad and where the input is provided by a lazy ByteString. So we only
have to deal with the output, end and error parts, making it like a foldr on
a list of output chunks.
For example:
toChunks params = foldDecompressStreamWithInput (:) (const []) throw (decompressST params)
or
import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L decompressWith params = foldDecompressStreamWithInput (L.chunk) (const L.empty) throw (decompressST params)
The compression parameter types
data CompressParams Source #
The full set of parameters for compression. The defaults are
defaultCompressParams.
The compressBufferSize is the size of the first output buffer containing
the compressed data. If you know an approximate upper bound on the size of
the compressed data then setting this parameter can save memory. The default
compression output buffer size is 16k. If your estimate is wrong it does
not matter too much, the default buffer size will be used for the remaining
chunks.
Constructors
| CompressParams | |
Fields | |
Instances
| Show CompressParams Source # | |
Defined in Codec.Compression.BZip.Internal Methods showsPrec :: Int -> CompressParams -> ShowS show :: CompressParams -> String showList :: [CompressParams] -> ShowS | |
defaultCompressParams :: CompressParams Source #
The default set of parameters for compression. This is typically used with
the compressWith function with specific parameters overridden.
data DecompressParams Source #
The full set of parameters for decompression. The defaults are
defaultDecompressParams.
The decompressBufferSize is the size of the first output buffer,
containing the uncompressed data. If you know an exact or approximate upper
bound on the size of the decompressed data then setting this parameter can
save memory. The default decompression output buffer size is 32k. If your
estimate is wrong it does not matter too much, the default buffer size will
be used for the remaining chunks.
One particular use case for setting the decompressBufferSize is if you
know the exact size of the decompressed data and want to produce a strict
ByteString. The compression and decompression functions
use lazy ByteStrings but if you set the
decompressBufferSize correctly then you can generate a lazy
ByteString with exactly one chunk, which can be
converted to a strict ByteString in O(1) time using
.concat . toChunks
Constructors
| DecompressParams | |
Fields | |
Instances
| Show DecompressParams Source # | |
Defined in Codec.Compression.BZip.Internal Methods showsPrec :: Int -> DecompressParams -> ShowS show :: DecompressParams -> String showList :: [DecompressParams] -> ShowS | |
defaultDecompressParams :: DecompressParams Source #
The default set of parameters for decompression. This is typically used with
the compressWith function with specific parameters overridden.
The block size affects both the compression ratio achieved, and the amount of memory needed for compression and decompression.
through BlockSize 1 specify the block size to be 100,000
bytes through 900,000 bytes respectively. The default is to use the maximum
block size.BlockSize 9
Larger block sizes give rapidly diminishing marginal returns. Most of the compression comes from the first two or three hundred k of block size, a fact worth bearing in mind when using bzip2 on small machines. It is also important to appreciate that the decompression memory requirement is set at compression time by the choice of block size.
- In general, try and use the largest block size memory constraints allow, since that maximises the compression achieved.
- Compression and decompression speed are virtually unaffected by block size.
Another significant point applies to files which fit in a single block -
that means most files you'd encounter using a large block size. The amount
of real memory touched is proportional to the size of the file, since the
file is smaller than a block. For example, compressing a file 20,000 bytes
long with the flag will cause the compressor to allocate
around 7600k of memory, but only touch 400k + 20000 * 8 = 560 kbytes of it.
Similarly, the decompressor will allocate 3700k but only touch 100k + 20000
* 4 = 180 kbytes.BlockSize 9
Constructors
| DefaultBlockSize | The default block size is also the maximum. |
| BlockSize Int | A specific block size between 1 and 9. |
data WorkFactor Source #
The WorkFactor parameter controls how the compression phase behaves when
presented with worst case, highly repetitive, input data. If compression
runs into difficulties caused by repetitive data, the library switches from
the standard sorting algorithm to a fallback algorithm. The fallback is
slower than the standard algorithm by perhaps a factor of three, but always
behaves reasonably, no matter how bad the input.
Lower values of WorkFactor reduce the amount of effort the standard
algorithm will expend before resorting to the fallback. You should set this
parameter carefully; too low, and many inputs will be handled by the
fallback algorithm and so compress rather slowly, too high, and your
average-to-worst case compression times can become very large. The default
value of 30 gives reasonable behaviour over a wide range of circumstances.
- Note that the compressed output generated is the same regardless of whether or not the fallback algorithm is used.
Constructors
| DefaultWorkFactor | The default work factor is 30. |
| WorkFactor Int | Allowable values range from 1 to 250 inclusive. |
Instances
| Show WorkFactor Source # | |
Defined in Codec.Compression.BZip.Stream Methods showsPrec :: Int -> WorkFactor -> ShowS show :: WorkFactor -> String showList :: [WorkFactor] -> ShowS | |
data MemoryLevel Source #
For files compressed with the default 900k block size, decompression will require about 3700k to decompress. To support decompression of any file in less than 4Mb there is the option to decompress using approximately half this amount of memory, about 2300k. Decompression speed is also halved, so you should use this option only where necessary.
Constructors
| DefaultMemoryLevel | The default. |
| MinMemoryLevel | Use minimum memory during decompression. This halves the memory needed but also halves the decompression speed. |
Instances
| Show MemoryLevel Source # | |
Defined in Codec.Compression.BZip.Stream Methods showsPrec :: Int -> MemoryLevel -> ShowS show :: MemoryLevel -> String showList :: [MemoryLevel] -> ShowS | |