0 | module Codec.Compression.Zlib.Decompress
  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.Array.Index
  7 | import Data.Buffer
  8 | import Data.Buffer.Builder
  9 | import Data.Buffer.Core
 10 | import Data.Nat
 11 | import System.Zlib.Constant
 12 | import System.Zlib.Error
 13 | import System.Zlib.Types
 14 |
 15 | %default total
 16 |
 17 | --------------------------------------------------------------------------------
 18 | --          Constants
 19 | --------------------------------------------------------------------------------
 20 |
 21 | ||| Number of output bytes allocated for each decompression step.
 22 | |||
 23 | ||| Decompression cannot generally determine the final uncompressed size in
 24 | ||| advance, so output is produced incrementally into fixed-size chunks and
 25 | ||| concatenated after `Z_STREAM_END` is reached.
 26 | |||
 27 | private
 28 | inflatechunksize : Nat
 29 | inflatechunksize = 32768
 30 |
 31 | --------------------------------------------------------------------------------
 32 | --          Decompression
 33 | --------------------------------------------------------------------------------
 34 |
 35 | ||| Decompress an immutable byte buffer using the requested wrapper format.
 36 | |||
 37 | ||| Decompression is performed incrementally because the final uncompressed
 38 | ||| size cannot generally be determined before decoding.
 39 | |||
 40 | ||| Each iteration allocates a fixed-size output buffer, calls `inflate`, and
 41 | ||| retains only the prefix actually produced by zlib. Input consumption is
 42 | ||| tracked using the `consumed` count returned by `inflateBuffer`, allowing
 43 | ||| subsequent calls to continue from the correct offset without copying or
 44 | ||| slicing the compressed input.
 45 | |||
 46 | ||| Output chunks are accumulated until zlib returns `Z_STREAM_END`, after
 47 | ||| which they are concatenated into a single `AnyBuffer`.
 48 | |||
 49 | ||| Input and output buffers cross the Chez/C boundary without intermediate
 50 | ||| copies. The C shim borrows their underlying bytevectors only for the
 51 | ||| duration of each `inflate` call.
 52 | |||
 53 | export
 54 | decompressWith :  {n : Nat}
 55 |                -> Wrapper
 56 |                -> IBuffer n
 57 |                -> IO (Either (List ZlibError) AnyBuffer)
 58 | decompressWith wrapper input =
 59 |   withDecompressor wrapper $ \decompressor =>
 60 |     go decompressor 0 (zeroLTE n) []
 61 |   where
 62 |     go :  Decompressor
 63 |        -> (inputoffset : Nat)
 64 |        -> (0 offsetbounds : LTE inputoffset n)
 65 |        -> List AnyBuffer
 66 |        -> IO (Either (List ZlibError) AnyBuffer)
 67 |     go decompressor inputoffset offsetbounds chunks = do
 68 |       let inputlength : Nat
 69 |           inputlength = n `minus` inputoffset
 70 |       output       <- mbuffer inflatechunksize
 71 |       Right result <-
 72 |         inflateBuffer
 73 |           decompressor
 74 |           inputoffset
 75 |           inputlength
 76 |           input
 77 |           {inputbounds = plusMinusLTE inputoffset n offsetbounds}
 78 |           0
 79 |           inflatechunksize
 80 |           output
 81 |           {outputbounds = zeroOffsetInBounds inflatechunksize}
 82 |           NoFlush
 83 |         | Left errs =>
 84 |             pure (Left errs)
 85 |       let consumed'   : Nat
 86 |           consumed'   = consumed result
 87 |           produced'   : Nat
 88 |           produced'   = produced result
 89 |           nextoffset  : Nat
 90 |           nextoffset  = inputoffset + consumed'
 91 |           chunkresult : IO (Either (List ZlibError) (List AnyBuffer))
 92 |           chunkresult =
 93 |             case produced' of
 94 |               0 =>
 95 |                 pure (Right chunks)
 96 |               _ =>
 97 |                 case isLTE produced' inflatechunksize of
 98 |                   No _               => do
 99 |                     errs <- mkError "Codec.Compression.Zlib.Decompress.decompressWith.go"
100 |                                     "inflate reported producing bytes beyond the output buffer"
101 |                     pure (Left errs)
102 |                   Yes producedBounds => do
103 |                     frozen <- freezeOutput produced' output {bounds = producedBounds}
104 |                     pure (Right (frozen :: chunks))
105 |       Right chunks' <- chunkresult
106 |         | Left errs =>
107 |             pure (Left errs)
108 |       case status result == (zlibconstantToInt Z_STREAM_END) of
109 |         True  =>
110 |           pure
111 |             ( Right
112 |                (fastConcat
113 |                  (reverse chunks'))
114 |             )
115 |         False =>
116 |           case consumed' == 0 && produced' == 0 of
117 |             True  => do
118 |               errs <- mkError "Codec.Compression.Zlib.Decompress.decompressWith.go"
119 |                               "inflate made no progress: no input bytes were consumed and no output bytes were produced"
120 |               pure (Left errs)
121 |             False =>
122 |               case isLTE nextoffset n of
123 |                 Yes nextbounds =>
124 |                   assert_total (go decompressor nextoffset nextbounds chunks')
125 |                 No _ => do
126 |                   errs <- mkError "Codec.Compression.Zlib.Decompress.decompressWith.go"
127 |                                   ( "inflate reported consuming bytes beyond the input buffer: "
128 |                                       ++ show nextoffset
129 |                                       ++ " > "
130 |                                       ++ show n
131 |                                   )
132 |                   pure (Left errs)
133 |
134 | --------------------------------------------------------------------------------
135 | --          Convenience Operations
136 | --------------------------------------------------------------------------------
137 |
138 | ||| Decompress an immutable byte buffer containing a standard zlib stream.
139 | |||
140 | export
141 | decompress :  {n : Nat}
142 |            -> IBuffer n
143 |            -> IO (Either (List ZlibError) AnyBuffer)
144 | decompress =
145 |   decompressWith ZlibWrapper
146 |
147 | ||| Decompress an immutable byte buffer containing a gzip stream.
148 | |||
149 | export
150 | gzipDecompress :  {n : Nat}
151 |                -> IBuffer n
152 |                -> IO (Either (List ZlibError) AnyBuffer)
153 | gzipDecompress =
154 |   decompressWith GZipWrapper
155 |
156 | ||| Decompress an immutable byte buffer containing a raw DEFLATE stream with
157 | ||| no zlib or gzip wrapper.
158 | |||
159 | export
160 | rawDecompress :  {n : Nat}
161 |               -> IBuffer n
162 |               -> IO (Either (List ZlibError) AnyBuffer)
163 | rawDecompress =
164 |   decompressWith RawWrapper
165 |