Skip to content

Commit

Permalink
Add byteArrayAsForeignPtr
Browse files Browse the repository at this point in the history
  • Loading branch information
sol committed Nov 4, 2023
1 parent 0b64fae commit 6f7ed08
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
9 changes: 9 additions & 0 deletions Data/Primitive/ByteArray.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ module Data.Primitive.ByteArray (
#if __GLASGOW_HASKELL__ >= 802
isByteArrayPinned, isMutableByteArrayPinned,
#endif
byteArrayAsForeignPtr,
byteArrayContents,
withByteArrayContents,
mutableByteArrayContents,
Expand All @@ -84,6 +85,7 @@ import Data.Word ( Word8 )
import qualified GHC.Exts as Exts
#endif
import GHC.Exts hiding (setByteArray#)
import GHC.ForeignPtr (ForeignPtr(..), ForeignPtrContents(..))

#if __GLASGOW_HASKELL__ < 804
import System.IO.Unsafe (unsafeDupablePerformIO)
Expand Down Expand Up @@ -128,6 +130,13 @@ newAlignedPinnedByteArray (I# n#) (I# k#)
= primitive (\s# -> case newAlignedPinnedByteArray# n# k# s# of
(# s'#, arr# #) -> (# s'#, MutableByteArray arr# #))

-- | Create a foreign pointer that points to the array's data. This operation
-- is only safe on /pinned/ byte arrays. The array's data is not garbage
-- collected while references to the foreign pointer exist.
byteArrayAsForeignPtr :: ByteArray -> ForeignPtr Word8
{-# INLINE byteArrayAsForeignPtr #-}
byteArrayAsForeignPtr (ByteArray arr#) = ForeignPtr (byteArrayContents# arr#) (PlainPtr (unsafeCoerce# arr#))

-- | Yield a pointer to the array's data. This operation is only safe on
-- /pinned/ byte arrays. Byte arrays allocated by 'newPinnedByteArray' and
-- 'newAlignedPinnedByteArray' are guaranteed to be pinned. Byte arrays
Expand Down
3 changes: 3 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## Changes in version 0.9.1.0
* Add `byteArrayAsForeignPtr`.

## Changes in version 0.9.0.0

* Add `withByteArrayContents`, `withMutableByteArrayContents`,
Expand Down
2 changes: 1 addition & 1 deletion primitive.cabal
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Cabal-Version: 2.0
Name: primitive
Version: 0.9.0.0
Version: 0.9.1.0
License: BSD3
License-File: LICENSE

Expand Down

0 comments on commit 6f7ed08

Please sign in to comment.