Search code examples
parsinghaskellbytestring

Generic and efficient way to parse various kinds of integers from ByteStrings in Haskell


Here's what I could come up with but I don't think it's very efficient or safe:

import qualified Data.ByteString.Char8 as B8

convert2Int = read . B8.unpack

Is there a better way to do this? I found functions in libraries that do it for the Int type, but not for other types like Int32, Int64, Word64, etc.


Solution

  • The most straightforward way is probably decode from Data.Binary:

    import qualified Data.ByteString.Lazy as BL
    import Data.Binary (decode)
    
    convertToIntegral :: (Binary a, Integral a) => BL.ByteString -> a
    convertToIntegral = decode
    

    There is also a decodeOrFail there, which produces an Either value if the decoding fails.

    P.S.: How do I know that decode will work for the types you want? By reading the list of Binary instances.