如何转换ByteString和Storable Vector? [英] How to convert between ByteString and Storable Vector?

查看:115
本文介绍了如何转换ByteString和Storable Vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Storable.Vector Word8 和一个严格的 ByteString

之间进行转换的最佳方法是什么?

当然,一个非复制(无操作)的方式将非常感激。



我应该只是 unsafeCoerce 还是有一个库函数(我找不到)?

另外,方法是否相同对于 Unboxed.Vector Word8

解决方案简单的 unsafeCoerce 将不起作用,因为数据构造函数的布局不同:

  data StorableArray ie = StorableArray!i!i Int!(ForeignPtr e)

vs。

  data ByteString = PS { - #UNPACK# - }!(ForeignPtr Word8) - 有效载荷
{ - #UNPACK# - }! Int - offset
{ - #UNPACK# - }!Int - length

你可以导入 Data.Arr ay.Storable.Internals Data.ByteString.Internal 来访问原始的构造函数,然后构造一个而不复制数据:

 >让bs = pack [1,2,3] 
> bs
\SOH\STX\ETX
>让sa =(PS ptr 0 n)的情况bs - > StorableArray 0(n-1)n ptr
> :t sa
sa :: StorableArray Int GHC.Word.Word8
> Data.Array.MArray.readArray sa 1
2
> Data.Array.MArray.readArray sa 0
1
> Data.Array.MArray.readArray sa 3
***异常:Ix {Int} .index:Index(3)超出范围((0,2))

(我删除了相当长的提示符 Prelude Data.Array.Storable.Internals Data.ByteString.Internal Data.ByteString> )。



这对于 Data.Vector.Unboxed 不起作用,因为这里数据位于Haskell堆中,由GHC运行时管理,另外两个数据管理Haskell堆外的数据。


What is the best way to convert between Storable.Vector Word8 and a strict ByteString?

Of course a non-copying (no-op) way would be most appreciated.

Should I just unsafeCoerce or is there a library function for that (I couldn't find one)?

Also, will the approach be the same for an Unboxed.Vector Word8?

解决方案

A simple unsafeCoerce will not work, as the layout of the data constructors is different:

data StorableArray i e = StorableArray !i !i Int !(ForeignPtr e)

vs.

data ByteString = PS {-# UNPACK #-} !(ForeignPtr Word8) -- payload
                     {-# UNPACK #-} !Int                -- offset
                     {-# UNPACK #-} !Int                -- length

You can import Data.Array.Storable.Internals and Data.ByteString.Internal to get access to the raw constructors and then construct one out of the other without copying the data:

> let bs = pack [1,2,3]
> bs
"\SOH\STX\ETX"
> let sa = case bs of (PS ptr 0 n) -> StorableArray 0 (n-1) n ptr
> :t sa
sa :: StorableArray Int GHC.Word.Word8
> Data.Array.MArray.readArray sa 1
2
> Data.Array.MArray.readArray sa 0
1
> Data.Array.MArray.readArray sa 3
*** Exception: Ix{Int}.index: Index (3) out of range ((0,2))

(I removed the rather long prompt of Prelude Data.Array.Storable.Internals Data.ByteString.Internal Data.ByteString>).

This will not work for Data.Vector.Unboxed, because here the data is on the Haskell heap and managed by the GHC runtime, while the other two manage the data outside the Haskell heap.

这篇关于如何转换ByteString和Storable Vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆