From 6f7ed089017205be016acdb8a633cca76de1355d Mon Sep 17 00:00:00 2001 From: Simon Hengel Date: Sat, 4 Nov 2023 22:55:26 +0700 Subject: [PATCH] Add `byteArrayAsForeignPtr` --- Data/Primitive/ByteArray.hs | 9 +++++++++ changelog.md | 3 +++ primitive.cabal | 2 +- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Data/Primitive/ByteArray.hs b/Data/Primitive/ByteArray.hs index 03d81a9..25daddb 100644 --- a/Data/Primitive/ByteArray.hs +++ b/Data/Primitive/ByteArray.hs @@ -62,6 +62,7 @@ module Data.Primitive.ByteArray ( #if __GLASGOW_HASKELL__ >= 802 isByteArrayPinned, isMutableByteArrayPinned, #endif + byteArrayAsForeignPtr, byteArrayContents, withByteArrayContents, mutableByteArrayContents, @@ -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) @@ -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 diff --git a/changelog.md b/changelog.md index 3b96aff..bdcd77d 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,6 @@ +## Changes in version 0.9.1.0 + * Add `byteArrayAsForeignPtr`. + ## Changes in version 0.9.0.0 * Add `withByteArrayContents`, `withMutableByteArrayContents`, diff --git a/primitive.cabal b/primitive.cabal index 57ecfe9..22c9e35 100644 --- a/primitive.cabal +++ b/primitive.cabal @@ -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