Created
December 20, 2016 04:24
-
-
Save vaibhavsagar/81182bb360bfe45d4389b73c9a20168d to your computer and use it in GitHub Desktop.
Zlib decompression with leftovers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": { | |
"collapsed": true | |
}, | |
"outputs": [], | |
"source": [ | |
"{-# LANGUAGE OverloadedStrings #-}\n", | |
"\n", | |
"import qualified Codec.Compression.Zlib as Z\n", | |
"import qualified Codec.Compression.Zlib.Internal as ZI\n", | |
"import qualified Data.ByteString as B\n", | |
"import qualified Data.ByteString.Lazy as L" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 7, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": [ | |
"(\"hello\",\"hi\")" | |
] | |
}, | |
"metadata": {}, | |
"output_type": "display_data" | |
} | |
], | |
"source": [ | |
"import qualified Control.Monad.ST.Lazy as ST\n", | |
"\n", | |
"ch = Z.compress \"hello\"\n", | |
"input = ch `L.append` \"hi\"\n", | |
"\n", | |
"run :: Monad m => ZI.DecompressStream m -> L.ByteString -> m (B.ByteString, L.ByteString)\n", | |
"run _ \"\" = return (\"\",\"\")\n", | |
"run (ZI.DecompressInputRequired supply) input = do\n", | |
" let (c:cs) = L.toChunks input\n", | |
" let cs' = L.fromChunks cs\n", | |
" supplied <- supply c\n", | |
" case supplied of\n", | |
" ZI.DecompressOutputAvailable output next -> do\n", | |
" next' <- next\n", | |
" (rest, remainder) <- run next' cs'\n", | |
" return (B.append output rest, remainder)\n", | |
" _ -> run supplied cs'\n", | |
"run (ZI.DecompressStreamEnd remainder) input =\n", | |
" return (\"\", L.fromStrict remainder `L.append` input)\n", | |
"run (ZI.DecompressStreamError err) _ =\n", | |
" error $ show err\n", | |
"\n", | |
"decompress :: L.ByteString -> (B.ByteString, L.ByteString)\n", | |
"decompress lbs = let\n", | |
" decompressor = ZI.decompressST ZI.zlibFormat ZI.defaultDecompressParams\n", | |
" in ST.runST $ run decompressor lbs\n", | |
"\n", | |
"decompress input" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Haskell", | |
"language": "haskell", | |
"name": "haskell" | |
}, | |
"language_info": { | |
"codemirror_mode": "ihaskell", | |
"file_extension": ".hs", | |
"name": "haskell", | |
"version": "7.10.3" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment