5

I wrote this code snippet to read a file that may be compressed:

import Codec.Compression.GZip
import IO -- using IO.try

read file = do
  let f = L.readFile file
  let c = fmap decompress $ f

  unzipped <- try c

  case unzipped of
    Right b -> return b
    Left  _ -> f

It compiles just fine, but it seems that this is no valid way to handle uncompressed files. Running the code on a compressed file works nice, but a uncompressed file fails with an exception:

*** Exception: Codec.Compression.Zlib: incorrect header check

Any idea on how to make this possible?

2

2 Answers 2

4

You need to import Codec.Compression.Zlib.Internal. Note in particular the section titled “Low-level API to get explicit error reports”.

You will want to use something like this (note untested):

import qualified Codec.Compression.Zlib.Internal as Z
import Control.Arrow (right)

decompressWithoutExceptions :: L.ByteString -> Either Z.DecompressError L.ByteString
decompressWithoutExceptions = finalise
                            . Z.foldDecompressStream cons nil err
                            . Z.decompressWithErrors Z.gzipFormat Z.defaultDecompressParams
  where err errorCode errorString = Left errorCode
        nil = Right []
        cons chunk = right (chunk :)
        finalise = right L.fromChunks

(I presume you have imported Data.ByteString.Lazy qualified as L.)

3
  • Never mind that, does it work?! (Which bits do you not understand? decompressWithErrors and foldDecompressStream, etc are explained (perhaps not clearly enough?) in the documentation I linked to.)
    – dave4420
    Apr 13, 2012 at 19:30
  • Where does this finalise method come from? I didn't find it via hayoo.
    – fho
    Apr 16, 2012 at 11:44
  • finalise is defined in the last line. It's purpose is to convert the result from type Either Z.DecompressError [Data.ByteString.ByteString] to Either Z.DecompressError L.ByteString (i.e. converting the "success" type from a list of strict bytestrings to a single lazy bytestring).
    – dave4420
    Apr 16, 2012 at 11:46
2

You might want to look at spoon, which will allow you to get Nothing if an exception was thrown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.