Revert rename of dph-common for now
[packages/dph.git] / dph-common / Data / Array / Parallel / PArr.hs
1 {-# LANGUAGE ParallelArrays, UnboxedTuples, MagicHash #-}
2 {-# OPTIONS_GHC -funbox-strict-fields #-}
3 {-# OPTIONS_HADDOCK hide #-}
4
5 -- #hide
6 module Data.Array.Parallel.PArr (
7 emptyPArr, replicatePArr, singletonPArr, indexPArr, lengthPArr
8 ) where
9
10 import GHC.ST ( ST(..), runST )
11 import GHC.Base ( Int (I#), MutableArray#, newArray#,
12 unsafeFreezeArray#, indexArray#, {- writeArray# -} )
13 import GHC.PArr -- provides the definition of '[::]'
14
15 emptyPArr :: [:a:]
16 {-# NOINLINE emptyPArr #-}
17 emptyPArr = replicatePArr 0 undefined
18
19 replicatePArr :: Int -> a -> [:a:]
20 {-# NOINLINE replicatePArr #-}
21 replicatePArr n e = runST (do
22 marr# <- newArray n e
23 mkPArr n marr#)
24
25 singletonPArr :: a -> [:a:]
26 {-# NOINLINE singletonPArr #-}
27 singletonPArr e = replicatePArr 1 e
28
29 indexPArr :: [:e:] -> Int -> e
30 {-# NOINLINE indexPArr #-}
31 indexPArr (PArr n arr#) i@(I# i#)
32 | i >= 0 && i < n =
33 case indexArray# arr# i# of (# e #) -> e
34 | otherwise = error $ "indexPArr: out of bounds parallel array index; " ++
35 "idx = " ++ show i ++ ", arr len = "
36 ++ show n
37
38 lengthPArr :: [:a:] -> Int
39 {-# NOINLINE lengthPArr #-}
40 lengthPArr (PArr n _) = n
41
42 -- auxiliary functions
43 -- -------------------
44
45 -- internally used mutable boxed arrays
46 --
47 data MPArr s e = MPArr !Int (MutableArray# s e)
48
49 -- allocate a new mutable array that is pre-initialised with a given value
50 --
51 newArray :: Int -> e -> ST s (MPArr s e)
52 {-# INLINE newArray #-}
53 newArray n@(I# n#) e = ST $ \s1# ->
54 case newArray# n# e s1# of { (# s2#, marr# #) ->
55 (# s2#, MPArr n marr# #)}
56
57 -- convert a mutable array into the external parallel array representation
58 --
59 mkPArr :: Int -> MPArr s e -> ST s [:e:]
60 {-# INLINE mkPArr #-}
61 mkPArr n (MPArr _ marr#) = ST $ \s1# ->
62 case unsafeFreezeArray# marr# s1# of { (# s2#, arr# #) ->
63 (# s2#, PArr n arr# #) }