@@ -51,3 +51,51 @@ pub fn decompress(data []u8, flags int) ![]u8 {
5151 return ret
5252 }
5353}
54+
55+ // ChunkCallback is used to receive decompressed chunks of maximum 32768 bytes.
56+ // After processing the chunk this function should return the chunk's length to indicate
57+ // the decompressor to send more chunks, otherwise the decompression stops.
58+ // The userdata parameter comes from the call to decompress_with_callback/4, and can be used
59+ // to pass arbitrary data, without having to create a closure.
60+ pub type ChunkCallback = fn (chunk []u8 , userdata voidptr ) int
61+
62+ // decompress_with_callback decompresses an array of bytes based on the provided flags,
63+ // and a V fn callback to receive decompressed chunks, of at most 32 kilobytes each.
64+ // It returns the total decompressed length, or a decompression error.
65+ // NB: this is a low level api, a high level implementation like zlib/gzip should be preferred.
66+ pub fn decompress_with_callback (data []u8 , cb ChunkCallback, userdata voidptr , flags int ) ! u64 {
67+ cbdata := DecompressionCallBackData{
68+ data: data.data
69+ size: usize (data.len)
70+ cb: cb
71+ userdata: userdata
72+ }
73+ status := C.tinfl_decompress_mem_to_callback (cbdata.data, & cbdata.size, c_cb_for_decompress_mem,
74+ & cbdata, flags)
75+ if status == 0 {
76+ return error ('decompression error' )
77+ }
78+ return cbdata.decompressed_size
79+ }
80+
81+ struct DecompressionCallBackData {
82+ mut :
83+ data voidptr
84+ size usize
85+ decompressed_size u64
86+ userdata voidptr
87+ cb ChunkCallback = unsafe { nil }
88+ }
89+
90+ fn c_cb_for_decompress_mem (buf & char, len int , pdcbd voidptr ) int {
91+ mut cbdata := unsafe { & DecompressionCallBackData (pdcbd) }
92+ if cbdata.cb (unsafe { voidptr (buf).vbytes (len) }, cbdata.userdata) == len {
93+ cbdata.decompressed_size + = u64 (len)
94+ return 1 // continue decompressing
95+ }
96+ return 0 // stop decompressing
97+ }
98+
99+ type DecompressCallback = fn (const_buffer voidptr , len int , userdata voidptr ) int
100+
101+ fn C.tinfl_decompress_mem_to_callback (const_input_buffer voidptr , psize & usize, put_buf_cb DecompressCallback, userdata voidptr , flags int ) int
0 commit comments