import Prelude hiding (length, concat, splitAt)
import Data.ByteString.Lazy.Char8 (pack)
import Data.ByteString.Lazy (ByteString, length, copy, concat)
import Data.Binary (Word32)
import Data.Int (Int32)
import Data.Binary.Put (runPut, putWord32le)
import Data.Binary.Get (getWord32le)
import Pipes
import Pipes.ByteString (fromLazy, stdout, splitAt)
import qualified Pipes.ByteString as P (ByteString)
import Pipes.Parse (runStateT, evalStateT, drawAll, Parser)
import Pipes.Binary (decodeGet, DecodingError, decoded, decode)
import Control.Lens (view, zoom)
first :: ByteString
first = pack "foo"
second :: ByteString
second = pack "bar"
merge :: ByteString -> ByteString -> ByteString
merge a b = concat [lengthBS a, a, b]
where
lengthBS = runPut . putWord32le . fromIntegral . length
split :: Monad m => Producer P.ByteString m r ->
m (Either DecodingError
(Producer P.ByteString m (Producer P.ByteString m r)))
split p = do
(headerLen, p') <- runStateT (decodeGet getWord32le) p
return $ case headerLen of
Left err -> Left err
Right headerLen' -> Right $
view (splitAt $ fromIntegral $ (headerLen' :: Word32)) p'
decoder :: Parser P.ByteString IO ()
decoder = do
headerLen <- decode
lift $ print (headerLen :: Either DecodingError Word32)
case headerLen of
Left err -> lift $ print err
Right hLen -> parseRest
main :: IO ()
main = do
evalStateT decoder $ fromLazy (merge first second)