对于一个网络协议,我需要能够从Source m ByteString
. 有lines
组合器,它将输入拆分为行,但我需要能够组合读取行和固定数量的字节。
我目前的方法是创建一个辅助函数:
| 在输入上折叠给定的函数。在函数返回时重复并将
Left
其结果累积到一个列表中。当函数返回时Right
,连接累积的结果(包括最后一个)并返回它,使用leftover
.Nothing
如果没有可用的输入则返回。
chunk :: (Monad m, Monoid a)
=> (s -> i -> Either (a, s) (a, i))
-> s
-> Consumer i m (Maybe a)
chunk f = loop []
where
loop xs s = await >>= maybe (emit xs) (go xs s)
go xs s i = case f s i of
Left (x, s') -> loop (x : xs) s'
Right (x, l) -> leftover l >> emit (x : xs)
emit [] = return Nothing
emit xs = return (Just . mconcat . L.reverse $ xs)
-- Note: We could use `mappend` to combine the chunks directly. But this would
-- often get us O(n^2) complexity (like for `ByteString`s) so we keep a list of
-- the chunks and then use `mconcat`, which can be optimized by the `Monoid`.
使用此功能,我创建了特定的消费者:
bytes :: (Monad m) => Int -> Consumer ByteString m (Maybe ByteString)
bytes = chunk f
where
f n bs | n' > 0 = Left (bs, n')
| otherwise = Right $ BS.splitAt n bs
where n' = n - BS.length bs
line :: (Monad m) => Consumer ByteString m (Maybe ByteString)
line = chunk f ()
where
f _ bs = maybe (Left (bs, ()))
(\i -> Right $ BS.splitAt (i + 1) bs)
(BS.findIndex (== '\n') bs)
有没有更好的办法?我想这个问题一定已经在某个地方解决了。