Skip to content

Instantly share code, notes, and snippets.

@maoe
Last active August 29, 2015 14:15
Show Gist options
  • Save maoe/2f835a207586f3758dc2 to your computer and use it in GitHub Desktop.
Save maoe/2f835a207586f3758dc2 to your computer and use it in GitHub Desktop.
Take n bytes of ByteString
import Data.ByteString (ByteString)
import Data.Iteratee
import qualified Data.ByteString as S
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Lazy as L
getByteStringN :: Monad m => Int -> Iteratee ByteString m ByteString
getByteStringN = liftI . step mempty
where
step b n chunk
| n <= 0 = idone (toBS b) chunk
step b n (Chunk bytes)
| len < n = liftI $ step (b <> fromBS bytes) (n - len)
| otherwise = idone
(toBS $ b <> fromBS (S.take n bytes))
(Chunk (S.drop n bytes))
where
len = S.length bytes
step _ _ (EOF Nothing) = throwErr $ toException EofException
step _ _ (EOF (Just e)) = throwErr e
fromBS = B.byteString
toBS = L.toStrict . B.toLazyByteString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment