我希望压缩应用程序的网络流量。
根据(最新的?) "Haskell Popularity Rankings",zlib似乎是一个相当流行的解决方案。zlib的接口使用ByteString
s:
compress :: ByteString -> ByteString
decompress :: ByteString -> ByteString
我使用的是常规String
,它们也是read
、show
和Network.Socket
使用的数据类型
sendTo :: Socket -> String -> SockAddr -> IO Int
recvFrom :: Socket -> Int -> IO (String, Int, SockAddr)
因此,为了压缩字符串,我需要某种方法将String
转换为ByteString
,反之亦然。在hoogle的帮助下,我发现:
Data.ByteString.Char8 pack :: String -> ByteString
尝试使用它:
Prelude Codec.Compression.Zlib Data.ByteString.Char8> compress (pack "boo")
<interactive>:1:10:
Couldn't match expected type `Data.ByteString.Lazy.Internal.ByteString'
against inferred type `ByteString'
In the first argument of `compress', namely `(pack "boo")'
In the expression: compress (pack "boo")
In the definition of `it': it = compress (pack "boo")
失败,因为(?)有不同类型的ByteString
?
所以基本上:
ByteString
有几种类型吗?什么类型?为什么?String
s转换为why的方法?顺便说一句,我发现它可以在Data.ByteString.Lazy.Char8
的ByteString
上运行,但我仍然很感兴趣。
发布于 2009-09-20 20:58:51
有两种类型的字节串:严格(在Data.Bytestring.Internal中定义)和惰性(在Data.Bytestring.Lazy.Internal中定义)。正如您所发现的,zlib使用惰性字节串。
发布于 2012-06-15 22:53:53
您要查找的函数是:
import Data.ByteString as BS
import Data.ByteString.Lazy as LBS
lazyToStrictBS :: LBS.ByteString -> BS.ByteString
lazyToStrictBS x = BS.concat $ LBS.toChunks x
我希望它可以在没有x的情况下写得更简洁(即无指针,但我是Haskell的新手)。
发布于 2009-09-20 19:41:14
一种更有效的机制可能是切换到基于全字节串的层:
字串套接字的
https://stackoverflow.com/questions/1451755
复制相似问题