Haskell Binary Parsing

戏子无情 提交于 2019-12-07 06:11:08

问题


I've been trying to implement a protocol parser in haskell and I'm pretty new to the language, especially when it comes to monads. I've been using binary-0.5.0.2 and have described the header and all the payloads of my protocol. the messages I'd like to parse look something like the following: header + (payload A, payload B, ..) where a field in the header specifies what type of payload the message has.

I have had success in parsing the first message in the bytestring, but am at a loss with how to go about reading the next messages, discarding the bytes that were read in processing the first message.

This might be rather vague, but I'd rather get input on a generalized parser than having my ugly code altered to work in this manner.

Thanks for the help


回答1:


Just use a sequence of parse operations and they will consume the input as they go along.

parseAll = do
    hdr <- parseHeader
    pa <- parsePayloadA
    pb <- parsePayloadB
    ...



回答2:


The second element of the tuple returned by runGetState from Data.Binary.Get is the remaining ByteString. You can simply keep applying your parser until you get an error or run out of bytes.



来源:https://stackoverflow.com/questions/5517620/haskell-binary-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!