0 | module Codec.Compression.Zlib.Stream
  1 |
  2 | import Codec.Compression.Zlib.Internal
  3 | import Codec.Compression.Zlib.Proofs
  4 | import Codec.Compression.Zlib.Types
  5 | import Codec.Compression.Zlib.Utilities
  6 | import Data.Buffer
  7 | import Data.Buffer.Core
  8 | import Data.Buffer.Indexed
  9 | import Data.Linear.Token
 10 | import Data.Nat
 11 | import System.Zlib.Error
 12 | import System.Zlib.Types
 13 |
 14 | %default total
 15 |
 16 | --------------------------------------------------------------------------------
 17 | --          Constants
 18 | --------------------------------------------------------------------------------
 19 |
 20 | ||| Number of bytes allocated for each streaming output chunk.
 21 | |||
 22 | ||| A fixed-size output buffer prevents repeated growth and copying while still
 23 | ||| allowing arbitrarily large streams to be processed incrementally.
 24 | |||
 25 | private
 26 | streamchunksize : Nat
 27 | streamchunksize = 32768
 28 |
 29 | --------------------------------------------------------------------------------
 30 | --          Stream Handles
 31 | --------------------------------------------------------------------------------
 32 |
 33 | ||| An initialized incremental compression stream.
 34 | |||
 35 | ||| Values of this type are valid only for the duration of
 36 | ||| `withStreamingCompressor`.
 37 | |||
 38 | export
 39 | record StreamingCompressor where
 40 |   constructor MkStreamingCompressor
 41 |   compressor : Compressor
 42 |
 43 | ||| An initialized incremental decompression stream.
 44 | |||
 45 | ||| Values of this type are valid only for the duration of
 46 | ||| `withStreamingDecompressor`.
 47 | |||
 48 | export
 49 | record StreamingDecompressor where
 50 |   constructor MkStreamingDecompressor
 51 |   decompressor : Decompressor
 52 |
 53 | --------------------------------------------------------------------------------
 54 | --          Buffer Utilities
 55 | --------------------------------------------------------------------------------
 56 |
 57 | ||| A non-empty backing buffer used when invoking zlib with zero bytes of input.
 58 | |||
 59 | ||| Keeping a valid backing bytevector avoids relying on the FFI representation
 60 | ||| of a zero-length buffer when `avail_in` is zero.
 61 | |||
 62 | private
 63 | dummyInput : IBuffer 1
 64 | dummyInput =
 65 |   bufferL [0]
 66 |
 67 | private
 68 | prependProduced :  {capacity : Nat}
 69 |                 -> String
 70 |                 -> (produced : Nat)
 71 |                 -> IOBuffer capacity
 72 |                 -> List AnyBuffer
 73 |                 -> IO (Either (List ZlibError) (List AnyBuffer))
 74 | prependProduced {capacity} location produced output chunks =
 75 |   case produced of
 76 |     0 =>
 77 |       pure (Right chunks)
 78 |     _ =>
 79 |       case isLTE produced capacity of
 80 |         No _               => do
 81 |           errs <- mkError location
 82 |                           "zlib reported producing bytes beyond the output buffer"
 83 |           pure (Left errs)
 84 |         Yes producedBounds => do
 85 |           frozen <- freezeOutput produced output {bounds = producedBounds}
 86 |           pure (Right (frozen :: chunks))
 87 |
 88 | --------------------------------------------------------------------------------
 89 | --          Resource Management
 90 | --------------------------------------------------------------------------------
 91 |
 92 | ||| Run an action with an initialized streaming compressor.
 93 | |||
 94 | ||| The underlying zlib stream is finalized and freed when the action returns.
 95 | |||
 96 | export
 97 | withStreamingCompressor :  ZlibCompressionLevel
 98 |                         -> Wrapper
 99 |                         -> (StreamingCompressor -> IO (Either (List ZlibError) a))
100 |                         -> IO (Either (List ZlibError) a)
101 | withStreamingCompressor level wrapper action =
102 |   withCompressor level wrapper $ \compressor =>
103 |     action (MkStreamingCompressor compressor)
104 |
105 | ||| Run an action with an initialized streaming decompressor.
106 | |||
107 | ||| The underlying zlib stream is finalized and freed when the action returns.
108 | |||
109 | export
110 | withStreamingDecompressor :  Wrapper
111 |                           -> (StreamingDecompressor -> IO (Either (List ZlibError) a))
112 |                           -> IO (Either (List ZlibError) a)
113 | withStreamingDecompressor wrapper action =
114 |   withDecompressor wrapper $ \decompressor =>
115 |     action (MkStreamingDecompressor decompressor)
116 |
117 | --------------------------------------------------------------------------------
118 | --          Streaming Compression
119 | --------------------------------------------------------------------------------
120 |
121 | private
122 | compressInput :  {n : Nat}
123 |               -> StreamingCompressor
124 |               -> FlushMode
125 |               -> IBuffer n
126 |               -> IO (Either (List ZlibError) CompressStreamResult)
127 | compressInput (MkStreamingCompressor compressor) flush input =
128 |   go 0 (zeroLTE n) []
129 |   where
130 |     mutual
131 |       continue :  Nat
132 |                -> Nat
133 |                -> Nat
134 |                -> Nat
135 |                -> Nat
136 |                -> List AnyBuffer
137 |                -> IO (Either (List ZlibError) CompressStreamResult)
138 |       continue inputoffset inputlength consumed' produced' nextoffset chunks' =
139 |           case isLTE nextoffset n of
140 |             No _ => do
141 |               errs <- mkError "Codec.Compression.Zlib.Stream.compressInput.continue"
142 |                               "deflate reported consuming bytes beyond the supplied input"
143 |               pure (Left errs)
144 |             Yes nextbounds =>
145 |               case nextoffset < n of
146 |                 True =>
147 |                   assert_total (go nextoffset nextbounds chunks')
148 |                 False =>
149 |                   -- All input has been consumed.  If the output buffer was
150 |                   -- completely filled, zlib may still have pending output.
151 |                   case produced' == streamchunksize of
152 |                     True =>
153 |                       assert_total (go nextoffset nextbounds chunks')
154 |                     False =>
155 |                       case flush == Finish of
156 |                         True => do
157 |                           errs <- mkError "Codec.Compression.Zlib.Stream.compressInput.continue"
158 |                                           "deflate did not reach Z_STREAM_END while finishing"
159 |                           pure (Left errs)
160 |                         False =>
161 |                           pure
162 |                             ( Right
163 |                                 ( MkCompressStreamResult
164 |                                     nextoffset
165 |                                     (reverse chunks')
166 |                                     False
167 |                                 )
168 |                             )
169 |       go :  (inputoffset : Nat)
170 |          -> (0 offsetbounds : LTE inputoffset n)
171 |          -> List AnyBuffer
172 |          -> IO (Either (List ZlibError) CompressStreamResult)
173 |       go inputoffset offsetbounds chunks = do
174 |         let inputlength : Nat
175 |             inputlength = n `minus` inputoffset
176 |         output         <- mbuffer streamchunksize
177 |         Right result   <-
178 |           deflateBuffer
179 |             compressor
180 |             inputoffset
181 |             inputlength
182 |             input
183 |             {inputbounds = plusMinusLTE inputoffset n offsetbounds}
184 |             0
185 |             streamchunksize
186 |             output
187 |             {outputbounds = zeroOffsetInBounds streamchunksize}
188 |             flush
189 |           | Left errs =>
190 |               pure (Left errs)
191 |         let consumed'  : Nat
192 |             consumed'  = consumed result
193 |             produced'  : Nat
194 |             produced'  = produced result
195 |             nextoffset : Nat
196 |             nextoffset = inputoffset + consumed'
197 |         Right chunks' <-
198 |           prependProduced
199 |             "Codec.Compression.Zlib.Stream.compressInput.go"
200 |             produced'
201 |             output
202 |             chunks
203 |           | Left errs =>
204 |               pure (Left errs)
205 |         case status result of
206 |           1          =>
207 |             pure
208 |               ( Right
209 |                   ( MkCompressStreamResult
210 |                       nextoffset
211 |                       (reverse chunks')
212 |                       True
213 |                   )
214 |               )
215 |           0          =>
216 |             continue inputoffset inputlength consumed' produced' nextoffset chunks'
217 |           (-5)       =>
218 |             case consumed' == 0 && produced' == 0 of
219 |               True =>
220 |                 case flush == Finish of
221 |                   True => do
222 |                     errs <- mkError "Codec.Compression.Zlib.Stream.compressInput.go"
223 |                                     "deflate made no progress while finishing the stream"
224 |                     pure (Left errs)
225 |                   False =>
226 |                     pure
227 |                       ( Right
228 |                           ( MkCompressStreamResult
229 |                               nextoffset
230 |                               (reverse chunks')
231 |                               False
232 |                           )
233 |                       )
234 |               False =>
235 |                 continue inputoffset inputlength consumed' produced' nextoffset chunks'
236 |           unexpected => do
237 |             errs <- mkError "Codec.Compression.Zlib.Stream.compressInput.go"
238 |                             ( "Unexpected deflate status: "
239 |                                 ++ show unexpected 
240 |                             )
241 |             pure (Left errs)
242 |
243 | ||| Feed a chunk of uncompressed data into an incremental compressor.
244 | |||
245 | ||| The input is compressed using `Z_NO_FLUSH`, allowing zlib to preserve
246 | ||| compression effectiveness across chunk boundaries.
247 | |||
248 | ||| Zero or more compressed output chunks may be returned.
249 | |||
250 | export
251 | compressChunk :  {n : Nat}
252 |               -> StreamingCompressor
253 |               -> IBuffer n
254 |               -> IO (Either (List ZlibError) CompressStreamResult)
255 | compressChunk stream input =
256 |   compressInput stream NoFlush input
257 |
258 | ||| Feed input into an incremental compressor using an explicit flush mode.
259 | |||
260 | ||| Frequent flushing can reduce compression effectiveness. `NoFlush` should
261 | ||| normally be used for ordinary input chunks.
262 | |||
263 | export
264 | compressChunkWith :  {n : Nat}
265 |                   -> FlushMode
266 |                   -> StreamingCompressor
267 |                   -> IBuffer n
268 |                   -> IO (Either (List ZlibError) CompressStreamResult)
269 | compressChunkWith flush stream input =
270 |   compressInput stream flush input
271 |
272 | ||| Finish an incremental compression stream and return all remaining output.
273 | |||
274 | ||| After this function successfully returns `finished = True`, the compressor
275 | ||| must not be used again unless its underlying zlib state is reset.
276 | |||
277 | export
278 | finishCompressor :  StreamingCompressor
279 |                  -> IO (Either (List ZlibError) CompressStreamResult)
280 | finishCompressor (MkStreamingCompressor compressor) =
281 |   finish []
282 |   where
283 |     finish :  List AnyBuffer
284 |            -> IO (Either (List ZlibError) CompressStreamResult)
285 |     finish chunks = do
286 |       output        <- mbuffer streamchunksize
287 |       Right result  <-
288 |         deflateBuffer
289 |           compressor
290 |           0
291 |           0
292 |           dummyInput
293 |           {inputbounds = LTEZero}
294 |           0
295 |           streamchunksize
296 |           output
297 |           {outputbounds = zeroOffsetInBounds streamchunksize}
298 |           Finish
299 |         | Left errs =>
300 |             pure (Left errs)
301 |       let produced' : Nat
302 |           produced' = produced result
303 |       Right chunks' <-
304 |         prependProduced
305 |           "Codec.Compression.Zlib.Stream.finishCompressor.finish"
306 |           produced'
307 |           output
308 |           chunks
309 |         | Left errs =>
310 |             pure (Left errs)
311 |       case status result of
312 |         1          =>
313 |           pure
314 |             ( Right
315 |                 ( MkCompressStreamResult
316 |                     0
317 |                     (reverse chunks')
318 |                     True
319 |                 )
320 |             )
321 |         0          =>
322 |           assert_total (finish chunks')
323 |         (-5)       =>
324 |           case produced' of
325 |             0 => do
326 |               errs <- mkError "Codec.Compression.Zlib.Stream.finishCompressor.finish"
327 |                               "deflate made no progress while finishing the stream"
328 |               pure (Left errs)
329 |             _ =>
330 |               assert_total (finish chunks')
331 |         unexpected => do
332 |           errs <- mkError "Codec.Compression.Zlib.Stream.finishCompressor.finish"
333 |                           ( "Unexpected deflate status while finishing: "
334 |                               ++ show unexpected
335 |                           )
336 |           pure (Left errs)
337 |
338 | --------------------------------------------------------------------------------
339 | --          Streaming Decompression
340 | --------------------------------------------------------------------------------
341 |
342 | ||| Feed a compressed input chunk into an incremental decompressor.
343 | |||
344 | ||| The function processes as much input as possible and returns zero or more
345 | ||| decompressed output chunks.
346 | |||
347 | ||| `consumed` indicates exactly how many bytes from the supplied input were
348 | ||| consumed. If `finished` is true and `consumed` is smaller than the input
349 | ||| size, the remaining bytes follow the compressed stream and are left for
350 | ||| the caller.
351 | |||
352 | export
353 | decompressChunk :  {n : Nat}
354 |                 -> StreamingDecompressor
355 |                 -> IBuffer n
356 |                 -> IO (Either (List ZlibError) DecompressStreamResult)
357 | decompressChunk (MkStreamingDecompressor decompressor) input =
358 |   go 0 (zeroLTE n) []
359 |   where
360 |     mutual
361 |       continue :  Nat
362 |                -> Nat
363 |                -> Nat
364 |                -> List AnyBuffer
365 |                -> IO (Either (List ZlibError) DecompressStreamResult)
366 |       continue consumed' produced' nextoffset chunks' =
367 |         case isLTE nextoffset n of
368 |           No _           => do
369 |             errs <- mkError "Codec.Compression.Zlib.Stream.decompressChunk.continue"
370 |                             "inflate reported consuming bytes beyond the supplied input"
371 |             pure (Left errs)
372 |           Yes nextbounds =>
373 |             case nextoffset < n of
374 |               True  =>
375 |                 assert_total (go nextoffset nextbounds chunks')
376 |               False =>
377 |                 -- All currently supplied input has been consumed.  If the
378 |                 -- output buffer filled completely, inflate may still have
379 |                 -- output pending that can be emitted without additional
380 |                 -- input.
381 |                 case produced' == streamchunksize of
382 |                   True  =>
383 |                     assert_total (go nextoffset nextbounds chunks')
384 |                   False =>
385 |                     pure
386 |                       ( Right
387 |                           ( MkDecompressStreamResult
388 |                               nextoffset
389 |                               (reverse chunks')
390 |                               False
391 |                           )
392 |                       )
393 |       go :  (inputoffset : Nat)
394 |          -> (0 offsetbounds : LTE inputoffset n)
395 |          -> List AnyBuffer
396 |          -> IO (Either (List ZlibError) DecompressStreamResult)
397 |       go inputoffset offsetbounds chunks = do
398 |         let inputlength : Nat
399 |             inputlength = n `minus` inputoffset
400 |         output          <- mbuffer streamchunksize
401 |         Right result    <-
402 |           inflateBuffer
403 |             decompressor
404 |             inputoffset
405 |             inputlength
406 |             input
407 |             {inputbounds = plusMinusLTE inputoffset n offsetbounds}
408 |             0
409 |             streamchunksize
410 |             output
411 |             {outputbounds = zeroOffsetInBounds streamchunksize}
412 |             NoFlush
413 |           | Left errs =>
414 |               pure (Left errs)
415 |         let consumed'  : Nat
416 |             consumed'  = consumed result
417 |             produced'  : Nat
418 |             produced'  = produced result
419 |             nextoffset : Nat
420 |             nextoffset = inputoffset + consumed'
421 |         Right chunks'  <-
422 |           prependProduced
423 |             "Codec.Compression.Zlib.Stream.decompressChunk.go"
424 |             produced'
425 |             output
426 |             chunks
427 |           | Left errs =>
428 |               pure (Left errs)
429 |         case status result of
430 |           1          =>
431 |             pure
432 |               ( Right
433 |                   ( MkDecompressStreamResult
434 |                       nextoffset
435 |                       (reverse chunks')
436 |                       True
437 |                   )
438 |               )
439 |           0          =>
440 |             continue consumed' produced' nextoffset chunks'
441 |           (-5)       =>
442 |             case consumed' == 0 && produced' == 0 of
443 |               True =>
444 |                 -- No progress with the current input is not an error for an
445 |                 -- incremental decompressor.  The caller can supply more bytes.
446 |                 pure
447 |                   ( Right
448 |                       ( MkDecompressStreamResult
449 |                           nextoffset
450 |                           (reverse chunks')
451 |                           False
452 |                       )
453 |                   )
454 |               False =>
455 |                 continue consumed' produced' nextoffset chunks'
456 |           unexpected => do
457 |             errs <- mkError "Codec.Compression.Zlib.Stream.decompressChunk.go"
458 |                             ( "Unexpected inflate status: "
459 |                                 ++ show unexpected
460 |                             )
461 |             pure (Left errs)
462 |