Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add byteArrayAsForeignPtr #402

Merged
merged 1 commit into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading