从 Haskell 中的 ByteStrings 解析各种整数的通用且有效的方法
Generic and efficient way to parse various kinds of integers from ByteStrings in Haskell
这是我能想到的,但我认为它不是很有效或安全:
import qualified Data.ByteString.Char8 as B8
convert2Int = read . B8.unpack
有更好的方法吗?我在库中找到了针对 Int
类型执行此操作的函数,但不适用于 Int32
、Int64
、Word64
等其他类型
最直接的方法可能是 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
那里还有一个decodeOrFail
,如果解码失败,它会产生一个Either
值。
P.S.: 我怎么知道 decode
适合你想要的类型?通过阅读 the list of Binary
instances.
我发现的另一种方法是使用 Attoparsec module:
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString as B
convertToIntegral :: (Integral a) => B.ByteString -> Either String a
convertToIntegral = parseOnly decimal
当然,这只适用于没有符号的字符串(不像“-3”和“+5”)。在这些情况下,可以使用 "signed" 而不是 "decimal"。
这是我能想到的,但我认为它不是很有效或安全:
import qualified Data.ByteString.Char8 as B8
convert2Int = read . B8.unpack
有更好的方法吗?我在库中找到了针对 Int
类型执行此操作的函数,但不适用于 Int32
、Int64
、Word64
等其他类型
最直接的方法可能是 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
那里还有一个decodeOrFail
,如果解码失败,它会产生一个Either
值。
P.S.: 我怎么知道 decode
适合你想要的类型?通过阅读 the list of Binary
instances.
我发现的另一种方法是使用 Attoparsec module:
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString as B
convertToIntegral :: (Integral a) => B.ByteString -> Either String a
convertToIntegral = parseOnly decimal
当然,这只适用于没有符号的字符串(不像“-3”和“+5”)。在这些情况下,可以使用 "signed" 而不是 "decimal"。