| examples | ||
| .gitignore | ||
| bz2.nim | ||
| bz2.nimble | ||
| LICENSE.txt | ||
| README.md | ||
bz2
bz2 is a Nim module for the bzip2 compression format.
install
nimble install bz2
Requirements
- Linux (other OS PRs welcome, it just takes figuring out the library name)
libbz2.so.1installed (It's inlibbz2-1.0for Debian based distros)
One-shot API
proc compress*(data: string, compresslevel: range[1..9] = 9): string
proc decompress*(data: string): string
Example: examples/compress_simple.nim
Streaming API
The BzCompressor and BzDecompressor types have =destroy hooks and do not need to be manually deallocated. They are not guaranteed to be thread safe. For details on the optional parameters check out the bzip2 manual.
Compression
type BzCompressor* = object
stream: BzStream
proc newBzCompressor*(compresslevel: range[1..9] = 9, verbosity: range[0..4] = 0,
workFactor: range[0..250] = 0): ref BzCompressor
proc compress*(compressor: ref BzCompressor, data: string): string
proc flush*(compressor: ref BzCompressor): string
proc finish*(compressor: ref BzCompressor): string
After a compressor is created with newBzCompressor data can be fed with compress and the procedure will return the compressed data. After all input data has been submitted the compression has to be completed with a call to finish which returns the remaining compressed stream. There is usually no need to call flush, it is only included for completeness.
Example: examples/compress_stream.nim
Decompression
type BzDecompressor* = object
stream: BzStream
eof: bool
unusedData: string
proc newBzDecompressor*(verbosity: range[0..4] = 0, small: bool = false):
ref BzDecompressor
proc decompress*(decompressor: ref BzDecompressor, data: string): string
After a decompressor is created with newBzDecompressor data can be fed with decompress and the procedure will return the decompressed data. The procedure will automatically detect the end of a compression stream and set the eof variable. Any remaining data that was not part of the compressed stream will be placed in unusedData. After eof has been set any subsequent call will raise an exception. Handling of multiple concatenated streams is not usually needed and can be ignored for simple applications.
Example: examples/decompress_stream.nim
Error Handling
Errors will raise a BzError. It contains a member code of type BzReturn which identifies the error.
type BzError* = object of CatchableError
code: BzReturn
type BzReturn* {.size: sizeof(cint).} = enum
BZ_CONFIG_ERROR = -9
BZ_OUTBUFF_FULL = -8
BZ_UNEXPECTED_EOF = -7
BZ_IO_ERROR = -6
BZ_DATA_ERROR_MAGIC = -5
BZ_DATA_ERROR = -4
BZ_MEM_ERROR = -3
BZ_PARAM_ERROR = -2
BZ_SEQUENCE_ERROR = -1
BZ_OK = 0
BZ_RUN_OK = 1
BZ_FLUSH_OK = 2
BZ_FINISH_OK = 3
BZ_STREAM_END = 4
Wrapper
This module includes a simple wrapper for the low-level C interface of libbz2 with type safe constants. It does not wrap the file based API.