File: Base.hs

package info (click to toggle)
haskell-zstd 0.1.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,988 kB
  • sloc: ansic: 26,812; haskell: 1,085; makefile: 4
file content (396 lines) | stat: -rw-r--r-- 14,608 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in
-- the LICENSE file in the root directory of this source tree. An
-- additional grant of patent rights can be found in the PATENTS file
-- in the same directory.

-- |
-- Module      : Codec.Compression.Zstd.Base
-- Copyright   : (c) 2016-present, Facebook, Inc. All rights reserved.
--
-- License     : BSD3
-- Maintainer  : bryano@fb.com
-- Stability   : experimental
-- Portability : GHC
--
-- Mid-level bindings to the native zstd compression library.  These
-- bindings provide a little more safety and ease of use than the
-- lowest-level FFI bindings.  Unless you have highly specialized
-- needs, you should use the streaming or other higher-level APIs
-- instead.

module Codec.Compression.Zstd.Base
    (
    -- * One-shot functions
      compress
    , maxCLevel
    , decompress
    , getDecompressedSize

    -- ** Cheaper operations using contexts
    -- *** Compression
    , CCtx
    , withCCtx
    , compressCCtx

    -- *** Decompression
    , DCtx
    , withDCtx
    , decompressDCtx

    -- * Streaming operations
    -- ** Streaming types
    , CStream
    , DStream
    , FFI.Buffer(..)
    , FFI.In
    , FFI.Out

    -- ** Streaming compression
    , cstreamInSize
    , cstreamOutSize
    , createCStream
    , initCStream
    , compressStream
    , endStream

    -- ** Streaming decompression
    , dstreamInSize
    , dstreamOutSize
    , createDStream
    , initDStream
    , decompressStream

    -- * Dictionary compression
    , trainFromBuffer
    , getDictID

    , compressUsingDict
    , decompressUsingDict

    -- ** Pre-digested dictionaries
    -- *** Compression
    , CDict
    , createCDict
    , compressUsingCDict

    -- *** Decompression
    , DDict
    , createDDict
    , decompressUsingDDict
    ) where

import Codec.Compression.Zstd.Base.Types (CDict(..), DDict(..))
import Codec.Compression.Zstd.FFI.Types (CCtx, DCtx)
import Control.Exception.Base (bracket)
import Data.Word (Word, Word64)
import Foreign.C.Types (CSize)
import Foreign.ForeignPtr (ForeignPtr, newForeignPtr, withForeignPtr)
import Foreign.Ptr (Ptr, castPtr)
import qualified Codec.Compression.Zstd.FFI as FFI

-- | Compress bytes from source buffer into destination buffer.
-- The destination buffer must be already allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
compress :: Ptr dst         -- ^ Destination buffer.
         -> Int             -- ^ Capacity of destination buffer.
         -> Ptr src         -- ^ Source buffer.
         -> Int             -- ^ Size of source buffer.
         -> Int             -- ^ Compression level.
         -> IO (Either String Int)
compress dst dstSize src srcSize level = checkError $
  FFI.compress dst (fromIntegral dstSize) src (fromIntegral srcSize)
               (fromIntegral level)

-- | The maximum compression level supported by the library.
maxCLevel :: Int
maxCLevel = fromIntegral FFI.maxCLevel

-- | Decompress a buffer.  The destination buffer must be already
-- allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
decompress :: Ptr dst         -- ^ Destination buffer.
           -> Int             -- ^ Capacity of destination buffer.
           -> Ptr src         -- ^ Source buffer.
           -> Int
           -- ^ Size of compressed input.  This must be exact, so
           -- for example supplying the size of a buffer that is
           -- larger than the compressed input will cause a failure.
           -> IO (Either String Int)
decompress dst dstSize src srcSize = checkError $
  FFI.decompress dst (fromIntegral dstSize) src (fromIntegral srcSize)

-- | Returns the decompressed size of a compressed payload if known.
--
-- To discover precisely why a result is not known, follow up with
-- 'FFI.getFrameParams'.
getDecompressedSize :: Ptr src
                    -> Int
                    -> IO (Maybe Word64)
getDecompressedSize src srcSize = do
  ret <- FFI.getDecompressedSize src (fromIntegral srcSize)
  return $! if ret == 0
            then Nothing
            else Just (fromIntegral ret)

-- | Allocate a compression context, run an action that may reuse the
-- context as many times as it needs, then free the context.
withCCtx :: (Ptr CCtx -> IO a) -> IO a
withCCtx act =
  bracket (FFI.checkAlloc "withCCtx" FFI.createCCtx) FFI.freeCCtx act

-- | Compress bytes from source buffer into destination buffer.
-- The destination buffer must be already allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
compressCCtx :: Ptr CCtx    -- ^ Compression context.
             -> Ptr dst     -- ^ Destination buffer.
             -> Int         -- ^ Capacity of destination buffer.
             -> Ptr src     -- ^ Source buffer.
             -> CSize       -- ^ Size of source buffer.
             -> Int         -- ^ Compression level.
             -> IO (Either String Int)
compressCCtx cctx dstPtr dstSize srcPtr srcSize level = checkError $
  FFI.compressCCtx cctx dstPtr (fromIntegral dstSize)
                        srcPtr (fromIntegral srcSize)
                        (fromIntegral level)

-- | Allocate a decompression context, run an action that may reuse
-- the context as many times as it needs, then free the context.
withDCtx :: (Ptr DCtx -> IO a) -> IO a
withDCtx act =
  bracket (FFI.checkAlloc "withDCtx" FFI.createDCtx) FFI.freeDCtx act

-- | Decompress a buffer.  The destination buffer must be already
-- allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
decompressDCtx :: Ptr DCtx        -- ^ Decompression context.
               -> Ptr dst         -- ^ Destination buffer.
               -> Int             -- ^ Capacity of destination buffer.
               -> Ptr src         -- ^ Source buffer.
               -> Int
               -- ^ Size of compressed input.  This must be exact, so
               -- for example supplying the size of a buffer that is
               -- larger than the compressed input will cause a failure.
               -> IO (Either String Int)
decompressDCtx dctx dst dstSize src srcSize = checkError $
  FFI.decompressDCtx dctx dst (fromIntegral dstSize) src (fromIntegral srcSize)

-- | Recommended size for input buffer.
cstreamInSize :: Int
cstreamInSize = fromIntegral FFI.cstreamInSize

-- | Recommended size for output buffer.
cstreamOutSize :: Int
cstreamOutSize = fromIntegral FFI.cstreamOutSize

-- | A context for streaming compression.
newtype CStream = CS (ForeignPtr FFI.CStream)

-- | Create a 'CStream' value.  After use, this will eventually be
-- freed via a finalizer.
createCStream :: IO CStream
createCStream = do
  cs <- FFI.checkAlloc "createCStream" FFI.createCStream
  cfp <- newForeignPtr FFI.p_freeCStream cs
  return (CS cfp)

-- | Begin a new streaming compression operation.
initCStream :: CStream
            -> Int              -- ^ Compression level.
            -> IO (Either String ())
initCStream (CS cfp) level =
  fmap (fmap (const ())) $ checkError $ withForeignPtr cfp $ \cs ->
    FFI.initCStream cs (fromIntegral level)

-- | Consume part or all of an input.
compressStream :: CStream -> Ptr (FFI.Buffer FFI.Out) -> Ptr (FFI.Buffer FFI.In)
               -> IO (Either String Int)
compressStream (CS cfp) bi bo = checkError $
  withForeignPtr cfp $ \cs ->
    FFI.compressStream cs bi bo

-- | End a compression stream. This performs a flush and writes a
-- frame epilogue.
endStream :: CStream -> Ptr (FFI.Buffer FFI.Out) -> IO (Either String Int)
endStream (CS cfp) bo = checkError $
  withForeignPtr cfp $ \cs ->
    FFI.endStream cs bo

-- | Recommended size for input buffer.
dstreamInSize :: Int
dstreamInSize = fromIntegral FFI.dstreamInSize

-- | Recommended size for output buffer.
dstreamOutSize :: Int
dstreamOutSize = fromIntegral FFI.dstreamOutSize

-- | A context for streaming decompression.
newtype DStream = DS (ForeignPtr FFI.DStream)

-- | Create a streaming decompression context.  After use, this will
-- eventually be freed via a finalizer.
createDStream :: IO DStream
createDStream = do
  ds <- FFI.checkAlloc "createDStream" FFI.createDStream
  dfp <- newForeignPtr FFI.p_freeDStream ds
  return (DS dfp)

-- | Begin a new streaming decompression operation.
initDStream :: DStream
            -> IO (Either String ())
initDStream (DS dfp) =
  fmap (fmap (const ())) $ checkError $ withForeignPtr dfp FFI.initDStream

-- | Consume part or all of an input.
decompressStream :: DStream -> Ptr (FFI.Buffer FFI.Out)
                 -> Ptr (FFI.Buffer FFI.In) -> IO (Either String Int)
decompressStream (DS dfp) bi bo = checkError $
  withForeignPtr dfp $ \ds ->
    FFI.decompressStream ds bi bo

-- | Train a dictionary from a collection of samples.
-- Returns the number size of the resulting dictionary.
trainFromBuffer :: Ptr dict
                -- ^ Preallocated dictionary buffer.
                -> Int
                -- ^ Capacity of dictionary buffer.
                -> Ptr samples
                -- ^ Concatenated samples.
                -> Ptr Int
                -- ^ Array of sizes of samples.
                -> Int
                -- ^ Number of samples.
                -> IO (Either String Int)
trainFromBuffer dictPtr dictSize sampPtr sampSizes sampCount = checkError $
  FFI.trainFromBuffer dictPtr (fromIntegral dictSize)
                      sampPtr (castPtr sampSizes) (fromIntegral sampCount)

-- | Return the identifier for the given dictionary, or 'Nothing' if
-- not a valid dictionary.
getDictID :: Ptr dict -> Int -> IO (Maybe Word)
getDictID ptr size = do
  n <- FFI.getDictID ptr (fromIntegral size)
  return $! if n == 0
            then Nothing
            else Just (fromIntegral n)

-- | Compress bytes from source buffer into destination buffer.
-- The destination buffer must be already allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
compressUsingDict :: Ptr CCtx
                  -> Ptr dst         -- ^ Destination buffer.
                  -> Int             -- ^ Capacity of destination buffer.
                  -> Ptr src         -- ^ Source buffer.
                  -> Int             -- ^ Size of source buffer.
                  -> Ptr dict        -- ^ Dictionary.
                  -> Int             -- ^ Size of dictionary.
                  -> Int             -- ^ Compression level.
                  -> IO (Either String Int)
compressUsingDict ctx dst dstSize src srcSize dict dictSize level = checkError $
  FFI.compressUsingDict ctx dst (fromIntegral dstSize)
    src (fromIntegral srcSize) dict (fromIntegral dictSize) (fromIntegral level)

-- | Decompress a buffer.  The destination buffer must be already
-- allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
decompressUsingDict :: Ptr DCtx
                    -> Ptr dst         -- ^ Destination buffer.
                    -> Int             -- ^ Capacity of destination buffer.
                    -> Ptr src         -- ^ Source buffer.
                    -> Int
                    -- ^ Size of compressed input.  This must be exact, so
                    -- for example supplying the size of a buffer that is
                    -- larger than the compressed input will cause a failure.
                    -> Ptr dict        -- ^ Dictionary.
                    -> Int             -- ^ Size of dictionary.
                    -> IO (Either String Int)
decompressUsingDict ctx dst dstSize src srcSize dict dictSize = checkError $
  FFI.decompressUsingDict ctx dst (fromIntegral dstSize)
    src (fromIntegral srcSize) dict (fromIntegral dictSize)

-- | Create a pre-digested compression dictionary.  After use, this
-- will eventually be freed via a finalizer.
createCDict :: Ptr dict
            -- ^ Dictionary.
            -> Int
            -- ^ Size of dictionary.
            -> Int
            -- ^ Compression level.
            -> IO CDict
createCDict dict size level = do
  cd <- FFI.checkAlloc "createCDict" $
        FFI.createCDict dict (fromIntegral size) (fromIntegral level)
  fp <- newForeignPtr FFI.p_freeCDict cd
  return (CD fp)

-- | Compress bytes from source buffer into destination buffer, using
-- a pre-digested dictionary.  The destination buffer must be already
-- allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
compressUsingCDict
    :: Ptr CCtx    -- ^ Compression context.
    -> Ptr dst     -- ^ Destination buffer.
    -> Int         -- ^ Capacity of destination buffer.
    -> Ptr src     -- ^ Source buffer.
    -> Int         -- ^ Size of source buffer.
    -> CDict       -- ^ Dictionary.
    -> IO (Either String Int)
compressUsingCDict ctx dst dstSize src srcSize (CD fp) =
  checkError . withForeignPtr fp $ \ dict ->
  FFI.compressUsingCDict ctx dst (fromIntegral dstSize)
    src (fromIntegral srcSize) dict

-- | Create a pre-digested decompression dictionary.  After use, this
-- will eventually be freed via a finalizer.
createDDict :: Ptr dict
            -- ^ Dictionary.
            -> Int
            -- ^ Size of dictionary.
            -> IO DDict
createDDict dict size = do
  cd <- FFI.checkAlloc "createDDict" $
        FFI.createDDict dict (fromIntegral size)
  fp <- newForeignPtr FFI.p_freeDDict cd
  return (DD fp)

-- | Decompress bytes from source buffer into destination buffer,
-- using a pre-digested dictionary.  The destination buffer must be
-- already allocated.
--
-- Returns the number of bytes written into destination buffer, or an
-- error description if it fails.
decompressUsingDDict
    :: Ptr DCtx    -- ^ Compression context.
    -> Ptr dst     -- ^ Destination buffer.
    -> Int         -- ^ Capacity of destination buffer.
    -> Ptr src     -- ^ Source buffer.
    -> Int         -- ^ Size of source buffer.
    -> DDict       -- ^ Dictionary.
    -> IO (Either String Int)
decompressUsingDDict ctx dst dstSize src srcSize (DD fp) =
  checkError . withForeignPtr fp $ \ dict ->
  FFI.decompressUsingDDict ctx dst (fromIntegral dstSize)
    src (fromIntegral srcSize) dict

checkError :: IO CSize -> IO (Either String Int)
checkError act = do
  ret <- act
  return $! if FFI.isError ret
            then Left (FFI.getErrorName ret)
            else Right (fromIntegral ret)