Skip to content

Commit

Permalink
Use fromPtrN in unsafeFromForeignPtr and make it monadic in nature
Browse files Browse the repository at this point in the history
  • Loading branch information
adithyaov committed Oct 11, 2024
1 parent 6b0238f commit e005881
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 15 deletions.
14 changes: 5 additions & 9 deletions core/src/Streamly/Internal/Data/Array/Type.hs
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,9 @@ import GHC.Base (build)
import GHC.Exts (IsList, IsString(..), Addr#, minusAddr#)
import GHC.Int (Int(..))
import GHC.ForeignPtr (ForeignPtr(..), ForeignPtrContents(..))
import Foreign.Storable (peek)

import GHC.IO (unsafePerformIO)
import GHC.Ptr (Ptr(..), plusPtr, nullPtr)
import GHC.Ptr (Ptr(..), nullPtr)
import Streamly.Internal.Data.Producer.Type (Producer(..))
import Streamly.Internal.Data.MutArray.Type (MutArray(..))
import Streamly.Internal.Data.MutByteArray.Type (MutByteArray)
Expand Down Expand Up @@ -308,17 +307,14 @@ mutableByteArrayContents# x = Exts.byteArrayContents# (Exts.unsafeCoerce# x)
-- | @unsafeFromForeignPtr fptr len@ converts the "ForeignPtr" to an "Array".
--
unsafeFromForeignPtr
:: ForeignPtr Word8 -> Int -> Array Word8
:: MonadIO m => ForeignPtr Word8 -> Int -> m (Array Word8)
unsafeFromForeignPtr (ForeignPtr addr# _) i
| Ptr addr# == nullPtr || i == 0 = empty
| Ptr addr# == nullPtr || i == 0 = pure empty
unsafeFromForeignPtr (ForeignPtr addr# (PlainPtr marr#)) len =
let off = I# (addr# `minusAddr#` mutableByteArrayContents# marr#)
in Array (Unboxed.MutByteArray marr#) off (off + len)
in pure (Array (Unboxed.MutByteArray marr#) off (off + len))
unsafeFromForeignPtr (ForeignPtr addr# _) len =
unsafeInlineIO
$ fromStreamN len
$ D.mapM (peek . plusPtr (Ptr addr#))
$ D.fromList [0,1..(len - 1)]
fromPtrN len (Ptr addr#)

{-# DEPRECATED asPtrUnsafe "Please use unsafePinnedAsPtr instead." #-}
{-# INLINE asPtrUnsafe #-}
Expand Down
8 changes: 2 additions & 6 deletions test/Streamly/Test/Data/Array.hs
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,7 @@ testForeignPtrConversionId :: IO ()
testForeignPtrConversionId = do
arr0 <- MA.unsafeGetSlice 10 50 <$> MA.fromList ([0 .. 99] :: [Word8])
let arr = A.unsafeFreeze arr0
arr1 <-
A.unsafeAsForeignPtr
arr
(\fptr len -> pure $ A.unsafeFromForeignPtr fptr len)
arr1 <- A.unsafeAsForeignPtr arr A.unsafeFromForeignPtr
arr1 `shouldBe` arr

testUnsafeFromForeignPtr :: IO ()
Expand All @@ -239,8 +236,7 @@ testUnsafeFromForeignPtr = do
A.unsafePinnedAsPtr arr $ \ptr len -> do
fptr <- newForeignPtr_ ptr
performMajorGC
let arr1 = A.unsafeFromForeignPtr fptr len
arr1 `shouldBe` arr
A.unsafeFromForeignPtr fptr len `shouldReturn` arr

reallocMA :: Property
reallocMA =
Expand Down

0 comments on commit e005881

Please sign in to comment.