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 alien.syntax
4 byte-arrays byte-vectors combinators continuations destructors
5 fry kernel libc math math.functions math.ranges sequences system ;
6 QUALIFIED: compression.zlib.ffi
9 ERROR: zlib-failed n string ;
11 : zlib-error-message ( n -- * )
12 dup compression.zlib.ffi:Z_ERRNO = [
13 drop errno "native libc error"
16 neg ! zlib error codes are negative
18 "no error" "libc_error"
19 "stream error" "data error"
20 "memory error" "buffer error" "zlib version error"
25 dup compression.zlib.ffi:Z_OK = [ drop ] [ dup zlib-error-message zlib-failed ] if ;
27 : compressed-size ( byte-array -- n )
28 length 1001/1000 * ceiling 12 + ;
30 : compress ( byte-array -- byte-array' )
33 [ <byte-vector> dup underlying>> ] keep ulong <ref>
35 dup length compression.zlib.ffi:compress zlib-error
36 ] 2keep drop ulong deref >>length B{ } like ;
38 : (uncompress) ( length byte-array -- byte-array )
40 [ drop [ malloc &free ] [ ulong <ref> ] bi ]
41 [ nip dup length ] 2bi
42 [ compression.zlib.ffi:uncompress zlib-error ] 4keep
43 2drop ulong deref memory>byte-array
46 : uncompress ( byte-array -- byte-array' )
47 [ length 5 [0,b) [ 2^ * ] with map ] keep
48 '[ _ (uncompress) ] attempt-all ;