module Codec.Compression.LZF (compress,decompress,compressString,decompressString) where
import Data.Char(ord,chr)
import Control.Monad (when)
import Foreign
import Foreign.C
foreign import ccall unsafe "lzf_compress" _compress :: Ptr a -> CUInt -> Ptr b -> CUInt -> IO CUInt
foreign import ccall unsafe "lzf_decompress" _decompress :: Ptr a -> CUInt -> Ptr b -> CUInt -> IO CUInt
compress :: Ptr a -> Int -> Ptr b -> Int -> IO Int
compress input ilen output olen = do
res <- _compress input (fromIntegral ilen) output (fromIntegral olen)
return (fromIntegral res)
decompress :: Ptr a -> Int -> Ptr b -> Int -> IO Int
decompress input ilen output olen = do
res <- _decompress input (fromIntegral ilen) output (fromIntegral olen)
return (fromIntegral res)
compressString :: String -> IO String
compressString str =
withCStringLen str $ \(inp,len) ->
allocaBytes len $ \out -> do
res <- compress inp len out (len2)
if res == 0 then return ("\0"++str)
else do c <- peekCStringLen (out,res)
return (chr len:c)
decompressString :: String -> IO String
decompressString ('\0':rest) = return rest
decompressString (ol:str) =
withCStringLen str $ \(inp,len) -> do
let olen = ord ol
allocaBytes olen $ \out -> do
res <- decompress inp len out olen
when (res == 0) $ fail "Codec.Compression.LZF.decompressString"
peekCStringLen (out,res)