1 ! Copyright (C) 2009 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien alien.c-types alien.data byte-vectors
4 combinators compression.zlib.ffi continuations destructors
5 kernel libc math math.functions ranges sequences ;
8 ERROR: zlib-failed n string ;
10 : zlib-error-message ( n -- * )
11 dup compression.zlib.ffi:Z_ERRNO = [
12 drop errno "native libc error"
15 neg ! zlib error codes are negative
17 "no error" "libc_error"
18 "stream error" "data error"
19 "memory error" "buffer error" "zlib version error"
25 { compression.zlib.ffi:Z_OK [ drop ] }
26 { compression.zlib.ffi:Z_STREAM_END [ drop ] }
27 [ dup zlib-error-message zlib-failed ]
30 : compressed-size ( byte-array -- n )
31 length 1001/1000 * ceiling 12 + ;
33 : compress ( byte-array -- byte-array' )
36 [ <byte-vector> dup underlying>> ] keep ulong <ref>
38 dup length compression.zlib.ffi:compress zlib-error
39 ] keepd ulong deref >>length B{ } like ;
41 : (uncompress) ( length byte-array -- byte-array )
43 [ drop [ malloc &free ] [ ulong <ref> ] bi ]
44 [ nip dup length ] 2bi
45 [ compression.zlib.ffi:uncompress zlib-error ] 4keep
46 2drop ulong deref memory>byte-array
49 : uncompress ( byte-array -- byte-array' )
50 [ length 5 [0..b) [ 2^ * ] with map ] keep
51 '[ _ (uncompress) ] attempt-all ;
54 : zlib-inflate-init ( -- z_stream_s )
56 dup ZLIB_VERSION over byte-length inflateInit_ zlib-error ;
58 ! window can be 0, 15, 32, 47 (others?)
59 : zlib-inflate-init2 ( window -- z_stream_s )
60 [ z_stream new dup ] dip
61 ZLIB_VERSION pick byte-length inflateInit2_ zlib-error ;
63 : zlib-inflate-end ( z_stream -- )
64 inflateEnd zlib-error ;
66 : zlib-inflate-reset ( z_stream -- )
67 inflateReset zlib-error ;
69 : zlib-inflate ( z_stream flush -- )
72 : zlib-inflate-get-header ( z_stream -- gz_header )
73 gz_header new [ inflateGetHeader zlib-error ] keep ;