Last active
August 29, 2015 14:15
-
-
Save maoe/2f835a207586f3758dc2 to your computer and use it in GitHub Desktop.
Take n bytes of ByteString
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
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