]> gitweb.factorcode.org Git - factor.git/blob - extra/compression/bzip3/bzip3.factor
add bzip3 compression
[factor.git] / extra / compression / bzip3 / bzip3.factor
1 USING: alien alien.libraries alien.c-types alien.data alien.syntax
2        kernel io.encodings.string byte-arrays sequences combinators syntax
3        compression.bzip3.ffi locals math math.order summary pair-rocket ;
4 IN: compression.bzip3
5
6 ERROR: invalid-block-size size ;
7 M: invalid-block-size summary drop "Block size must be between 65 KiB and 511 MiB" ;
8 ERROR: internal-error msg ;
9 M: internal-error summary drop "bzip3: Internal Error" ;
10 <PRIVATE
11 CONSTANT: dsize 1048576 ! placeholder block size
12
13 : throw-internal-error ( code -- msg ) {
14     -1 => [ "BZ3_ERR_OUT_OF_BOUNDS" ]
15     -2 => [ "BZ3_ERR_BWT" ]
16     -3 => [ "BZ3_ERR_CRC" ]
17     -4 => [ "BZ3_ERR_MALFORMED_HEADER" ]
18     -5 => [ "BZ3_ERR_TRUNCATED_DATA" ]
19     -6 => [ "BZ3_ERR_DATA_TOO_BIG" ]
20     -7 => [ "BZ3_ERR_INIT" ]
21     [ drop "UNDEFINED_ERR" ]
22   } case internal-error
23 ;
24
25 : KiB ( b -- kib ) 1024 * ;
26 : MiB ( b -- mib ) 1024 * 1024 * ;
27 : validate-block-size ( b -- b ) dup 65 KiB 511 MiB between? 
28   [ invalid-block-size ] unless ;
29 PRIVATE>
30
31 ALIAS: version bz3_version
32 :: compress ( byte-array block-size/f -- byte-array' )
33   byte-array length :> in-size
34   in-size bz3_bound :> out-size
35   out-size <byte-array> :> out
36   block-size/f [ dsize ] unless* validate-block-size
37   byte-array out in-size out-size size_t <ref> bz3_compress
38   dup 0 = [ drop out ] [ throw-internal-error ] if
39 ;
40
41 :: decompress ( byte-array -- byte-array' )
42   byte-array length :> in-size
43   in-size bz3_bound :> out-size
44   out-size <byte-array> :> out
45   byte-array out in-size out-size size_t <ref> bz3_decompress
46   dup 0 = [ drop out ] [ throw-internal-error ] if
47 ;