Skip to content

byteArrayToByteString, and byteStringToByteArray? #186

@chessai

Description

@chessai

i find myself using the following more often now:

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.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions