I have a String x which may or may not be gzip-compressed. Using the zlib library, I want to try decompressing x -- if it succeeds, the function shall return the compressed String. If not (i.e. x is not gzip-compressed) I want to simply return x.
As GZip.decompress generates an error if applied to a non-gzip string, I could use catch or similar, but I'm specifically asking for a solution that uses the zlib error handling mechanism.
How can I write a function, say decompressIfPossible :: ByteString -> ByteString that has the previously described characteristics? I'd prefer a Either String ByteString to represent either the error or the decompression result.
Note: This question intentionally does not show research effort, as it was immediately answered in a Q&A-style manner.
The function from
zlibyou need to use here is calleddecompressWithErrors. Its value is the recursiveDecompressStreamdata structure that you can fold to aByteStringusingv:fromDecompressStreamHere's a full example of how to write the function you asked for:
Note that this example uses
gzipOrZlibFormatwhich automatically detects if the header is a zlib or a gzip header.