haskell / haskell/bytestring

byteArrayToByteString, and byteStringToByteArray?

Open
#186 5 comments 1 reaction 0 assignees View on GitHub
enhancement
Dominant language
Haskell
Stars
301
Forks
144
Avg merge
7d 22h
Merged PRs (30d)
1

Description

i find myself using the following more often now:

```haskell
unsafeByteArrayToByteString :: ByteArray -> ByteString
unsafeByteArrayToByteString (ByteArray b#) =
let addr# = byteArrayContents# b#
fp = ForeignPtr addr# (PlainPtr (unsafeCoerce# b#))
len = I# (sizeofByteArray# b#)
in PS fp 0 len

byteArrayToByteString :: ByteArray -> ByteString
byteArrayToByteString b@(ByteArray b#)
| isTrue# (isByteArrayPinned# b#) = unsafeByteArrayToByteString b
| otherwise = runST $ do
let len = sizeofByteArray b
marr@(MutableByteArray marr#) <- newPinnedByteArray len
copyByteArray marr 0 b 0 len
let addr# = byteArrayContents# (unsafeCoerce# marr#)
let fp = ForeignPtr addr# (PlainPtr (unsafeCoerce# marr#))
pure (PS fp 0 len)

byteStringToByteArray :: ByteString -> ByteArray
byteStringToByteArray (PS fp off len) =
accursedUnutterablePerformIO $
withForeignPtr fp $ \ptr -> do
marr <- newByteArray len
copyPtrToMutableByteArray (ptr `plusPtr` off) marr 0 len
unsafeFreezeByteArray marr
```

is it possible that these could be added somewhere? i work with ByteArray a lot more than i do bytestring, but there are places where ByteString is necessary because of other apis (aeson, binary, etc.)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.