{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Data.Array.Accelerate.IO.Foreign.ForeignPtr
where
import Data.Array.Accelerate.Array.Data ( ArrayData, GArrayDataR )
import Data.Array.Accelerate.Array.Unique
import Data.Array.Accelerate.Lifetime
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Sugar.Array
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Shape
import qualified Data.Array.Accelerate.Representation.Array as R
import Data.Array.Accelerate.IO.Foreign.Internal
import Foreign.ForeignPtr
import System.IO.Unsafe
type ForeignPtrs e = GArrayDataR ForeignPtr e
{-# INLINE fromForeignPtrs #-}
fromForeignPtrs :: forall sh e. (Shape sh, Elt e) => sh -> ForeignPtrs (EltR e) -> Array sh e
fromForeignPtrs sh fps = Array (R.Array (fromElt sh) (go (eltR @e) fps))
where
go :: TypeR a -> ForeignPtrs a -> ArrayData a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafePerformIO $ newUniqueArray a
{-# INLINE toForeignPtrs #-}
toForeignPtrs :: forall sh e. (Shape sh, Elt e) => Array sh e -> ForeignPtrs (EltR e)
toForeignPtrs (Array (R.Array _ adata)) = go (eltR @e) adata
where
go :: TypeR a -> ArrayData a -> ForeignPtrs a
go TupRunit () = ()
go (TupRpair aR1 aR2) (a1, a2) = (go aR1 a1, go aR2 a2)
go (TupRsingle t) a
| ScalarArrayDict{} <- scalarArrayDict t
= unsafeGetValue (uniqueArrayData a)