我实现了读取ByteString并以十六进制格式转换它的函数.例如,给定"AA10",它将其转换为[170,16]
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.Internal as BS (w2c)
rHex :: BSL.ByteString -> BSL.ByteString
rHex bs
| BSL.null bs = BSL.empty
| BSL.null rest' = fromHex c1 `BSL.cons` BSL.empty
| otherwise = rChunk c1 c2 `BSL.cons` rHex rest
where (c1, rest') = (BSL.head bs, BSL.tail bs)
(c2, rest) = (BSL.head rest', BSL.tail rest')
rChunk c1 c2 = (fromHex c1) * 16 + fromHex c2
fromHex = fromIntegral . digitToInt . BS.w2c
Run Code Online (Sandbox Code Playgroud)
但是我意识到我需要相同的功能但是对于简单的ByteString,而不是Lazy.我遇到的唯一方法是这样的:
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BS (w2c)
rHex' funcs@(null, empty, cons, head, tail, fromHex) bs
| null bs = empty
| null rest' = fromHex c1 `cons` empty
| otherwise = rChunk c1 c2 `cons` rHex' funcs rest
where (c1, rest') = (head bs, tail bs)
(c2, rest) = (head rest', tail rest')
rChunk c1 c2 = (fromHex c1) * 16 + fromHex c2
fromHex = fromIntegral . digitToInt . BS.w2c
rHexBSL :: BSL.ByteString -> BSL.ByteString
rHexBSL = rHex' (BSL.null, BSL.empty, BSL.cons, BSL.head, BSL.tail, fromHex)
rHexBS :: BS.ByteString -> BS.ByteString
rHexBS = rHex' (BS.null, BS.empty, BS.cons, BS.head, BS.tail, fromHex)
Run Code Online (Sandbox Code Playgroud)
所以我直接rHex'在函数中传递所有需要的函数rHexBSL rHexBS.是否有更多的Haskell方法为Bytestring和Bytestring.Lazy创建一个通用函数?也许创建类型类或什么?
我将通过使用[Word8]和使用pack每种unpack类型的 ByteString 来简化这一点,以获得您想要的东西 - 例如:
toHex :: Word8 -> Word8 -> Word8
toHex a b = (fromHex a) * 16 + fromHex b
hexify :: [Word8] -> [Word8] -> [Word8]
hexify (a:b:cs) = toHex a b : hexify cs
hexify [b] = toHex 0 b
hexify [] = []
rHexBSL :: BSL.ByteString -> BSL.ByteString
rHexBSL = BSL.pack . hexify . BSL.unpack
rHexBS :: BS.ByteString -> BS.ByteString
rHexBS = BS.pack . hexify . BS.unpack
Run Code Online (Sandbox Code Playgroud)
我认为这样做很有可能实现融合,从而提高运营效率。
也就是说,看看 Bryan 如何在他的base16-bytestring` 包中做到这一点是有启发性的。