0 | module Codec.Compression.Zlib.Internal
  1 |
  2 | import Codec.Compression.Zlib.Types
  3 | import Codec.Compression.Zlib.Utilities
  4 | import Control.Monad.Elin
  5 | import Control.Monad.MCancel
  6 | import Data.Buffer
  7 | import Data.Buffer.Core
  8 | import Data.Linear.Token
  9 | import System.Posix.Timer
 10 | import System.Posix.Timer.Prim
 11 | import System.FFI
 12 | import System.Zlib.Constant
 13 | import System.Zlib.Error
 14 | import System.Zlib.Types
 15 | import System.Zlib.Raw
 16 |
 17 | %default total
 18 |
 19 | --------------------------------------------------------------------------------
 20 | --          Stream Lifecycle
 21 | --------------------------------------------------------------------------------
 22 |
 23 | ||| Allocate and initialize a zlib compression stream.
 24 | |||
 25 | ||| If initialization fails, the native stream allocation is released before
 26 | ||| returning the error. A successful result therefore represents a fully
 27 | ||| initialized stream that must later be destroyed with `destroyCompressor`.
 28 | |||
 29 | export
 30 | createCompressor :  ZlibCompressionLevel
 31 |                  -> Wrapper
 32 |                  -> IO (Either (List ZlibError) Compressor)
 33 | createCompressor level wrapper = do
 34 |   ptr    <- primIO prim__newStream
 35 |   status <- primIO ( prim__deflateInit2
 36 |                      ptr
 37 |                      (zlibCompressionLevelValue level)
 38 |                      (zlibconstantToInt Z_DEFLATED)
 39 |                      (windowBits wrapper)
 40 |                      (zlibconstantToInt Z_DEFAULT_MEM_LEVEL)
 41 |                      (strategyValue DefaultStrategy)
 42 |                    )
 43 |   case status == (zlibconstantToInt Z_OK) of
 44 |     True  =>
 45 |       pure (Right (MkCompressor (MkZStreamHandle ptr)))
 46 |     False => do
 47 |       -- deflateInit2 did not successfully initialize the stream, so there is
 48 |       -- no initialized zlib state to finalize with deflateEnd. We only release
 49 |       -- the allocation owned by our shim.
 50 |       primIO (prim__freeStream ptr)
 51 |       err <- statusError "Codec.Compression.Zlib.Internal.createCompressor" status
 52 |       pure (Left err)
 53 |
 54 | ||| Finalize and release a zlib compression stream.
 55 | |||
 56 | ||| `deflateEnd` releases resources owned internally by zlib, after which
 57 | ||| `prim__freeStream` releases the opaque stream allocation owned by the
 58 | ||| C shim.
 59 | |||
 60 | ||| This function is intended primarily as the release action used by
 61 | ||| `withCompressor`.
 62 | |||
 63 | export
 64 | destroyCompressor :  Compressor
 65 |                   -> IO ()
 66 | destroyCompressor (MkCompressor (MkZStreamHandle ptr)) = do
 67 |   _ <- primIO $ prim__deflateEnd ptr
 68 |   primIO $ prim__freeStream ptr
 69 |
 70 | ||| Allocate and initialize a zlib decompression stream.
 71 | |||
 72 | ||| If initialization fails, the native stream allocation is released before
 73 | ||| returning the error. A successful result therefore represents a fully
 74 | ||| initialized stream that must later be destroyed with
 75 | ||| `destroyDecompressor`.
 76 | |||
 77 | export
 78 | createDecompressor :  Wrapper
 79 |                    -> IO (Either (List ZlibError) Decompressor)
 80 | createDecompressor wrapper = do
 81 |   ptr    <- primIO prim__newStream
 82 |   status <- primIO (prim__inflateInit2 ptr (windowBits wrapper))
 83 |   case status == (zlibconstantToInt Z_OK) of
 84 |     True  =>
 85 |       pure (Right (MkDecompressor (MkZStreamHandle ptr)))
 86 |     False => do
 87 |       -- inflateInit2 did not successfully initialize the stream, so only the
 88 |       -- shim-owned stream allocation has to be released.
 89 |       primIO (prim__freeStream ptr)
 90 |       err <- statusError "Codec.Compression.Zlib.Internal.createDecompressor" status
 91 |       pure (Left err)
 92 |
 93 | ||| Finalize and release a zlib decompression stream.
 94 | |||
 95 | ||| `inflateEnd` releases resources owned internally by zlib, after which
 96 | ||| `prim__freeStream` releases the opaque stream allocation owned by the
 97 | ||| C shim.
 98 | |||
 99 | ||| This function is intended primarily as the release action used by
100 | ||| `withDecompressor`.
101 | |||
102 | export
103 | destroyDecompressor :  Decompressor
104 |                     -> IO ()
105 | destroyDecompressor (MkDecompressor (MkZStreamHandle ptr)) = do
106 |   _ <- primIO $ prim__inflateEnd ptr
107 |   primIO $ prim__freeStream ptr
108 |
109 | --------------------------------------------------------------------------------
110 | --          Safe Resource Combinators
111 | --------------------------------------------------------------------------------
112 |
113 | ||| Execute an action with a freshly initialized zlib compression stream.
114 | |||
115 | ||| The compressor is finalized and released regardless of how the protected
116 | ||| action exits. Failure to initialize the compressor is returned without
117 | ||| executing the supplied action.
118 | |||
119 | export
120 | withCompressor :  ZlibCompressionLevel
121 |                -> Wrapper
122 |                -> (Compressor -> IO (Either (List ZlibError) a))
123 |                -> IO (Either (List ZlibError) a)
124 | withCompressor level wrapper action = do
125 |   result <- runElinIO withCompressor'
126 |   case result of
127 |     Left err    => do
128 |       errs <- mkError "Codec.Compression.Zlib.Internal.withCompressor" "\{show err}"
129 |       pure (Left errs)
130 |     Right value =>
131 |       case value of
132 |         Left errs    =>
133 |           pure (Left errs)
134 |         Right value' =>
135 |           pure (Right value')
136 |   where
137 |     acquire : F1 World (Either (List ZlibError) Compressor)
138 |     acquire =
139 |       ioToF1 (createCompressor level wrapper)
140 |     use :  Either (List ZlibError) Compressor
141 |         -> F1 World (Either (List ZlibError) a)
142 |     use (Left err)         =
143 |       ioToF1 (pure (Left err))
144 |     use (Right compressor) =
145 |       ioToF1 (action compressor)
146 |     release :  Either (List ZlibError) Compressor
147 |             -> F1' World
148 |     release (Left _)           =
149 |       ioToF1 (pure ())
150 |     release (Right compressor) =
151 |       ioToF1 (destroyCompressor compressor)
152 |     withCompressor' : Elin World [] (Either (List ZlibError) a)
153 |     withCompressor' =
154 |       bracket (runIO acquire)
155 |               (\resource => runIO (use resource))
156 |               (\resource => runIO (release resource))
157 |
158 | ||| Execute an action with a freshly initialized zlib decompression stream.
159 | |||
160 | ||| The decompressor is finalized and released regardless of how the protected
161 | ||| action exits. Failure to initialize the decompressor is returned without
162 | ||| executing the supplied action.
163 | |||
164 | export
165 | withDecompressor :  Wrapper
166 |                  -> (Decompressor -> IO (Either (List ZlibError) a))
167 |                  -> IO (Either (List ZlibError) a)
168 | withDecompressor wrapper action = do
169 |   result <- runElinIO withDecompressor'
170 |   case result of
171 |     Left err    => do
172 |       errs <- mkError "Codec.Compression.Zlib.Internal.withCompressor" "\{show err}"
173 |       pure (Left errs)
174 |     Right value =>
175 |       case value of
176 |         Left errs    =>
177 |           pure (Left errs)
178 |         Right value' =>
179 |           pure (Right value')
180 |   where
181 |     acquire : F1 World (Either (List ZlibError) Decompressor)
182 |     acquire =
183 |       ioToF1 (createDecompressor wrapper)
184 |     use :  Either (List ZlibError) Decompressor
185 |         -> F1 World (Either (List ZlibError) a)
186 |     use (Left err)           =
187 |       ioToF1 (pure (Left err))
188 |     use (Right decompressor) =
189 |       ioToF1 (action decompressor)
190 |     release :  Either (List ZlibError) Decompressor
191 |             -> F1' World
192 |     release (Left _)             =
193 |       ioToF1 (pure ())
194 |     release (Right decompressor) =
195 |       ioToF1 (destroyDecompressor decompressor)
196 |     withDecompressor' : Elin World [] (Either (List ZlibError) a)
197 |     withDecompressor' =
198 |       bracket (runIO acquire)
199 |               (\resource => runIO (use resource))
200 |               (\resource => runIO (release resource))
201 |
202 | --------------------------------------------------------------------------------
203 | --          Buffer Operations
204 | --------------------------------------------------------------------------------
205 |
206 | private
207 | deflateBoundError : Bits64
208 | deflateBoundError = 0xffffffffffffffff
209 |
210 | ||| Compute an upper bound on the number of bytes required to compress an
211 | ||| input of the given size with an initialized compressor.
212 | |||
213 | ||| The returned capacity is sufficient for single-pass compression when the
214 | ||| complete input is supplied to `deflateBuffer` and the flush mode is
215 | ||| `Finish`. In that case, zlib guarantees that an output buffer of at least
216 | ||| this size is sufficient for `deflate` to complete with `Z_STREAM_END`.
217 | |||
218 | ||| This helper additionally enforces the size limits of the raw buffer bridge:
219 | ||| both the input length and resulting output capacity must fit in the
220 | ||| `uInt`-sized lengths used by zlib's `avail_in` and `avail_out` fields.
221 | |||
222 | ||| Returns an error when the requested input or resulting bound cannot be
223 | ||| represented safely by the one-shot buffer API.
224 | |||
225 | export
226 | deflateBound :  Compressor
227 |              -> Nat
228 |              -> IO (Either (List ZlibError) Nat)
229 | deflateBound (MkCompressor (MkZStreamHandle ptr)) size =
230 |   case size > 0xffffffff of
231 |     True =>
232 |       do
233 |         err <- mkError "Codec.Compression.Zlib.Internal.deflateBound"
234 |                        "Input is too large for the one-shot zlib buffer interface"
235 |         pure (Left err)
236 |     False => do
237 |       bound <- primIO (prim__deflateBound ptr (cast size))
238 |       case bound == deflateBoundError of
239 |         True => do
240 |           err <- mkError "Codec.Compression.Zlib.Internal.deflateBound"
241 |                          "Compressed-size bound cannot be represented by the one-shot zlib buffer interface"
242 |           pure (Left err)
243 |         False =>
244 |           pure (Right (cast bound))
245 |
246 | ||| Compress a region of an immutable input buffer into a region of a mutable
247 | ||| output buffer.
248 | |||
249 | ||| Neither buffer is copied before crossing the FFI boundary. On the Chez
250 | ||| backend, their underlying bytevectors are borrowed as `u8*` values for
251 | ||| the duration of the atomic C call.
252 | |||
253 | ||| The C shim guarantees that the borrowed pointers are removed from the
254 | ||| underlying `z_stream` before returning.
255 | |||
256 | ||| The returned `BufferResult` reports how many input bytes were consumed
257 | ||| and how many output bytes were produced.
258 | |||
259 | export
260 | deflateBuffer :  Compressor
261 |               -> (inputoffset : Nat)
262 |               -> (inputlength : Nat)
263 |               -> IBuffer n
264 |               -> {auto 0 inputbounds : LTE (inputoffset + inputlength) n}
265 |               -> (outputoffset : Nat)
266 |               -> (outputlength : Nat)
267 |               -> IOBuffer m
268 |               -> {auto 0 outputbounds : LTE (outputoffset + outputlength) m}
269 |               -> FlushMode
270 |               -> IO (Either (List ZlibError) BufferResult)
271 | deflateBuffer (MkCompressor (MkZStreamHandle ptr)) inputoffset inputlength input outputoffset outputlength output flush = do
272 |   status <- primIO ( prim__deflateBuffer
273 |                        ptr
274 |                        (unsafeGetBuffer input)
275 |                        (cast inputoffset)
276 |                        (cast inputlength)
277 |                        (unsafeFromMBuffer output)
278 |                        (cast outputoffset)
279 |                        (cast outputlength)
280 |                        (flushModeValue flush)
281 |                    )
282 |   consumed <- primIO (prim__consumed ptr)
283 |   produced <- primIO (prim__produced ptr)
284 |   case status == (zlibconstantToInt Z_OK) || status == (zlibconstantToInt Z_STREAM_END) || status == (zlibconstantToInt Z_BUF_ERROR) of
285 |     True  =>
286 |       pure (Right (MkBufferResult status (cast consumed) (cast produced)))
287 |     False => do
288 |       err <- statusError "Codec.Compression.Zlib.Internal.deflateBuffer" status
289 |       pure (Left err)
290 |
291 | ||| Decompress a region of an immutable input buffer into a region of a mutable
292 | ||| output buffer.
293 | |||
294 | ||| Neither buffer is copied before crossing the FFI boundary. On the Chez
295 | ||| backend, their underlying bytevectors are borrowed as `u8*` values for
296 | ||| the duration of the atomic C call.
297 | |||
298 | ||| The C shim guarantees that the borrowed pointers are removed from the
299 | ||| underlying `z_stream` before returning.
300 | |||
301 | ||| `Z_OK` indicates that decompression can continue. `Z_STREAM_END` indicates
302 | ||| that the complete compressed stream has been decoded. Both are represented
303 | ||| as successful `BufferResult` values; the caller can use the stream-oriented
304 | ||| operation when it needs to distinguish them.
305 | |||
306 | export
307 | inflateBuffer :  Decompressor
308 |               -> (inputoffset : Nat)
309 |               -> (inputlength : Nat)
310 |               -> IBuffer n
311 |               -> {auto 0 inputbounds : LTE (inputoffset + inputlength) n}
312 |               -> (outputoffset : Nat)
313 |               -> (outputlength : Nat)
314 |               -> IOBuffer m
315 |               -> {auto 0 outputbounds : LTE (outputoffset + outputlength) m}
316 |               -> FlushMode
317 |               -> IO (Either (List ZlibError) BufferResult)
318 | inflateBuffer (MkDecompressor (MkZStreamHandle ptr)) inputoffset inputlength input outputoffset outputlength output flush = do
319 |   status <- primIO ( prim__inflateBuffer
320 |                        ptr
321 |                        (unsafeGetBuffer input)
322 |                        (cast inputoffset)
323 |                        (cast inputlength)
324 |                        (unsafeFromMBuffer output)
325 |                        (cast outputoffset)
326 |                        (cast outputlength)
327 |                        (flushModeValue flush)
328 |                    )
329 |   consumed <- primIO (prim__consumed ptr)
330 |   produced <- primIO (prim__produced ptr)
331 |   case status == (zlibconstantToInt Z_OK) || status == (zlibconstantToInt Z_STREAM_END) || status == (zlibconstantToInt Z_BUF_ERROR) of
332 |     True  =>
333 |       pure (Right (MkBufferResult status (cast consumed) (cast produced)))
334 |     False => do
335 |       err <- statusError "Codec.Compression.Zlib.Internal.inflateBuffer" status
336 |       pure (Left err)
337 |