Parse fixed length strings with elm/parser

Hi! I’m trying to use elm/parser to parse fixed length strings. This is what I have come up with so far:

cString : Int -> Parser String
cString length =
    getChompedString <|
        loop 0 (helper length)

helper : Int -> Int -> Parser (Step Int Int)
helper length count =
    if length == count then
        succeed () |> map (\_ -> Done count)

        succeed (Loop (count + 1))
            |. chompIf (\_ -> True)

Is there a better way? If the name “cString” didn’t give at away already, I’m abusing elm/parser to parse a binary file. The file contents sit in a String, where I have made sure every Char code is below 256. So far it works very well.

I think your way is the correct one for parsing a known-length string.

But there is the elm/bytes package that is made for decoding binary data. Maybe that is a better fit for your problem? (the general approach would still be the same: use loop to count the correct number of characters)

1 Like

Thanks for the pointer. I actually ended up using zwilias/elm-bytes-parser, which gives mostly the same functionality as elm/parser. It does not have the nice |. and |= operators, but those I can add myself.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.